File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1446: download - view: text, annotated - select for diffs
Fri Apr 9 02:01:11 2021 UTC (3 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Remove extra closing brace added in rev. 1.1444

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1446 2021/04/09 02:01:11 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use Net::CIDR;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: use LONCAPA::LWPReq;
  105: use LONCAPA::transliterate;
  106: 
  107: use File::Copy;
  108: 
  109: my $readit;
  110: my $max_connection_retries = 20;     # Or some such value.
  111: 
  112: require Exporter;
  113: 
  114: our @ISA = qw (Exporter);
  115: our @EXPORT = qw(%env);
  116: 
  117: 
  118: # ------------------------------------ Logging (parameters, docs, slots, roles)
  119: {
  120:     my $logid;
  121:     sub write_log {
  122: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  123:         if ($context eq 'course') {
  124:             if (($cnum eq '') || ($cdom eq '')) {
  125:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  126:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  127:             }
  128:         }
  129: 	$logid ++;
  130:         my $now = time();
  131: 	my $id=$now.'00000'.$$.'00000'.$logid;
  132:         my $ip = &get_requestor_ip();
  133:         my $logentry = { 
  134:                           $id => {
  135:                                    'exe_uname' => $env{'user.name'},
  136:                                    'exe_udom'  => $env{'user.domain'},
  137:                                    'exe_time'  => $now,
  138:                                    'exe_ip'    => $ip,
  139:                                    'delflag'   => $delflag,
  140:                                    'logentry'  => $storehash,
  141:                                    'uname'     => $uname,
  142:                                    'udom'      => $udom,
  143:                                   }
  144:                        };
  145: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  146:     }
  147: }
  148: 
  149: sub logtouch {
  150:     my $execdir=$perlvar{'lonDaemons'};
  151:     unless (-e "$execdir/logs/lonnet.log") {	
  152: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  153: 	close $fh;
  154:     }
  155:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  156:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  157: }
  158: 
  159: sub logthis {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  165: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  166: 	print $fh $logstring;
  167: 	close($fh);
  168:     }
  169:     return 1;
  170: }
  171: 
  172: sub logperm {
  173:     my $message=shift;
  174:     my $execdir=$perlvar{'lonDaemons'};
  175:     my $now=time;
  176:     my $local=localtime($now);
  177:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  178: 	print $fh "$now:$message:$local\n";
  179: 	close($fh);
  180:     }
  181:     return 1;
  182: }
  183: 
  184: sub create_connection {
  185:     my ($hostname,$lonid) = @_;
  186:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  187: 				     Type    => SOCK_STREAM,
  188: 				     Timeout => 10);
  189:     return 0 if (!$client);
  190:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  191:     my $result = <$client>;
  192:     chomp($result);
  193:     return 1 if ($result eq 'done');
  194:     return 0;
  195: }
  196: 
  197: sub get_server_timezone {
  198:     my ($cnum,$cdom) = @_;
  199:     my $home=&homeserver($cnum,$cdom);
  200:     if ($home ne 'no_host') {
  201:         my $cachetime = 24*3600;
  202:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  203:         if (defined($cached)) {
  204:             return $timezone;
  205:         } else {
  206:             my $timezone = &reply('servertimezone',$home);
  207:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  208:         }
  209:     }
  210: }
  211: 
  212: sub get_server_distarch {
  213:     my ($lonhost,$ignore_cache) = @_;
  214:     if (defined($lonhost)) {
  215:         if (!defined(&hostname($lonhost))) {
  216:             return;
  217:         }
  218:         my $cachetime = 12*3600;
  219:         if (!$ignore_cache) {
  220:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  221:             if (defined($cached)) {
  222:                 return $distarch;
  223:             }
  224:         }
  225:         my $rep = &reply('serverdistarch',$lonhost);
  226:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  227:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  228:                 $rep eq '') {
  229:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  230:         }
  231:     }
  232:     return;
  233: }
  234: 
  235: sub get_servercerts_info {
  236:     my ($lonhost,$hostname,$context) = @_;
  237:     return if ($lonhost eq '');
  238:     if ($hostname eq '') {
  239:         $hostname = &hostname($lonhost);
  240:     }
  241:     return if ($hostname eq '');
  242:     my ($rep,$uselocal);
  243:     if ($context eq 'install') {
  244:         $uselocal = 1;
  245:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  246:         $uselocal = 1;
  247:     }
  248:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  249:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  250:         if ($distro eq '') {
  251:             $uselocal = 0;
  252:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  253:             if ($1 < 6) {
  254:                 $uselocal = 0;
  255:             }
  256:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  257:             if ($1 < 12) {
  258:                 $uselocal = 0;
  259:             }
  260:         }
  261:     }
  262:     if ($uselocal) {
  263:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  264:     } else {
  265:         $rep=&reply('servercerts',$lonhost);
  266:     }
  267:     my ($result,%returnhash);
  268:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  269:         ($rep eq 'unknown_cmd')) {
  270:         $result = $rep;
  271:     } else {
  272:         $result = 'ok';
  273:         my @pairs=split(/\&/,$rep);
  274:         foreach my $item (@pairs) {
  275:             my ($key,$value)=split(/=/,$item,2);
  276:             my $what = &unescape($key);
  277:             $returnhash{$what}=&thaw_unescape($value);
  278:         }
  279:     }
  280:     return ($result,\%returnhash);
  281: }
  282: 
  283: sub get_server_loncaparev {
  284:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  285:     if (defined($lonhost)) {
  286:         if (!defined(&hostname($lonhost))) {
  287:             undef($lonhost);
  288:         }
  289:     }
  290:     if (!defined($lonhost)) {
  291:         if (defined(&domain($dom,'primary'))) {
  292:             $lonhost=&domain($dom,'primary');
  293:             if ($lonhost eq 'no_host') {
  294:                 undef($lonhost);
  295:             }
  296:         }
  297:     }
  298:     if (defined($lonhost)) {
  299:         my $cachetime = 12*3600;
  300:         if (!$ignore_cache) {
  301:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  302:             if (defined($cached)) {
  303:                 return $loncaparev;
  304:             }
  305:         }
  306:         my ($answer,$loncaparev);
  307:         my @ids=&current_machine_ids();
  308:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  309:             $answer = $perlvar{'lonVersion'};
  310:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  311:                 $loncaparev = $1;
  312:             }
  313:         } else {
  314:             $answer = &reply('serverloncaparev',$lonhost);
  315:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  316:                 if ($caller eq 'loncron') {
  317:                     my $hostname = &hostname($lonhost);
  318:                     my $protocol = $protocol{$lonhost};
  319:                     $protocol = 'http' if ($protocol ne 'https');
  320:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  321:                     my $request=new HTTP::Request('GET',$url);
  322:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  323:                     unless ($response->is_error()) {
  324:                         my $content = $response->content;
  325:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  326:                             $loncaparev = $1;
  327:                         }
  328:                     }
  329:                 } else {
  330:                     $loncaparev = $loncaparevs{$lonhost};
  331:                 }
  332:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  333:                 $loncaparev = $1;
  334:             }
  335:         }
  336:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  337:     }
  338: }
  339: 
  340: sub get_server_homeID {
  341:     my ($hostname,$ignore_cache,$caller) = @_;
  342:     unless ($ignore_cache) {
  343:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  344:         if (defined($cached)) {
  345:             return $serverhomeID;
  346:         }
  347:     }
  348:     my $cachetime = 12*3600;
  349:     my $serverhomeID;
  350:     if ($caller eq 'loncron') { 
  351:         my @machine_ids = &machine_ids($hostname);
  352:         foreach my $id (@machine_ids) {
  353:             my $response = &reply('serverhomeID',$id);
  354:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  355:                 $serverhomeID = $response;
  356:                 last;
  357:             }
  358:         }
  359:         if ($serverhomeID eq '') {
  360:             $serverhomeID = $machine_ids[-1];
  361:         }
  362:     } else {
  363:         $serverhomeID = $serverhomeIDs{$hostname};
  364:     }
  365:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  366: }
  367: 
  368: sub get_remote_globals {
  369:     my ($lonhost,$whathash,$ignore_cache) = @_;
  370:     my ($result,%returnhash,%whatneeded);
  371:     if (ref($whathash) eq 'HASH') {
  372:         foreach my $what (sort(keys(%{$whathash}))) {
  373:             my $hashid = $lonhost.'-'.$what;
  374:             my ($response,$cached);
  375:             unless ($ignore_cache) {
  376:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  377:             }
  378:             if (defined($cached)) {
  379:                 $returnhash{$what} = $response;
  380:             } else {
  381:                 $whatneeded{$what} = 1;
  382:             }
  383:         }
  384:         if (keys(%whatneeded) == 0) {
  385:             $result = 'ok';
  386:         } else {
  387:             my $requested = &freeze_escape(\%whatneeded);
  388:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  389:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  390:                 ($rep eq 'unknown_cmd')) {
  391:                 $result = $rep;
  392:             } else {
  393:                 $result = 'ok';
  394:                 my @pairs=split(/\&/,$rep);
  395:                 foreach my $item (@pairs) {
  396:                     my ($key,$value)=split(/=/,$item,2);
  397:                     my $what = &unescape($key);
  398:                     my $hashid = $lonhost.'-'.$what;
  399:                     $returnhash{$what}=&thaw_unescape($value);
  400:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  401:                 }
  402:             }
  403:         }
  404:     }
  405:     return ($result,\%returnhash);
  406: }
  407: 
  408: sub remote_devalidate_cache {
  409:     my ($lonhost,$cachekeys) = @_;
  410:     my $items;
  411:     return unless (ref($cachekeys) eq 'ARRAY');
  412:     my $cachestr = join('&',@{$cachekeys});
  413:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  414:     return $response;
  415: }
  416: 
  417: # -------------------------------------------------- Non-critical communication
  418: sub subreply {
  419:     my ($cmd,$server)=@_;
  420:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  421:     #
  422:     #  With loncnew process trimming, there's a timing hole between lonc server
  423:     #  process exit and the master server picking up the listen on the AF_UNIX
  424:     #  socket.  In that time interval, a lock file will exist:
  425: 
  426:     my $lockfile=$peerfile.".lock";
  427:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  428: 	sleep(0.1);
  429:     }
  430:     # At this point, either a loncnew parent is listening or an old lonc
  431:     # or loncnew child is listening so we can connect or everything's dead.
  432:     #
  433:     #   We'll give the connection a few tries before abandoning it.  If
  434:     #   connection is not possible, we'll con_lost back to the client.
  435:     #   
  436:     my $client;
  437:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  438: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  439: 				      Type    => SOCK_STREAM,
  440: 				      Timeout => 10);
  441: 	if ($client) {
  442: 	    last;		# Connected!
  443: 	} else {
  444: 	    &create_connection(&hostname($server),$server);
  445: 	}
  446:         sleep(0.1);	# Try again later if failed connection.
  447:     }
  448:     my $answer;
  449:     if ($client) {
  450: 	print $client "sethost:$server:$cmd\n";
  451: 	$answer=<$client>;
  452: 	if (!$answer) { $answer="con_lost"; }
  453: 	chomp($answer);
  454:     } else {
  455: 	$answer = 'con_lost';	# Failed connection.
  456:     }
  457:     return $answer;
  458: }
  459: 
  460: sub reply {
  461:     my ($cmd,$server)=@_;
  462:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  463:     my $answer=subreply($cmd,$server);
  464:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  465:         my $logged = $cmd;
  466:         if ($cmd =~ /^encrypt:([^:]+):/) {
  467:             my $subcmd = $1;
  468:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  469:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  470:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  471:                 (undef,undef,my @rest) = split(/:/,$cmd);
  472:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  473:                     splice(@rest,2,1,'Hidden');
  474:                 } elsif ($subcmd eq 'passwd') {
  475:                     splice(@rest,2,2,('Hidden','Hidden'));
  476:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  477:                          ($subcmd eq 'autoexportgrades')) {
  478:                     splice(@rest,3,1,'Hidden');
  479:                 }
  480:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  481:             }
  482:         }
  483:         &logthis("<font color=\"blue\">WARNING:".
  484:                  " $logged to $server returned $answer</font>");
  485:     }
  486:     return $answer;
  487: }
  488: 
  489: # ----------------------------------------------------------- Send USR1 to lonc
  490: 
  491: sub reconlonc {
  492:     my ($lonid) = @_;
  493:     if ($lonid) {
  494:         my $hostname = &hostname($lonid);
  495: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  496: 	if ($hostname && -e $peerfile) {
  497: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  498: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  499: 					     Type    => SOCK_STREAM,
  500: 					     Timeout => 10);
  501: 	    if ($client) {
  502: 		print $client ("reset_retries\n");
  503: 		my $answer=<$client>;
  504: 		#reset just this one.
  505: 	    }
  506: 	}
  507: 	return;
  508:     }
  509: 
  510:     &logthis("Trying to reconnect lonc");
  511:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  512:     if (open(my $fh,"<",$loncfile)) {
  513: 	my $loncpid=<$fh>;
  514:         chomp($loncpid);
  515:         if (kill 0 => $loncpid) {
  516: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  517:             kill USR1 => $loncpid;
  518:             sleep 1;
  519:         } else {
  520: 	    &logthis(
  521:                "<font color=\"blue\">WARNING:".
  522:                " lonc at pid $loncpid not responding, giving up</font>");
  523:         }
  524:     } else {
  525: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  526:     }
  527: }
  528: 
  529: # ------------------------------------------------------ Critical communication
  530: 
  531: sub critical {
  532:     my ($cmd,$server)=@_;
  533:     unless (&hostname($server)) {
  534:         &logthis("<font color=\"blue\">WARNING:".
  535:                " Critical message to unknown server ($server)</font>");
  536:         return 'no_such_host';
  537:     }
  538:     my $answer=reply($cmd,$server);
  539:     if ($answer eq 'con_lost') {
  540: 	&reconlonc($server);
  541: 	my $answer=reply($cmd,$server);
  542:         if ($answer eq 'con_lost') {
  543:             my $now=time;
  544:             my $middlename=$cmd;
  545:             $middlename=substr($middlename,0,16);
  546:             $middlename=~s/\W//g;
  547:             my $dfilename=
  548:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  549:             $dumpcount++;
  550:             {
  551: 		my $dfh;
  552: 		if (open($dfh,">",$dfilename)) {
  553: 		    print $dfh "$cmd\n"; 
  554: 		    close($dfh);
  555: 		}
  556:             }
  557:             sleep 1;
  558:             my $wcmd='';
  559:             {
  560: 		my $dfh;
  561: 		if (open($dfh,"<",$dfilename)) {
  562: 		    $wcmd=<$dfh>; 
  563: 		    close($dfh);
  564: 		}
  565:             }
  566:             chomp($wcmd);
  567:             if ($wcmd eq $cmd) {
  568: 		&logthis("<font color=\"blue\">WARNING: ".
  569:                          "Connection buffer $dfilename: $cmd</font>");
  570:                 &logperm("D:$server:$cmd");
  571: 	        return 'con_delayed';
  572:             } else {
  573:                 &logthis("<font color=\"red\">CRITICAL:"
  574:                         ." Critical connection failed: $server $cmd</font>");
  575:                 &logperm("F:$server:$cmd");
  576:                 return 'con_failed';
  577:             }
  578:         }
  579:     }
  580:     return $answer;
  581: }
  582: 
  583: # ------------------------------------------- check if return value is an error
  584: 
  585: sub error {
  586:     my ($result) = @_;
  587:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  588: 	if ($2 == 2) { return undef; }
  589: 	return $1;
  590:     }
  591:     return undef;
  592: }
  593: 
  594: sub convert_and_load_session_env {
  595:     my ($lonidsdir,$handle)=@_;
  596:     my @profile;
  597:     {
  598: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  599: 	if (!$opened) {
  600: 	    return 0;
  601: 	}
  602: 	flock($idf,LOCK_SH);
  603: 	@profile=<$idf>;
  604: 	close($idf);
  605:     }
  606:     my %temp_env;
  607:     foreach my $line (@profile) {
  608: 	if ($line !~ m/=/) {
  609: 	    return 0;
  610: 	}
  611: 	chomp($line);
  612: 	my ($envname,$envvalue)=split(/=/,$line,2);
  613: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  614:     }
  615:     unlink("$lonidsdir/$handle.id");
  616:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  617: 	    0640)) {
  618: 	%disk_env = %temp_env;
  619: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  620: 	untie(%disk_env);
  621:     }
  622:     return 1;
  623: }
  624: 
  625: # ------------------------------------------- Transfer profile into environment
  626: my $env_loaded;
  627: sub transfer_profile_to_env {
  628:     my ($lonidsdir,$handle,$force_transfer) = @_;
  629:     if (!$force_transfer && $env_loaded) { return; } 
  630: 
  631:     if (!defined($lonidsdir)) {
  632: 	$lonidsdir = $perlvar{'lonIDsDir'};
  633:     }
  634:     if (!defined($handle)) {
  635:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  636:     }
  637: 
  638:     my $convert;
  639:     {
  640:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  641: 	if (!$opened) {
  642: 	    return;
  643: 	}
  644: 	flock($idf,LOCK_SH);
  645: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  646: 		&GDBM_READER(),0640)) {
  647: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  648: 	    untie(%disk_env);
  649: 	} else {
  650: 	    $convert = 1;
  651: 	}
  652:     }
  653:     if ($convert) {
  654: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  655: 	    &logthis("Failed to load session, or convert session.");
  656: 	}
  657:     }
  658: 
  659:     my %remove;
  660:     while ( my $envname = each(%env) ) {
  661:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  662:             if ($time < time-300) {
  663:                 $remove{$key}++;
  664:             }
  665:         }
  666:     }
  667: 
  668:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  669:     $env_loaded=1;
  670:     foreach my $expired_key (keys(%remove)) {
  671:         &delenv($expired_key);
  672:     }
  673: }
  674: 
  675: # ---------------------------------------------------- Check for valid session 
  676: sub check_for_valid_session {
  677:     my ($r,$name,$userhashref,$domref) = @_;
  678:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  679:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  680:     if ($name eq 'lonDAV') {
  681:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  682:     } else {
  683:         $lonidsdir=$r->dir_config('lonIDsDir');
  684:         if ($name eq '') {
  685:             $name = 'lonID';
  686:         }
  687:     }
  688:     if ($name eq 'lonID') {
  689:         $secure = 'lonSID';
  690:         $linkname = 'lonLinkID';
  691:         $pubname = 'lonPubID';
  692:         if (exists($cookies{$secure})) {
  693:             $lonid=$cookies{$secure};
  694:         } elsif (exists($cookies{$name})) {
  695:             $lonid=$cookies{$name};
  696:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  697:             $lonid=$cookies{$linkname};
  698:         } elsif (exists($cookies{$pubname})) {
  699:             $lonid=$cookies{$pubname};
  700:         }
  701:     } else {
  702:         $lonid=$cookies{$name};
  703:     }
  704:     return undef if (!$lonid);
  705: 
  706:     my $handle=&LONCAPA::clean_handle($lonid->value);
  707:     if (-l "$lonidsdir/$handle.id") {
  708:         my $link = readlink("$lonidsdir/$handle.id");
  709:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  710:             $handle = $1;
  711:         }
  712:     }
  713:     if (!-e "$lonidsdir/$handle.id") {
  714:         if ((ref($domref)) && ($name eq 'lonID') && 
  715:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  716:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  717:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  718:                 $$domref = $possudom;
  719:             }
  720:         }
  721:         return undef;
  722:     }
  723: 
  724:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  725:     return undef if (!$opened);
  726: 
  727:     flock($idf,LOCK_SH);
  728:     my %disk_env;
  729:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  730: 	    &GDBM_READER(),0640)) {
  731: 	return undef;	
  732:     }
  733: 
  734:     if (!defined($disk_env{'user.name'})
  735: 	|| !defined($disk_env{'user.domain'})) {
  736:         untie(%disk_env);
  737: 	return undef;
  738:     }
  739: 
  740:     if (ref($userhashref) eq 'HASH') {
  741:         $userhashref->{'name'} = $disk_env{'user.name'};
  742:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  743:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  744:         if ($userhashref->{'lti'}) {
  745:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  746:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  747:         }
  748:     }
  749:     untie(%disk_env);
  750: 
  751:     return $handle;
  752: }
  753: 
  754: sub timed_flock {
  755:     my ($file,$lock_type) = @_;
  756:     my $failed=0;
  757:     eval {
  758: 	local $SIG{__DIE__}='DEFAULT';
  759: 	local $SIG{ALRM}=sub {
  760: 	    $failed=1;
  761: 	    die("failed lock");
  762: 	};
  763: 	alarm(13);
  764: 	flock($file,$lock_type);
  765: 	alarm(0);
  766:     };
  767:     if ($failed) {
  768: 	return undef;
  769:     } else {
  770: 	return 1;
  771:     }
  772: }
  773: 
  774: sub get_sessionfile_vars {
  775:     my ($handle,$lonidsdir,$storearr) = @_;
  776:     my %returnhash;
  777:     unless (ref($storearr) eq 'ARRAY') {
  778:         return %returnhash;
  779:     }
  780:     if (-l "$lonidsdir/$handle.id") {
  781:         my $link = readlink("$lonidsdir/$handle.id");
  782:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  783:             $handle = $1;
  784:         }
  785:     }
  786:     if ((-e "$lonidsdir/$handle.id") &&
  787:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  788:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  789:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  790:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  791:                 flock($idf,LOCK_SH);
  792:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  793:                         &GDBM_READER(),0640)) {
  794:                     foreach my $item (@{$storearr}) {
  795:                         $returnhash{$item} = $disk_env{$item};
  796:                     }
  797:                     untie(%disk_env);
  798:                 }
  799:             }
  800:         }
  801:     }
  802:     return %returnhash;
  803: }
  804: 
  805: # ---------------------------------------------------------- Append Environment
  806: 
  807: sub appenv {
  808:     my ($newenv,$roles) = @_;
  809:     if (ref($newenv) eq 'HASH') {
  810:         foreach my $key (keys(%{$newenv})) {
  811:             my $refused = 0;
  812: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  813:                 $refused = 1;
  814:                 if (ref($roles) eq 'ARRAY') {
  815:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  816:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  817:                         $refused = 0;
  818:                     }
  819:                 }
  820:             }
  821:             if ($refused) {
  822:                 &logthis("<font color=\"blue\">WARNING: ".
  823:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  824:                          .'</font>');
  825: 	        delete($newenv->{$key});
  826:             } else {
  827:                 $env{$key}=$newenv->{$key};
  828:             }
  829:         }
  830:         my $lonids = $perlvar{'lonIDsDir'};
  831:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  832:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  833:             if ($opened
  834: 	        && &timed_flock($env_file,LOCK_EX)
  835: 	        &&
  836: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  837: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  838: 	        while (my ($key,$value) = each(%{$newenv})) {
  839: 	            $disk_env{$key} = $value;
  840: 	        }
  841: 	        untie(%disk_env);
  842:             }
  843:         }
  844:     }
  845:     return 'ok';
  846: }
  847: # ----------------------------------------------------- Delete from Environment
  848: 
  849: sub delenv {
  850:     my ($delthis,$regexp,$roles) = @_;
  851:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  852:         my $refused = 1;
  853:         if (ref($roles) eq 'ARRAY') {
  854:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  855:             if (grep(/^\Q$role\E$/,@{$roles})) {
  856:                 $refused = 0;
  857:             }
  858:         }
  859:         if ($refused) {
  860:             &logthis("<font color=\"blue\">WARNING: ".
  861:                      "Attempt to delete from environment ".$delthis);
  862:             return 'error';
  863:         }
  864:     }
  865:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  866:     if ($opened
  867: 	&& &timed_flock($env_file,LOCK_EX)
  868: 	&&
  869: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  870: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  871: 	foreach my $key (keys(%disk_env)) {
  872: 	    if ($regexp) {
  873:                 if ($key=~/^$delthis/) {
  874:                     delete($env{$key});
  875:                     delete($disk_env{$key});
  876:                 } 
  877:             } else {
  878:                 if ($key=~/^\Q$delthis\E/) {
  879: 		    delete($env{$key});
  880: 		    delete($disk_env{$key});
  881: 	        }
  882:             }
  883: 	}
  884: 	untie(%disk_env);
  885:     }
  886:     return 'ok';
  887: }
  888: 
  889: sub get_env_multiple {
  890:     my ($name) = @_;
  891:     my @values;
  892:     if (defined($env{$name})) {
  893:         # exists is it an array
  894:         if (ref($env{$name})) {
  895:             @values=@{ $env{$name} };
  896:         } else {
  897:             $values[0]=$env{$name};
  898:         }
  899:     }
  900:     return(@values);
  901: }
  902: 
  903: # ------------------------------------------------------------------- Locking
  904: 
  905: sub set_lock {
  906:     my ($text)=@_;
  907:     $locknum++;
  908:     my $id=$$.'-'.$locknum;
  909:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  910:              'session.lock.'.$id => $text});
  911:     return $id;
  912: }
  913: 
  914: sub get_locks {
  915:     my $num=0;
  916:     my %texts=();
  917:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  918:        if ($lock=~/\w/) {
  919:           $num++;
  920:           $texts{$lock}=$env{'session.lock.'.$lock};
  921:        }
  922:    }
  923:    return ($num,%texts);
  924: }
  925: 
  926: sub remove_lock {
  927:     my ($id)=@_;
  928:     my $newlocks='';
  929:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  930:        if (($lock=~/\w/) && ($lock ne $id)) {
  931:           $newlocks.=','.$lock;
  932:        }
  933:     }
  934:     &appenv({'session.locks' => $newlocks});
  935:     &delenv('session.lock.'.$id);
  936: }
  937: 
  938: sub remove_all_locks {
  939:     my $activelocks=$env{'session.locks'};
  940:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  941:        if ($lock=~/\w/) {
  942:           &remove_lock($lock);
  943:        }
  944:     }
  945: }
  946: 
  947: 
  948: # ------------------------------------------ Find out current server userload
  949: sub userload {
  950:     my $numusers=0;
  951:     {
  952: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  953: 	my $filename;
  954: 	my $curtime=time;
  955: 	while ($filename=readdir(LONIDS)) {
  956: 	    next if ($filename eq '.' || $filename eq '..');
  957: 	    next if ($filename =~ /publicuser_\d+\.id/);
  958:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  959: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  960: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  961: 	}
  962: 	closedir(LONIDS);
  963:     }
  964:     my $userloadpercent=0;
  965:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  966:     if ($maxuserload) {
  967: 	$userloadpercent=100*$numusers/$maxuserload;
  968:     }
  969:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  970:     return $userloadpercent;
  971: }
  972: 
  973: # ------------------------------ Find server with least workload from spare.tab
  974: 
  975: sub spareserver {
  976:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  977:     my $spare_server;
  978:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  979:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  980:                                                      :  $userloadpercent;
  981:     my ($uint_dom,$remotesessions);
  982:     if (($udom ne '') && (&domain($udom) ne '')) {
  983:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  984:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  985:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  986:         $remotesessions = $udomdefaults{'remotesessions'};
  987:     }
  988:     my $spareshash = &this_host_spares($udom);
  989:     if (ref($spareshash) eq 'HASH') {
  990:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  991:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  992:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  993:                                              $try_server));
  994: 	        ($spare_server, $lowest_load) =
  995: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  996:             }
  997:         }
  998: 
  999:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1000: 
 1001:         if (!$found_server) {
 1002:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1003: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1004:                     next unless (&spare_can_host($udom,$uint_dom,
 1005:                                                  $remotesessions,$try_server));
 1006: 	            ($spare_server, $lowest_load) =
 1007: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1008:                 }
 1009: 	    }
 1010:         }
 1011:     }
 1012: 
 1013:     if (!$want_server_name) {
 1014:         if (defined($spare_server)) {
 1015:             my $hostname = &hostname($spare_server);
 1016:             if (defined($hostname)) {
 1017:                 my $protocol = 'http';
 1018:                 if ($protocol{$spare_server} eq 'https') {
 1019:                     $protocol = $protocol{$spare_server};
 1020:                 }
 1021: 	        $spare_server = $protocol.'://'.$hostname;
 1022:             }
 1023:         }
 1024:     }
 1025:     return $spare_server;
 1026: }
 1027: 
 1028: sub compare_server_load {
 1029:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1030: 
 1031:     if ($required) {
 1032:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1033:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1034:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1035:         if (($major eq '' && $minor eq '') ||
 1036:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1037:             return ($spare_server,$lowest_load);
 1038:         }
 1039:     }
 1040: 
 1041:     my $loadans     = &reply('load',    $try_server);
 1042:     my $userloadans = &reply('userload',$try_server);
 1043: 
 1044:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1045: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1046:     }
 1047: 
 1048:     my $load;
 1049:     if ($loadans =~ /\d/) {
 1050: 	if ($userloadans =~ /\d/) {
 1051: 	    #both are numbers, pick the bigger one
 1052: 	    $load = ($loadans > $userloadans) ? $loadans 
 1053: 		                              : $userloadans;
 1054: 	} else {
 1055: 	    $load = $loadans;
 1056: 	}
 1057:     } else {
 1058: 	$load = $userloadans;
 1059:     }
 1060: 
 1061:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1062: 	$spare_server = $try_server;
 1063: 	$lowest_load  = $load;
 1064:     }
 1065:     return ($spare_server,$lowest_load);
 1066: }
 1067: 
 1068: # --------------------------- ask offload servers if user already has a session
 1069: sub find_existing_session {
 1070:     my ($udom,$uname) = @_;
 1071:     my $spareshash = &this_host_spares($udom);
 1072:     if (ref($spareshash) eq 'HASH') {
 1073:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1074:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1075:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1076:             }
 1077:         }
 1078:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1079:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1080:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1081:             }
 1082:         }
 1083:     }
 1084:     return;
 1085: }
 1086: 
 1087: sub delusersession {
 1088:     my ($lonid,$udom,$uname) = @_;
 1089:     my $uprimary_id = &domain($udom,'primary');
 1090:     my $uintdom = &internet_dom($uprimary_id);
 1091:     my $intdom = &internet_dom($lonid);
 1092:     my $serverhomedom = &host_domain($lonid);
 1093:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1094:         return &reply(join(':','delusersession',
 1095:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1096:     }
 1097:     return;
 1098: }
 1099: 
 1100: # check if user's browser sent load balancer cookie and server still has session
 1101: # and is not overloaded.
 1102: sub check_for_balancer_cookie {
 1103:     my ($r,$update_mtime) = @_;
 1104:     my ($otherserver,$cookie);
 1105:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1106:     if (exists($cookies{'balanceID'})) {
 1107:         my $balid = $cookies{'balanceID'};
 1108:         $cookie=&LONCAPA::clean_handle($balid->value);
 1109:         my $balancedir=$r->dir_config('lonBalanceDir');
 1110:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1111:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1112:                 my ($possudom,$possuname) = ($1,$2);
 1113:                 my $has_session = 0;
 1114:                 if ((&domain($possudom) ne '') &&
 1115:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1116:                     my $try_server;
 1117:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1118:                     if ($opened) {
 1119:                         flock($idf,LOCK_SH);
 1120:                         while (my $line = <$idf>) {
 1121:                             chomp($line);
 1122:                             if (&hostname($line) ne '') {
 1123:                                 $try_server = $line;
 1124:                                 last;
 1125:                             }
 1126:                         }
 1127:                         close($idf);
 1128:                         if (($try_server) &&
 1129:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1130:                             my $lowest_load = 30000;
 1131:                             ($otherserver,$lowest_load) =
 1132:                                 &compare_server_load($try_server,undef,$lowest_load);
 1133:                             if ($otherserver ne '' && $lowest_load < 100) {
 1134:                                 $has_session = 1;
 1135:                             } else {
 1136:                                 undef($otherserver);
 1137:                             }
 1138:                         }
 1139:                     }
 1140:                 }
 1141:                 if ($has_session) {
 1142:                     if ($update_mtime) {
 1143:                         my $atime = my $mtime = time;
 1144:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1145:                     }
 1146:                 } else {
 1147:                     unlink("$balancedir/$cookie.id");
 1148:                 }
 1149:             }
 1150:         }
 1151:     }
 1152:     return ($otherserver,$cookie);
 1153: }
 1154: 
 1155: sub updatebalcookie {
 1156:     my ($cookie,$balancer,$lastentry)=@_;
 1157:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1158:         my ($udom,$uname) = ($1,$2);
 1159:         my $uprimary_id = &domain($udom,'primary');
 1160:         my $uintdom = &internet_dom($uprimary_id);
 1161:         my $intdom = &internet_dom($balancer);
 1162:         my $serverhomedom = &host_domain($balancer);
 1163:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1164:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1165:         }
 1166:     }
 1167:     return;
 1168: }
 1169: 
 1170: sub delbalcookie {
 1171:     my ($cookie,$balancer) =@_;
 1172:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1173:         my ($udom,$uname) = ($1,$2);
 1174:         my $uprimary_id = &domain($udom,'primary');
 1175:         my $uintdom = &internet_dom($uprimary_id);
 1176:         my $intdom = &internet_dom($balancer);
 1177:         my $serverhomedom = &host_domain($balancer);
 1178:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1179:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1180:         }
 1181:     }
 1182: }
 1183: 
 1184: # -------------------------------- ask if server already has a session for user
 1185: sub has_user_session {
 1186:     my ($lonid,$udom,$uname) = @_;
 1187:     my $result = &reply(join(':','userhassession',
 1188: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1189:     return 1 if ($result eq 'ok');
 1190: 
 1191:     return 0;
 1192: }
 1193: 
 1194: # --------- determine least loaded server in a user's domain which allows login
 1195: 
 1196: sub choose_server {
 1197:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1198:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1199:     my %servers = &get_servers($udom);
 1200:     my $lowest_load = 30000;
 1201:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1202:     if ($skiploadbal) {
 1203:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1204:         unless (defined($cached)) {
 1205:             my $cachetime = 60*60*24;
 1206:             my %domconfig =
 1207:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1208:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1209:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1210:                                            $cachetime);
 1211:             }
 1212:         }
 1213:     }
 1214:     foreach my $lonhost (keys(%servers)) {
 1215:         if ($skiploadbal) {
 1216:             if (ref($balancers) eq 'HASH') {
 1217:                 next if (exists($balancers->{$lonhost}));
 1218:             }
 1219:         }
 1220:         my $loginvia;
 1221:         if ($checkloginvia) {
 1222:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1223:             if ($loginvia) {
 1224:                 my ($server,$path) = split(/:/,$loginvia);
 1225:                 ($login_host, $lowest_load) =
 1226:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1227:                 if ($login_host eq $server) {
 1228:                     $portal_path = $path;
 1229:                     $isredirect = 1;
 1230:                 }
 1231:             } else {
 1232:                 ($login_host, $lowest_load) =
 1233:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1234:                 if ($login_host eq $lonhost) {
 1235:                     $portal_path = '';
 1236:                     $isredirect = ''; 
 1237:                 }
 1238:             }
 1239:         } else {
 1240:             ($login_host, $lowest_load) =
 1241:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1242:         }
 1243:     }
 1244:     if ($login_host ne '') {
 1245:         $hostname = &hostname($login_host);
 1246:     }
 1247:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1248: }
 1249: 
 1250: sub get_course_sessions {
 1251:     my ($cnum,$cdom,$lastactivity) = @_;
 1252:     my %servers = &internet_dom_servers($cdom);
 1253:     my %returnhash;
 1254:     foreach my $server (sort(keys(%servers))) {
 1255:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1256:         my @pairs=split(/\&/,$rep);
 1257:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1258:             foreach my $item (@pairs) {
 1259:                 my ($key,$value)=split(/=/,$item,2);
 1260:                 $key = &unescape($key);
 1261:                 next if ($key =~ /^error: 2 /);
 1262:                 if (exists($returnhash{$key})) {
 1263:                     next if ($value < $returnhash{$key});
 1264:                 }
 1265:                 $returnhash{$key}=$value;
 1266:             }
 1267:         }
 1268:     }
 1269:     return %returnhash;
 1270: }
 1271: 
 1272: # --------------------------------------------- Try to change a user's password
 1273: 
 1274: sub changepass {
 1275:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1276:     $currentpass = &escape($currentpass);
 1277:     $newpass     = &escape($newpass);
 1278:     my $lonhost = $perlvar{'lonHostID'};
 1279:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1280: 		       $server);
 1281:     if (! $answer) {
 1282: 	&logthis("No reply on password change request to $server ".
 1283: 		 "by $uname in domain $udom.");
 1284:     } elsif ($answer =~ "^ok") {
 1285:         &logthis("$uname in $udom successfully changed their password ".
 1286: 		 "on $server.");
 1287:     } elsif ($answer =~ "^pwchange_failure") {
 1288: 	&logthis("$uname in $udom was unable to change their password ".
 1289: 		 "on $server.  The action was blocked by either lcpasswd ".
 1290: 		 "or pwchange");
 1291:     } elsif ($answer =~ "^non_authorized") {
 1292:         &logthis("$uname in $udom did not get their password correct when ".
 1293: 		 "attempting to change it on $server.");
 1294:     } elsif ($answer =~ "^auth_mode_error") {
 1295:         &logthis("$uname in $udom attempted to change their password despite ".
 1296: 		 "not being locally or internally authenticated on $server.");
 1297:     } elsif ($answer =~ "^unknown_user") {
 1298:         &logthis("$uname in $udom attempted to change their password ".
 1299: 		 "on $server but were unable to because $server is not ".
 1300: 		 "their home server.");
 1301:     } elsif ($answer =~ "^refused") {
 1302: 	&logthis("$server refused to change $uname in $udom password because ".
 1303: 		 "it was sent an unencrypted request to change the password.");
 1304:     } elsif ($answer =~ "invalid_client") {
 1305:         &logthis("$server refused to change $uname in $udom password because ".
 1306:                  "it was a reset by e-mail originating from an invalid server.");
 1307:     } elsif ($answer =~ "^prioruse") {
 1308:        &logthis("$server refused to change $uname in $udom password because ".
 1309:                 "the password had been used before");
 1310:     }
 1311:     return $answer;
 1312: }
 1313: 
 1314: # ----------------------- Try to determine user's current authentication scheme
 1315: 
 1316: sub queryauthenticate {
 1317:     my ($uname,$udom)=@_;
 1318:     my $uhome=&homeserver($uname,$udom);
 1319:     if (!$uhome) {
 1320: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1321: 	return 'no_host';
 1322:     }
 1323:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1324:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1325: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1326:     }
 1327:     return $answer;
 1328: }
 1329: 
 1330: # --------- Try to authenticate user from domain's lib servers (first this one)
 1331: 
 1332: sub authenticate {
 1333:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1334:     $upass=&escape($upass);
 1335:     $uname= &LONCAPA::clean_username($uname);
 1336:     my $uhome=&homeserver($uname,$udom,1);
 1337:     my $newhome;
 1338:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1339: # Maybe the machine was offline and only re-appeared again recently?
 1340:         &reconlonc();
 1341: # One more
 1342: 	$uhome=&homeserver($uname,$udom,1);
 1343:         if (($uhome eq 'no_host') && $checkdefauth) {
 1344:             if (defined(&domain($udom,'primary'))) {
 1345:                 $newhome=&domain($udom,'primary');
 1346:             }
 1347:             if ($newhome ne '') {
 1348:                 $uhome = $newhome;
 1349:             }
 1350:         }
 1351: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1352: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1353: 	    return 'no_host';
 1354:         }
 1355:     }
 1356:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1357:     if ($answer eq 'authorized') {
 1358:         if ($newhome) {
 1359:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1360:             return 'no_account_on_host'; 
 1361:         } else {
 1362:             &logthis("User $uname at $udom authorized by $uhome");
 1363:             return $uhome;
 1364:         }
 1365:     }
 1366:     if ($answer eq 'non_authorized') {
 1367: 	&logthis("User $uname at $udom rejected by $uhome");
 1368: 	return 'no_host'; 
 1369:     }
 1370:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1371:     return 'no_host';
 1372: }
 1373: 
 1374: sub can_host_session {
 1375:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1376:     my $canhost = 1;
 1377:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1378:     if (ref($remotesessions) eq 'HASH') {
 1379:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1380:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1381:                 $canhost = 0;
 1382:             } else {
 1383:                 $canhost = 1;
 1384:             }
 1385:         }
 1386:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1387:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1388:                 $canhost = 1;
 1389:             } else {
 1390:                 $canhost = 0;
 1391:             }
 1392:         }
 1393:         if ($canhost) {
 1394:             if ($remotesessions->{'version'} ne '') {
 1395:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1396:                 if ($reqmajor ne '' && $reqminor ne '') {
 1397:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1398:                         my $major = $1;
 1399:                         my $minor = $2;
 1400:                         if (($major < $reqmajor ) ||
 1401:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1402:                             $canhost = 0;
 1403:                         }
 1404:                     } else {
 1405:                         $canhost = 0;
 1406:                     }
 1407:                 }
 1408:             }
 1409:         }
 1410:     }
 1411:     if ($canhost) {
 1412:         if (ref($hostedsessions) eq 'HASH') {
 1413:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1414:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1415:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1416:                 if (($uint_dom ne '') && 
 1417:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1418:                     $canhost = 0;
 1419:                 } else {
 1420:                     $canhost = 1;
 1421:                 }
 1422:             }
 1423:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1424:                 if (($uint_dom ne '') && 
 1425:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1426:                     $canhost = 1;
 1427:                 } else {
 1428:                     $canhost = 0;
 1429:                 }
 1430:             }
 1431:         }
 1432:     }
 1433:     return $canhost;
 1434: }
 1435: 
 1436: sub spare_can_host {
 1437:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1438:     my $canhost=1;
 1439:     my $try_server_hostname = &hostname($try_server);
 1440:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1441:     my $serverhomedom = &host_domain($serverhomeID);
 1442:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1443:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1444:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1445:             $canhost = 0;
 1446:         }
 1447:     }
 1448:     if ($canhost) {
 1449:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1450:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1451:                 unless (&shared_institution($udom,$try_server)) {
 1452:                     $canhost = 0;
 1453:                 }
 1454:             }
 1455:         }
 1456:     }
 1457:     if (($canhost) && ($uint_dom)) {
 1458:         my @intdoms;
 1459:         my $internet_names = &get_internet_names($try_server);
 1460:         if (ref($internet_names) eq 'ARRAY') {
 1461:             @intdoms = @{$internet_names};
 1462:         }
 1463:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1464:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1465:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1466:                                          $remotesessions,
 1467:                                          $defdomdefaults{'hostedsessions'});
 1468:         }
 1469:     }
 1470:     return $canhost;
 1471: }
 1472: 
 1473: sub this_host_spares {
 1474:     my ($dom) = @_;
 1475:     my ($dom_in_use,$lonhost_in_use,$result);
 1476:     my @hosts = &current_machine_ids();
 1477:     foreach my $lonhost (@hosts) {
 1478:         if (&host_domain($lonhost) eq $dom) {
 1479:             $dom_in_use = $dom;
 1480:             $lonhost_in_use = $lonhost;
 1481:             last;
 1482:         }
 1483:     }
 1484:     if ($dom_in_use ne '') {
 1485:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1486:     }
 1487:     if (ref($result) ne 'HASH') {
 1488:         $lonhost_in_use = $perlvar{'lonHostID'};
 1489:         $dom_in_use = &host_domain($lonhost_in_use);
 1490:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1491:         if (ref($result) ne 'HASH') {
 1492:             $result = \%spareid;
 1493:         }
 1494:     }
 1495:     return $result;
 1496: }
 1497: 
 1498: sub spares_for_offload  {
 1499:     my ($dom_in_use,$lonhost_in_use) = @_;
 1500:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1501:     if (defined($cached)) {
 1502:         return $result;
 1503:     } else {
 1504:         my $cachetime = 60*60*24;
 1505:         my %domconfig =
 1506:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1507:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1508:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1509:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1510:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1511:                 }
 1512:             }
 1513:         }
 1514:     }
 1515:     return;
 1516: }
 1517: 
 1518: sub get_lonbalancer_config {
 1519:     my ($servers) = @_;
 1520:     my ($currbalancer,$currtargets);
 1521:     if (ref($servers) eq 'HASH') {
 1522:         foreach my $server (keys(%{$servers})) {
 1523:             my %what = (
 1524:                          spareid => 1,
 1525:                          perlvar => 1,
 1526:                        );
 1527:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1528:             if ($result eq 'ok') {
 1529:                 if (ref($returnhash) eq 'HASH') {
 1530:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1531:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1532:                             $currbalancer = $server;
 1533:                             $currtargets = {};
 1534:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1535:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1536:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1537:                                 }
 1538:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1539:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1540:                                 }
 1541:                             }
 1542:                             last;
 1543:                         }
 1544:                     }
 1545:                 }
 1546:             }
 1547:         }
 1548:     }
 1549:     return ($currbalancer,$currtargets);
 1550: }
 1551: 
 1552: sub check_loadbalancing {
 1553:     my ($uname,$udom,$caller) = @_;
 1554:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1555:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1556:     my $lonhost = $perlvar{'lonHostID'};
 1557:     my @hosts = &current_machine_ids();
 1558:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1559:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1560:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1561:     my $serverhomedom = &host_domain($lonhost);
 1562:     my $domneedscache;
 1563:     my $cachetime = 60*60*24;
 1564: 
 1565:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1566:         $dom_in_use = $udom;
 1567:         $homeintdom = 1;
 1568:     } else {
 1569:         $dom_in_use = $serverhomedom;
 1570:     }
 1571:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1572:     unless (defined($cached)) {
 1573:         my %domconfig =
 1574:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1575:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1576:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1577:         } else {
 1578:             $domneedscache = $dom_in_use;
 1579:         }
 1580:     }
 1581:     if (ref($result) eq 'HASH') {
 1582:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1583:             &check_balancer_result($result,@hosts);
 1584:         if ($is_balancer) {
 1585:             if (ref($currrules) eq 'HASH') {
 1586:                 if ($homeintdom) {
 1587:                     if ($uname ne '') {
 1588:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1589:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1590:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1591:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1592:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1593:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1594:                             }
 1595:                         }
 1596:                         if ($rule_in_effect eq '') {
 1597:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1598:                             if ($userenv{'inststatus'} ne '') {
 1599:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1600:                                 my ($othertitle,$usertypes,$types) =
 1601:                                     &Apache::loncommon::sorted_inst_types($udom);
 1602:                                 if (ref($types) eq 'ARRAY') {
 1603:                                     foreach my $type (@{$types}) {
 1604:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1605:                                             if (exists($currrules->{$type})) {
 1606:                                                 $rule_in_effect = $currrules->{$type};
 1607:                                             }
 1608:                                         }
 1609:                                     }
 1610:                                 }
 1611:                             } else {
 1612:                                 if (exists($currrules->{'default'})) {
 1613:                                     $rule_in_effect = $currrules->{'default'};
 1614:                                 }
 1615:                             }
 1616:                         }
 1617:                     } else {
 1618:                         if (exists($currrules->{'default'})) {
 1619:                             $rule_in_effect = $currrules->{'default'};
 1620:                         }
 1621:                     }
 1622:                 } else {
 1623:                     if ($currrules->{'_LC_external'} ne '') {
 1624:                         $rule_in_effect = $currrules->{'_LC_external'};
 1625:                     }
 1626:                 }
 1627:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1628:                                                        $uname,$udom);
 1629:             }
 1630:         }
 1631:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1632:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1633:         unless (defined($cached)) {
 1634:             my %domconfig =
 1635:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1636:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1637:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1638:             } else {
 1639:                 $domneedscache = $serverhomedom;
 1640:             }
 1641:         }
 1642:         if (ref($result) eq 'HASH') {
 1643:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1644:                 &check_balancer_result($result,@hosts);
 1645:             if ($is_balancer) {
 1646:                 if (ref($currrules) eq 'HASH') {
 1647:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1648:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1649:                     }
 1650:                 }
 1651:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1652:                                                        $uname,$udom);
 1653:             }
 1654:         } else {
 1655:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1656:                 $is_balancer = 1;
 1657:                 $offloadto = &this_host_spares($dom_in_use);
 1658:             }
 1659:             unless (defined($cached)) {
 1660:                 $domneedscache = $serverhomedom;
 1661:             }
 1662:         }
 1663:     } else {
 1664:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1665:             $is_balancer = 1;
 1666:             $offloadto = &this_host_spares($dom_in_use);
 1667:         }
 1668:         unless (defined($cached)) {
 1669:             $domneedscache = $serverhomedom;
 1670:         }
 1671:     }
 1672:     if ($domneedscache) {
 1673:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1674:     }
 1675:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1676:         my $lowest_load = 30000;
 1677:         if (ref($offloadto) eq 'HASH') {
 1678:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1679:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1680:                     ($otherserver,$lowest_load) =
 1681:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1682:                 }
 1683:             }
 1684:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1685: 
 1686:             if (!$found_server) {
 1687:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1688:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1689:                         ($otherserver,$lowest_load) =
 1690:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1691:                     }
 1692:                 }
 1693:             }
 1694:         } elsif (ref($offloadto) eq 'ARRAY') {
 1695:             if (@{$offloadto} == 1) {
 1696:                 $otherserver = $offloadto->[0];
 1697:             } elsif (@{$offloadto} > 1) {
 1698:                 foreach my $try_server (@{$offloadto}) {
 1699:                     ($otherserver,$lowest_load) =
 1700:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1701:                 }
 1702:             }
 1703:         }
 1704:         unless ($caller eq 'login') {
 1705:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1706:                 $is_balancer = 0;
 1707:                 if ($uname ne '' && $udom ne '') {
 1708:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1709:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1710:                                  'user.loadbalcheck.time' => time});
 1711:                     }
 1712:                 }
 1713:             }
 1714:         }
 1715:     }
 1716:     if (($is_balancer) && (!$homeintdom)) {
 1717:         undef($setcookie);
 1718:     }
 1719:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1720: }
 1721: 
 1722: sub check_balancer_result {
 1723:     my ($result,@hosts) = @_;
 1724:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1725:     if (ref($result) eq 'HASH') {
 1726:         if ($result->{'lonhost'} ne '') {
 1727:             my $currbalancer = $result->{'lonhost'};
 1728:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1729:                 $is_balancer = 1;
 1730:                 $currtargets = $result->{'targets'};
 1731:                 $currrules = $result->{'rules'};
 1732:             }
 1733:             $dom_balancers = $currbalancer;
 1734:         } else {
 1735:             if (keys(%{$result})) {
 1736:                 foreach my $key (keys(%{$result})) {
 1737:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1738:                         (ref($result->{$key}) eq 'HASH')) {
 1739:                         $is_balancer = 1;
 1740:                         $currrules = $result->{$key}{'rules'};
 1741:                         $currtargets = $result->{$key}{'targets'};
 1742:                         $setcookie = $result->{$key}{'cookie'};
 1743:                         last;
 1744:                     }
 1745:                 }
 1746:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1747:             }
 1748:         }
 1749:     }
 1750:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1751: }
 1752: 
 1753: sub get_loadbalancer_targets {
 1754:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1755:     my $offloadto;
 1756:     if ($rule_in_effect eq 'none') {
 1757:         return [$perlvar{'lonHostID'}];
 1758:     } elsif ($rule_in_effect eq '') {
 1759:         $offloadto = $currtargets;
 1760:     } else {
 1761:         if ($rule_in_effect eq 'homeserver') {
 1762:             my $homeserver = &homeserver($uname,$udom);
 1763:             if ($homeserver ne 'no_host') {
 1764:                 $offloadto = [$homeserver];
 1765:             }
 1766:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1767:             my %domconfig =
 1768:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1769:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1770:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1771:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1772:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1773:                     }
 1774:                 }
 1775:             } else {
 1776:                 my %servers = &internet_dom_servers($udom);
 1777:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1778:                 if (&hostname($remotebalancer) ne '') {
 1779:                     $offloadto = [$remotebalancer];
 1780:                 }
 1781:             }
 1782:         } elsif (&hostname($rule_in_effect) ne '') {
 1783:             $offloadto = [$rule_in_effect];
 1784:         }
 1785:     }
 1786:     return $offloadto;
 1787: }
 1788: 
 1789: sub internet_dom_servers {
 1790:     my ($dom) = @_;
 1791:     my (%uniqservers,%servers);
 1792:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1793:     my @machinedoms = &machine_domains($primaryserver);
 1794:     foreach my $mdom (@machinedoms) {
 1795:         my %currservers = %servers;
 1796:         my %server = &get_servers($mdom);
 1797:         %servers = (%currservers,%server);
 1798:     }
 1799:     my %by_hostname;
 1800:     foreach my $id (keys(%servers)) {
 1801:         push(@{$by_hostname{$servers{$id}}},$id);
 1802:     }
 1803:     foreach my $hostname (sort(keys(%by_hostname))) {
 1804:         if (@{$by_hostname{$hostname}} > 1) {
 1805:             my $match = 0;
 1806:             foreach my $id (@{$by_hostname{$hostname}}) {
 1807:                 if (&host_domain($id) eq $dom) {
 1808:                     $uniqservers{$id} = $hostname;
 1809:                     $match = 1;
 1810:                 }
 1811:             }
 1812:             unless ($match) {
 1813:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1814:             }
 1815:         } else {
 1816:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1817:         }
 1818:     }
 1819:     return %uniqservers;
 1820: }
 1821: 
 1822: sub trusted_domains {
 1823:     my ($cmdtype,$calldom) = @_;
 1824:     my ($trusted,$untrusted);
 1825:     if (&domain($calldom) eq '') {
 1826:         return ($trusted,$untrusted);
 1827:     }
 1828:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1829:         return ($trusted,$untrusted);
 1830:     }
 1831:     my $callprimary = &domain($calldom,'primary');
 1832:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1833:     if ($intcalldom eq '') {
 1834:         return ($trusted,$untrusted);
 1835:     }
 1836: 
 1837:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1838:     unless (defined($cached)) {
 1839:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1840:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1841:         $trustconfig = $domconfig{'trust'};
 1842:     }
 1843:     if (ref($trustconfig)) {
 1844:         my (%possexc,%possinc,@allexc,@allinc); 
 1845:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1846:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1847:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1848:             }
 1849:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1850:                 $possinc{$intcalldom} = 1;
 1851:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1852:             }
 1853:         }
 1854:         if (keys(%possexc)) {
 1855:             if (keys(%possinc)) {
 1856:                 foreach my $key (sort(keys(%possexc))) {
 1857:                     next if ($key eq $intcalldom);
 1858:                     unless ($possinc{$key}) {
 1859:                         push(@allexc,$key);
 1860:                     }
 1861:                 }
 1862:             } else {
 1863:                 @allexc = sort(keys(%possexc));
 1864:             }
 1865:         }
 1866:         if (keys(%possinc)) {
 1867:             $possinc{$intcalldom} = 1;
 1868:             @allinc = sort(keys(%possinc));
 1869:         }
 1870:         if ((@allexc > 0) || (@allinc > 0)) {
 1871:             my %doms_by_intdom;
 1872:             my %allintdoms = &all_host_intdom();
 1873:             my %alldoms = &all_host_domain();
 1874:             foreach my $key (%allintdoms) {
 1875:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1876:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1877:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1878:                     }
 1879:                 } else {
 1880:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1881:                 }
 1882:             }
 1883:             foreach my $exc (@allexc) {
 1884:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1885:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1886:                 }
 1887:             }
 1888:             foreach my $inc (@allinc) {
 1889:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1890:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1891:                 }
 1892:             }
 1893:         }
 1894:     }
 1895:     return ($trusted,$untrusted);
 1896: }
 1897: 
 1898: sub will_trust {
 1899:     my ($cmdtype,$domain,$possdom) = @_;
 1900:     return 1 if ($domain eq $possdom);
 1901:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1902:     my $willtrust; 
 1903:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1904:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1905:             $willtrust = 1;
 1906:         }
 1907:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1908:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1909:             $willtrust = 1;
 1910:         }
 1911:     } else {
 1912:         $willtrust = 1;
 1913:     }
 1914:     return $willtrust;
 1915: }
 1916: 
 1917: # ---------------------- Find the homebase for a user from domain's lib servers
 1918: 
 1919: my %homecache;
 1920: sub homeserver {
 1921:     my ($uname,$udom,$ignoreBadCache)=@_;
 1922:     my $index="$uname:$udom";
 1923: 
 1924:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1925: 
 1926:     my %servers = &get_servers($udom,'library');
 1927:     foreach my $tryserver (keys(%servers)) {
 1928:         next if ($ignoreBadCache ne 'true' && 
 1929: 		 exists($badServerCache{$tryserver}));
 1930: 
 1931: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1932: 	if ($answer eq 'found') {
 1933: 	    delete($badServerCache{$tryserver}); 
 1934: 	    return $homecache{$index}=$tryserver;
 1935: 	} elsif ($answer eq 'no_host') {
 1936: 	    $badServerCache{$tryserver}=1;
 1937: 	}
 1938:     }    
 1939:     return 'no_host';
 1940: }
 1941: 
 1942: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1943: 
 1944: sub idget {
 1945:     my ($udom,$idsref,$namespace)=@_;
 1946:     my %returnhash=();
 1947:     my @ids=(); 
 1948:     if (ref($idsref) eq 'ARRAY') {
 1949:         @ids = @{$idsref};
 1950:     } else {
 1951:         return %returnhash; 
 1952:     }
 1953:     if ($namespace eq '') {
 1954:         $namespace = 'ids';
 1955:     }
 1956:     
 1957:     my %servers = &get_servers($udom,'library');
 1958:     foreach my $tryserver (keys(%servers)) {
 1959: 	my $idlist=join('&', map { &escape($_); } @ids);
 1960: 	if ($namespace eq 'ids') {
 1961: 	    $idlist=~tr/A-Z/a-z/;
 1962: 	}
 1963: 	my $reply;
 1964: 	if ($namespace eq 'ids') {
 1965: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1966: 	} else {
 1967: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1968: 	}
 1969: 	my @answer=();
 1970: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1971: 	    @answer=split(/\&/,$reply);
 1972: 	}                    ;
 1973: 	my $i;
 1974: 	for ($i=0;$i<=$#ids;$i++) {
 1975: 	    if ($answer[$i]) {
 1976: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1977: 	    }
 1978: 	}
 1979:     }
 1980:     return %returnhash;
 1981: }
 1982: 
 1983: # ------------------------------------- Find the IDs behind a list of usernames
 1984: 
 1985: sub idrget {
 1986:     my ($udom,@unames)=@_;
 1987:     my %returnhash=();
 1988:     foreach my $uname (@unames) {
 1989:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1990:     }
 1991:     return %returnhash;
 1992: }
 1993: 
 1994: # Store away a list of names and associated student/employee IDs or clicker IDs
 1995: 
 1996: sub idput {
 1997:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1998:     my %servers=();
 1999:     my %ids=();
 2000:     my %byid = ();
 2001:     if (ref($idsref) eq 'HASH') {
 2002:         %ids=%{$idsref};
 2003:     }
 2004:     if ($namespace eq '') {
 2005:         $namespace = 'ids'; 
 2006:     }
 2007:     foreach my $uname (keys(%ids)) {
 2008: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2009:         if ($uhom eq '') {
 2010:             $uhom=&homeserver($uname,$udom);
 2011:         }
 2012:         if ($uhom ne 'no_host') {
 2013:             my $esc_unam=&escape($uname);
 2014:             if ($namespace eq 'ids') {
 2015:                 my $id=&escape($ids{$uname});
 2016:                 $id=~tr/A-Z/a-z/;
 2017:                 my $esc_unam=&escape($uname);
 2018:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2019:             } else {
 2020:                 my @currids = split(/,/,$ids{$uname});
 2021:                 foreach my $id (@currids) {
 2022:                     $byid{$uhom}{$id} .= $uname.',';
 2023:                 }
 2024:             }
 2025:         }
 2026:     }
 2027:     if ($namespace eq 'clickers') {
 2028:         foreach my $server (keys(%byid)) {
 2029:             if (ref($byid{$server}) eq 'HASH') {
 2030:                 foreach my $id (keys(%{$byid{$server}})) {
 2031:                     $byid{$server} =~ s/,$//;
 2032:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2033:                 }
 2034:             }
 2035:         }
 2036:     }
 2037:     foreach my $server (keys(%servers)) {
 2038:         $servers{$server} =~ s/\&$//;
 2039:         if ($namespace eq 'ids') {     
 2040:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2041:         } else {
 2042:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2043:         }
 2044:     }
 2045: }
 2046: 
 2047: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2048: 
 2049: sub iddel {
 2050:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2051:     my %result=();
 2052:     my %ids=();
 2053:     my %byid = ();
 2054:     if (ref($idshashref) eq 'HASH') {
 2055:         %ids=%{$idshashref};
 2056:     } else {
 2057:         return %result;
 2058:     }
 2059:     if ($namespace eq '') {
 2060:         $namespace = 'ids';
 2061:     }
 2062:     my %servers=();
 2063:     while (my ($id,$unamestr) = each(%ids)) {
 2064:         if ($namespace eq 'ids') {
 2065:             my $uhom = $uhome;
 2066:             if ($uhom eq '') { 
 2067:                 $uhom=&homeserver($unamestr,$udom);
 2068:             }
 2069:             if ($uhom ne 'no_host') {
 2070:                 $servers{$uhom}.='&'.&escape($id);
 2071:             }
 2072:          } else {
 2073:             my @curritems = split(/,/,$ids{$id});
 2074:             foreach my $uname (@curritems) {
 2075:                 my $uhom = $uhome;
 2076:                 if ($uhom eq '') {
 2077:                     $uhom=&homeserver($uname,$udom);
 2078:                 }
 2079:                 if ($uhom ne 'no_host') { 
 2080:                     $byid{$uhom}{$id} .= $uname.',';
 2081:                 }
 2082:             }
 2083:         }
 2084:     }
 2085:     if ($namespace eq 'clickers') {
 2086:         foreach my $server (keys(%byid)) {
 2087:             if (ref($byid{$server}) eq 'HASH') {
 2088:                 foreach my $id (keys(%{$byid{$server}})) {
 2089:                     $byid{$server}{$id} =~ s/,$//;
 2090:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2091:                 }
 2092:             }
 2093:         }
 2094:     }
 2095:     foreach my $server (keys(%servers)) {
 2096:         $servers{$server} =~ s/\&$//;
 2097:         if ($namespace eq 'ids') {
 2098:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2099:         } elsif ($namespace eq 'clickers') {
 2100:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2101:         }
 2102:     }
 2103:     return %result;
 2104: }
 2105: 
 2106: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2107: 
 2108: sub updateclickers {
 2109:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2110:     my %clickers;
 2111:     if (ref($idshashref) eq 'HASH') {
 2112:         %clickers=%{$idshashref};
 2113:     } else {
 2114:         return;
 2115:     }
 2116:     my $items='';
 2117:     foreach my $item (keys(%clickers)) {
 2118:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2119:     }
 2120:     $items=~s/\&$//;
 2121:     my $request = "updateclickers:$udom:$action:$items";
 2122:     if ($critical) {
 2123:         return &critical($request,$uhome);
 2124:     } else {
 2125:         return &reply($request,$uhome);
 2126:     }
 2127: }
 2128: 
 2129: # ------------------------------dump from db file owned by domainconfig user
 2130: sub dump_dom {
 2131:     my ($namespace, $udom, $regexp) = @_;
 2132: 
 2133:     $udom ||= $env{'user.domain'};
 2134: 
 2135:     return () unless $udom;
 2136: 
 2137:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2138: }
 2139: 
 2140: # ------------------------------------------ get items from domain db files   
 2141: 
 2142: sub get_dom {
 2143:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2144:     return if ($udom eq 'public');
 2145:     my $items='';
 2146:     foreach my $item (@$storearr) {
 2147:         $items.=&escape($item).'&';
 2148:     }
 2149:     $items=~s/\&$//;
 2150:     if (!$udom) {
 2151:         $udom=$env{'user.domain'};
 2152:         return if ($udom eq 'public');
 2153:         if (defined(&domain($udom,'primary'))) {
 2154:             $uhome=&domain($udom,'primary');
 2155:         } else {
 2156:             undef($uhome);
 2157:         }
 2158:     } else {
 2159:         if (!$uhome) {
 2160:             if (defined(&domain($udom,'primary'))) {
 2161:                 $uhome=&domain($udom,'primary');
 2162:             }
 2163:         }
 2164:     }
 2165:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2166:         my $rep;
 2167:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2168:             # domain information is hosted on this machine
 2169:             my $cmd = 'getdom';
 2170:             if ($namespace =~ /^enc/) {
 2171:                 $cmd = 'egetdom';
 2172:             }
 2173:             $rep = &LONCAPA::Lond::get_dom("$cmd:$udom:$namespace:$items");
 2174:         } else {
 2175:             if ($namespace =~ /^enc/) {
 2176:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2177:             } else {
 2178:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2179:             }
 2180:         }
 2181:         my %returnhash;
 2182:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2183:             return %returnhash;
 2184:         }
 2185:         my @pairs=split(/\&/,$rep);
 2186:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2187:             return @pairs;
 2188:         }
 2189:         my $i=0;
 2190:         foreach my $item (@$storearr) {
 2191:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2192:             $i++;
 2193:         }
 2194:         return %returnhash;
 2195:     } else {
 2196:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2197:     }
 2198: }
 2199: 
 2200: # -------------------------------------------- put items in domain db files 
 2201: 
 2202: sub put_dom {
 2203:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2204:     if (!$udom) {
 2205:         $udom=$env{'user.domain'};
 2206:         if (defined(&domain($udom,'primary'))) {
 2207:             $uhome=&domain($udom,'primary');
 2208:         } else {
 2209:             undef($uhome);
 2210:         }
 2211:     } else {
 2212:         if (!$uhome) {
 2213:             if (defined(&domain($udom,'primary'))) {
 2214:                 $uhome=&domain($udom,'primary');
 2215:             }
 2216:         }
 2217:     } 
 2218:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2219:         my $items='';
 2220:         foreach my $item (keys(%$storehash)) {
 2221:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2222:         }
 2223:         $items=~s/\&$//;
 2224:         if ($namespace =~ /^enc/) {
 2225:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2226:         } else {
 2227:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2228:         }
 2229:     } else {
 2230:         &logthis("put_dom failed - no homeserver and/or domain");
 2231:     }
 2232: }
 2233: 
 2234: # --------------------- newput for items in db file owned by domainconfig user
 2235: sub newput_dom {
 2236:     my ($namespace,$storehash,$udom) = @_;
 2237:     my $result;
 2238:     if (!$udom) {
 2239:         $udom=$env{'user.domain'};
 2240:     }
 2241:     if ($udom) {
 2242:         my $uname = &get_domainconfiguser($udom);
 2243:         $result = &newput($namespace,$storehash,$udom,$uname);
 2244:     }
 2245:     return $result;
 2246: }
 2247: 
 2248: # --------------------- delete for items in db file owned by domainconfig user
 2249: sub del_dom {
 2250:     my ($namespace,$storearr,$udom)=@_;
 2251:     if (ref($storearr) eq 'ARRAY') {
 2252:         if (!$udom) {
 2253:             $udom=$env{'user.domain'};
 2254:         }
 2255:         if ($udom) {
 2256:             my $uname = &get_domainconfiguser($udom); 
 2257:             return &del($namespace,$storearr,$udom,$uname);
 2258:         }
 2259:     }
 2260: }
 2261: 
 2262: # ----------------------------------construct domainconfig user for a domain 
 2263: sub get_domainconfiguser {
 2264:     my ($udom) = @_;
 2265:     return $udom.'-domainconfig';
 2266: }
 2267: 
 2268: sub retrieve_inst_usertypes {
 2269:     my ($udom) = @_;
 2270:     my (%returnhash,@order);
 2271:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2272:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2273:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2274:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2275:     } else {
 2276:         if (defined(&domain($udom,'primary'))) {
 2277:             my $uhome=&domain($udom,'primary');
 2278:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2279:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2280:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2281:                 return (\%returnhash,\@order);
 2282:             }
 2283:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2284:             my @pairs=split(/\&/,$hashitems);
 2285:             foreach my $item (@pairs) {
 2286:                 my ($key,$value)=split(/=/,$item,2);
 2287:                 $key = &unescape($key);
 2288:                 next if ($key =~ /^error: 2 /);
 2289:                 $returnhash{$key}=&thaw_unescape($value);
 2290:             }
 2291:             my @esc_order = split(/\&/,$orderitems);
 2292:             foreach my $item (@esc_order) {
 2293:                 push(@order,&unescape($item));
 2294:             }
 2295:         } else {
 2296:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2297:         }
 2298:         return (\%returnhash,\@order);
 2299:     }
 2300: }
 2301: 
 2302: sub is_domainimage {
 2303:     my ($url) = @_;
 2304:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2305:         if (&domain($1) ne '') {
 2306:             return '1';
 2307:         }
 2308:     }
 2309:     return;
 2310: }
 2311: 
 2312: sub inst_directory_query {
 2313:     my ($srch) = @_;
 2314:     my $udom = $srch->{'srchdomain'};
 2315:     my %results;
 2316:     my $homeserver = &domain($udom,'primary');
 2317:     my $outcome;
 2318:     if ($homeserver ne '') {
 2319:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2320:             if ($srch->{'srchby'} eq 'email') {
 2321:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2322:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2323:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2324:                     (($major == 2) && ($minor < 12))) {
 2325:                     return;
 2326:                 }
 2327:             }
 2328:         }
 2329: 	my $queryid=&reply("querysend:instdirsearch:".
 2330: 			   &escape($srch->{'srchby'}).':'.
 2331: 			   &escape($srch->{'srchterm'}).':'.
 2332: 			   &escape($srch->{'srchtype'}),$homeserver);
 2333: 	my $host=&hostname($homeserver);
 2334: 	if ($queryid !~/^\Q$host\E\_/) {
 2335: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2336: 	    return;
 2337: 	}
 2338: 	my $response = &get_query_reply($queryid);
 2339: 	my $maxtries = 5;
 2340: 	my $tries = 1;
 2341: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2342: 	    $response = &get_query_reply($queryid);
 2343: 	    $tries ++;
 2344: 	}
 2345: 
 2346:         if (!&error($response) && $response ne 'refused') {
 2347:             if ($response eq 'unavailable') {
 2348:                 $outcome = $response;
 2349:             } else {
 2350:                 $outcome = 'ok';
 2351:                 my @matches = split(/\n/,$response);
 2352:                 foreach my $match (@matches) {
 2353:                     my ($key,$value) = split(/=/,$match);
 2354:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2355:                 }
 2356:             }
 2357:         }
 2358:     }
 2359:     return ($outcome,%results);
 2360: }
 2361: 
 2362: sub usersearch {
 2363:     my ($srch) = @_;
 2364:     my $dom = $srch->{'srchdomain'};
 2365:     my %results;
 2366:     my %libserv = &all_library();
 2367:     my $query = 'usersearch';
 2368:     foreach my $tryserver (keys(%libserv)) {
 2369:         if (&host_domain($tryserver) eq $dom) {
 2370:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2371:                 if ($srch->{'srchby'} eq 'email') {
 2372:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2373:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2374:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2375:                              (($major == 2) && ($minor < 12)));
 2376:                 }
 2377:             }
 2378:             my $host=&hostname($tryserver);
 2379:             my $queryid=
 2380:                 &reply("querysend:".&escape($query).':'.
 2381:                        &escape($srch->{'srchby'}).':'.
 2382:                        &escape($srch->{'srchtype'}).':'.
 2383:                        &escape($srch->{'srchterm'}),$tryserver);
 2384:             if ($queryid !~/^\Q$host\E\_/) {
 2385:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2386:                 next;
 2387:             }
 2388:             my $reply = &get_query_reply($queryid);
 2389:             my $maxtries = 1;
 2390:             my $tries = 1;
 2391:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2392:                 $reply = &get_query_reply($queryid);
 2393:                 $tries ++;
 2394:             }
 2395:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2396:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2397:             } else {
 2398:                 my @matches;
 2399:                 if ($reply =~ /\n/) {
 2400:                     @matches = split(/\n/,$reply);
 2401:                 } else {
 2402:                     @matches = split(/\&/,$reply);
 2403:                 }
 2404:                 foreach my $match (@matches) {
 2405:                     my ($uname,$udom,%userhash);
 2406:                     foreach my $entry (split(/:/,$match)) {
 2407:                         my ($key,$value) =
 2408:                             map {&unescape($_);} split(/=/,$entry);
 2409:                         $userhash{$key} = $value;
 2410:                         if ($key eq 'username') {
 2411:                             $uname = $value;
 2412:                         } elsif ($key eq 'domain') {
 2413:                             $udom = $value;
 2414:                         }
 2415:                     }
 2416:                     $results{$uname.':'.$udom} = \%userhash;
 2417:                 }
 2418:             }
 2419:         }
 2420:     }
 2421:     return %results;
 2422: }
 2423: 
 2424: sub get_instuser {
 2425:     my ($udom,$uname,$id) = @_;
 2426:     my $homeserver = &domain($udom,'primary');
 2427:     my ($outcome,%results);
 2428:     if ($homeserver ne '') {
 2429:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2430:                            &escape($id).':'.&escape($udom),$homeserver);
 2431:         my $host=&hostname($homeserver);
 2432:         if ($queryid !~/^\Q$host\E\_/) {
 2433:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2434:             return;
 2435:         }
 2436:         my $response = &get_query_reply($queryid);
 2437:         my $maxtries = 5;
 2438:         my $tries = 1;
 2439:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2440:             $response = &get_query_reply($queryid);
 2441:             $tries ++;
 2442:         }
 2443:         if (!&error($response) && $response ne 'refused') {
 2444:             if ($response eq 'unavailable') {
 2445:                 $outcome = $response;
 2446:             } else {
 2447:                 $outcome = 'ok';
 2448:                 my @matches = split(/\n/,$response);
 2449:                 foreach my $match (@matches) {
 2450:                     my ($key,$value) = split(/=/,$match);
 2451:                     $results{&unescape($key)} = &thaw_unescape($value);
 2452:                 }
 2453:             }
 2454:         }
 2455:     }
 2456:     my %userinfo;
 2457:     if (ref($results{$uname}) eq 'HASH') {
 2458:         %userinfo = %{$results{$uname}};
 2459:     } 
 2460:     return ($outcome,%userinfo);
 2461: }
 2462: 
 2463: sub get_multiple_instusers {
 2464:     my ($udom,$users,$caller) = @_;
 2465:     my ($outcome,$results);
 2466:     if (ref($users) eq 'HASH') {
 2467:         my $count = keys(%{$users}); 
 2468:         my $requested = &freeze_escape($users);
 2469:         my $homeserver = &domain($udom,'primary');
 2470:         if ($homeserver ne '') {
 2471:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2472:             my $host=&hostname($homeserver);
 2473:             if ($queryid !~/^\Q$host\E\_/) {
 2474:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2475:                          ' for host: '.$homeserver.'in domain '.$udom);
 2476:                 return ($outcome,$results);
 2477:             }
 2478:             my $response = &get_query_reply($queryid);
 2479:             my $maxtries = 5;
 2480:             if ($count > 100) {
 2481:                 $maxtries = 1+int($count/20);
 2482:             }
 2483:             my $tries = 1;
 2484:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2485:                 $response = &get_query_reply($queryid);
 2486:                 $tries ++;
 2487:             }
 2488:             if ($response eq '') {
 2489:                 $results = {};
 2490:                 foreach my $key (keys(%{$users})) {
 2491:                     my ($uname,$id);
 2492:                     if ($caller eq 'id') {
 2493:                         $id = $key;
 2494:                     } else {
 2495:                         $uname = $key;
 2496:                     }
 2497:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2498:                     $outcome = $resp;
 2499:                     if ($resp eq 'ok') {
 2500:                         %{$results} = (%{$results}, %info);
 2501:                     } else {
 2502:                         last;
 2503:                     }
 2504:                 }
 2505:             } elsif(!&error($response) && ($response ne 'refused')) {
 2506:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2507:                     $outcome = $response;
 2508:                 } else {
 2509:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2510:                     if ($outcome eq 'ok') {
 2511:                         $results = &thaw_unescape($userdata); 
 2512:                     }
 2513:                 }
 2514:             }
 2515:         }
 2516:     }
 2517:     return ($outcome,$results);
 2518: }
 2519: 
 2520: sub inst_rulecheck {
 2521:     my ($udom,$uname,$id,$item,$rules) = @_;
 2522:     my %returnhash;
 2523:     if ($udom ne '') {
 2524:         if (ref($rules) eq 'ARRAY') {
 2525:             @{$rules} = map {&escape($_);} (@{$rules});
 2526:             my $rulestr = join(':',@{$rules});
 2527:             my $homeserver=&domain($udom,'primary');
 2528:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2529:                 my $response;
 2530:                 if ($item eq 'username') {                
 2531:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2532:                                               ':'.&escape($uname).':'.$rulestr,
 2533:                                               $homeserver));
 2534:                 } elsif ($item eq 'id') {
 2535:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2536:                                               ':'.&escape($id).':'.$rulestr,
 2537:                                               $homeserver));
 2538:                 } elsif ($item eq 'selfcreate') {
 2539:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2540:                                                &escape($udom).':'.&escape($uname).
 2541:                                               ':'.$rulestr,$homeserver));
 2542:                 }
 2543:                 if ($response ne 'refused') {
 2544:                     my @pairs=split(/\&/,$response);
 2545:                     foreach my $item (@pairs) {
 2546:                         my ($key,$value)=split(/=/,$item,2);
 2547:                         $key = &unescape($key);
 2548:                         next if ($key =~ /^error: 2 /);
 2549:                         $returnhash{$key}=&thaw_unescape($value);
 2550:                     }
 2551:                 }
 2552:             }
 2553:         }
 2554:     }
 2555:     return %returnhash;
 2556: }
 2557: 
 2558: sub inst_userrules {
 2559:     my ($udom,$check) = @_;
 2560:     my (%ruleshash,@ruleorder);
 2561:     if ($udom ne '') {
 2562:         my $homeserver=&domain($udom,'primary');
 2563:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2564:             my $response;
 2565:             if ($check eq 'id') {
 2566:                 $response=&reply('instidrules:'.&escape($udom),
 2567:                                  $homeserver);
 2568:             } elsif ($check eq 'email') {
 2569:                 $response=&reply('instemailrules:'.&escape($udom),
 2570:                                  $homeserver);
 2571:             } else {
 2572:                 $response=&reply('instuserrules:'.&escape($udom),
 2573:                                  $homeserver);
 2574:             }
 2575:             if (($response ne 'refused') && ($response ne 'error') && 
 2576:                 ($response ne 'unknown_cmd') && 
 2577:                 ($response ne 'no_such_host')) {
 2578:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2579:                 my @pairs=split(/\&/,$hashitems);
 2580:                 foreach my $item (@pairs) {
 2581:                     my ($key,$value)=split(/=/,$item,2);
 2582:                     $key = &unescape($key);
 2583:                     next if ($key =~ /^error: 2 /);
 2584:                     $ruleshash{$key}=&thaw_unescape($value);
 2585:                 }
 2586:                 my @esc_order = split(/\&/,$orderitems);
 2587:                 foreach my $item (@esc_order) {
 2588:                     push(@ruleorder,&unescape($item));
 2589:                 }
 2590:             }
 2591:         }
 2592:     }
 2593:     return (\%ruleshash,\@ruleorder);
 2594: }
 2595: 
 2596: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2597: 
 2598: sub get_domain_defaults {
 2599:     my ($domain,$ignore_cache) = @_;
 2600:     return if (($domain eq '') || ($domain eq 'public'));
 2601:     my $cachetime = 60*60*24;
 2602:     unless ($ignore_cache) {
 2603:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2604:         if (defined($cached)) {
 2605:             if (ref($result) eq 'HASH') {
 2606:                 return %{$result};
 2607:             }
 2608:         }
 2609:     }
 2610:     my %domdefaults;
 2611:     my %domconfig =
 2612:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2613:                                   'requestcourses','inststatus',
 2614:                                   'coursedefaults','usersessions',
 2615:                                   'requestauthor','selfenrollment',
 2616:                                   'coursecategories','ssl','autoenroll',
 2617:                                   'trust','helpsettings','wafproxy'],$domain);
 2618:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2619:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2620:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2621:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2622:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2623:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2624:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2625:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2626:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2627:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2628:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2629:     } else {
 2630:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2631:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2632:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2633:     }
 2634:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2635:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2636:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2637:         } else {
 2638:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2639:         }
 2640:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2641:         foreach my $item (@usertools) {
 2642:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2643:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2644:             }
 2645:         }
 2646:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2647:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2648:         }
 2649:     }
 2650:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2651:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2652:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2653:         }
 2654:     }
 2655:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2656:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2657:     }
 2658:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2659:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2660:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2661:         }
 2662:     }
 2663:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2664:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2665:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2666:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2667:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2668:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2669:         }
 2670:         foreach my $type (@coursetypes) {
 2671:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2672:                 unless ($type eq 'community') {
 2673:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2674:                 }
 2675:             }
 2676:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2677:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2678:             }
 2679:             if ($domdefaults{'postsubmit'} eq 'on') {
 2680:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2681:                     $domdefaults{$type.'postsubtimeout'} = 
 2682:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2683:                 }
 2684:             }
 2685:         }
 2686:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2687:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2688:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2689:                 if (@clonecodes) {
 2690:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2691:                 }
 2692:             }
 2693:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2694:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2695:         }
 2696:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2697:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2698:         } 
 2699:     }
 2700:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2701:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2702:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2703:         }
 2704:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2705:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2706:         }
 2707:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2708:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2709:         }
 2710:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2711:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2712:         }
 2713:     }
 2714:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2715:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2716:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2717:                             'approval','limit');
 2718:             foreach my $type (@coursetypes) {
 2719:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2720:                     my @mgrdc = ();
 2721:                     foreach my $item (@settings) {
 2722:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2723:                             push(@mgrdc,$item);
 2724:                         }
 2725:                     }
 2726:                     if (@mgrdc) {
 2727:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2728:                     }
 2729:                 }
 2730:             }
 2731:         }
 2732:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2733:             foreach my $type (@coursetypes) {
 2734:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2735:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2736:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2737:                     }
 2738:                 }
 2739:             }
 2740:         }
 2741:     }
 2742:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2743:         $domdefaults{'catauth'} = 'std';
 2744:         $domdefaults{'catunauth'} = 'std';
 2745:         if ($domconfig{'coursecategories'}{'auth'}) {
 2746:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2747:         }
 2748:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2749:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2750:         }
 2751:     }
 2752:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2753:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2754:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2755:         }
 2756:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2757:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2758:         }
 2759:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2760:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2761:         }
 2762:     }
 2763:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2764:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2765:         foreach my $prefix (@prefixes) {
 2766:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2767:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2768:             }
 2769:         }
 2770:     }
 2771:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2772:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2773:     }
 2774:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2775:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2776:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2777:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2778:         }
 2779:     }
 2780:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2781:         foreach my $item ('ipheader','trusted','vpnint','vpnext') {
 2782:             if ($domconfig{'wafproxy'}{$item}) {
 2783:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2784:             }
 2785:         }
 2786:     } 
 2787:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2788:     return %domdefaults;
 2789: }
 2790: 
 2791: sub get_dom_cats {
 2792:     my ($dom) = @_;
 2793:     return unless (&domain($dom));
 2794:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2795:     unless (defined($cached)) {
 2796:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2797:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2798:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2799:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2800:             } else {
 2801:                 $cats = {};
 2802:             }
 2803:         } else {
 2804:             $cats = {};
 2805:         }
 2806:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2807:     }
 2808:     return $cats;
 2809: }
 2810: 
 2811: sub get_dom_instcats {
 2812:     my ($dom) = @_;
 2813:     return unless (&domain($dom));
 2814:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2815:     unless (defined($cached)) {
 2816:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2817:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2818:         if ($totcodes > 0) {
 2819:             my $caller = 'global';
 2820:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2821:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2822:                 $instcats = {
 2823:                                 codes => \%codes,
 2824:                                 codetitles => \@codetitles,
 2825:                                 cat_titles => \%cat_titles,
 2826:                                 cat_order => \%cat_order,
 2827:                             };
 2828:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2829:             }
 2830:         }
 2831:     }
 2832:     return $instcats;
 2833: }
 2834: 
 2835: sub retrieve_instcodes {
 2836:     my ($coursecodes,$dom) = @_;
 2837:     my $totcodes;
 2838:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2839:     foreach my $course (keys(%courses)) {
 2840:         if (ref($courses{$course}) eq 'HASH') {
 2841:             if ($courses{$course}{'inst_code'} ne '') {
 2842:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2843:                 $totcodes ++;
 2844:             }
 2845:         }
 2846:     }
 2847:     return $totcodes;
 2848: }
 2849: 
 2850: sub course_portal_url {
 2851:     my ($cnum,$cdom) = @_;
 2852:     my $chome = &homeserver($cnum,$cdom);
 2853:     my $hostname = &hostname($chome);
 2854:     my $protocol = $protocol{$chome};
 2855:     $protocol = 'http' if ($protocol ne 'https');
 2856:     my %domdefaults = &get_domain_defaults($cdom);
 2857:     my $firsturl;
 2858:     if ($domdefaults{'portal_def'}) {
 2859:         $firsturl = $domdefaults{'portal_def'};
 2860:     } else {
 2861:         $firsturl = $protocol.'://'.$hostname;
 2862:     }
 2863:     return $firsturl;
 2864: }
 2865: 
 2866: # --------------------------------------------- Get domain config for passwords
 2867: 
 2868: sub get_passwdconf {
 2869:     my ($dom) = @_;
 2870:     my (%passwdconf,$gotconf,$lookup);
 2871:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2872:     if (defined($cached)) {
 2873:         if (ref($result) eq 'HASH') {
 2874:             %passwdconf = %{$result};
 2875:             $gotconf = 1;
 2876:         }
 2877:     }
 2878:     unless ($gotconf) {
 2879:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2880:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2881:             %passwdconf = %{$domconfig{'passwords'}};
 2882:         }
 2883:         my $cachetime = 24*60*60;
 2884:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2885:     }
 2886:     return %passwdconf;
 2887: }
 2888: 
 2889: # --------------------------------------------------- Assign a key to a student
 2890: 
 2891: sub assign_access_key {
 2892: #
 2893: # a valid key looks like uname:udom#comments
 2894: # comments are being appended
 2895: #
 2896:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2897:     $kdom=
 2898:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2899:     $knum=
 2900:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2901:     $cdom=
 2902:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2903:     $cnum=
 2904:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2905:     $udom=$env{'user.name'} unless (defined($udom));
 2906:     $uname=$env{'user.domain'} unless (defined($uname));
 2907:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2908:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2909:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2910:                                                   # assigned to this person
 2911:                                                   # - this should not happen,
 2912:                                                   # unless something went wrong
 2913:                                                   # the first time around
 2914: # ready to assign
 2915:         $logentry=$1.'; '.$logentry;
 2916:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2917:                                                  $kdom,$knum) eq 'ok') {
 2918: # key now belongs to user
 2919: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2920:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2921:                 &appenv({'environment.'.$envkey => $ckey});
 2922:                 return 'ok';
 2923:             } else {
 2924:                 return 
 2925:   'error: Count not permanently assign key, will need to be re-entered later.';
 2926: 	    }
 2927:         } else {
 2928:             return 'error: Could not assign key, try again later.';
 2929:         }
 2930:     } elsif (!$existing{$ckey}) {
 2931: # the key does not exist
 2932: 	return 'error: The key does not exist';
 2933:     } else {
 2934: # the key is somebody else's
 2935: 	return 'error: The key is already in use';
 2936:     }
 2937: }
 2938: 
 2939: # ------------------------------------------ put an additional comment on a key
 2940: 
 2941: sub comment_access_key {
 2942: #
 2943: # a valid key looks like uname:udom#comments
 2944: # comments are being appended
 2945: #
 2946:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2947:     $cdom=
 2948:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2949:     $cnum=
 2950:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2951:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2952:     if ($existing{$ckey}) {
 2953:         $existing{$ckey}.='; '.$logentry;
 2954: # ready to assign
 2955:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2956:                                                  $cdom,$cnum) eq 'ok') {
 2957: 	    return 'ok';
 2958:         } else {
 2959: 	    return 'error: Count not store comment.';
 2960:         }
 2961:     } else {
 2962: # the key does not exist
 2963: 	return 'error: The key does not exist';
 2964:     }
 2965: }
 2966: 
 2967: # ------------------------------------------------------ Generate a set of keys
 2968: 
 2969: sub generate_access_keys {
 2970:     my ($number,$cdom,$cnum,$logentry)=@_;
 2971:     $cdom=
 2972:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2973:     $cnum=
 2974:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2975:     unless (&allowed('mky',$cdom)) { return 0; }
 2976:     unless (($cdom) && ($cnum)) { return 0; }
 2977:     if ($number>10000) { return 0; }
 2978:     sleep(2); # make sure don't get same seed twice
 2979:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2980:     my $total=0;
 2981:     for (my $i=1;$i<=$number;$i++) {
 2982:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2983:                   sprintf("%lx",int(100000*rand)).'-'.
 2984:                   sprintf("%lx",int(100000*rand));
 2985:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2986:        $newkey=~s/0/h/g; # and also 0 and O
 2987:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2988:        if ($existing{$newkey}) {
 2989:            $i--;
 2990:        } else {
 2991: 	  if (&put('accesskeys',
 2992:               { $newkey => '# generated '.localtime().
 2993:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2994:                            '; '.$logentry },
 2995: 		   $cdom,$cnum) eq 'ok') {
 2996:               $total++;
 2997: 	  }
 2998:        }
 2999:     }
 3000:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3001:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3002:     return $total;
 3003: }
 3004: 
 3005: # ------------------------------------------------------- Validate an accesskey
 3006: 
 3007: sub validate_access_key {
 3008:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3009:     $cdom=
 3010:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3011:     $cnum=
 3012:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3013:     $udom=$env{'user.domain'} unless (defined($udom));
 3014:     $uname=$env{'user.name'} unless (defined($uname));
 3015:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3016:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3017: }
 3018: 
 3019: # ------------------------------------- Find the section of student in a course
 3020: sub devalidate_getsection_cache {
 3021:     my ($udom,$unam,$courseid)=@_;
 3022:     my $hashid="$udom:$unam:$courseid";
 3023:     &devalidate_cache_new('getsection',$hashid);
 3024: }
 3025: 
 3026: sub courseid_to_courseurl {
 3027:     my ($courseid) = @_;
 3028:     #already url style courseid
 3029:     return $courseid if ($courseid =~ m{^/});
 3030: 
 3031:     if (exists($env{'course.'.$courseid.'.num'})) {
 3032: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3033: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3034: 	return "/$cdom/$cnum";
 3035:     }
 3036: 
 3037:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3038:     if (exists($courseinfo{'num'})) {
 3039: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3040:     }
 3041: 
 3042:     return undef;
 3043: }
 3044: 
 3045: sub getsection {
 3046:     my ($udom,$unam,$courseid)=@_;
 3047:     my $cachetime=1800;
 3048: 
 3049:     my $hashid="$udom:$unam:$courseid";
 3050:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3051:     if (defined($cached)) { return $result; }
 3052: 
 3053:     my %Pending; 
 3054:     my %Expired;
 3055:     #
 3056:     # Each role can either have not started yet (pending), be active, 
 3057:     #    or have expired.
 3058:     #
 3059:     # If there is an active role, we are done.
 3060:     #
 3061:     # If there is more than one role which has not started yet, 
 3062:     #     choose the one which will start sooner
 3063:     # If there is one role which has not started yet, return it.
 3064:     #
 3065:     # If there is more than one expired role, choose the one which ended last.
 3066:     # If there is a role which has expired, return it.
 3067:     #
 3068:     $courseid = &courseid_to_courseurl($courseid);
 3069:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3070:     foreach my $key (keys(%roleshash)) {
 3071:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3072:         my $section=$1;
 3073:         if ($key eq $courseid.'_st') { $section=''; }
 3074:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3075:         my $now=time;
 3076:         if (defined($end) && $end && ($now > $end)) {
 3077:             $Expired{$end}=$section;
 3078:             next;
 3079:         }
 3080:         if (defined($start) && $start && ($now < $start)) {
 3081:             $Pending{$start}=$section;
 3082:             next;
 3083:         }
 3084:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3085:     }
 3086:     #
 3087:     # Presumedly there will be few matching roles from the above
 3088:     # loop and the sorting time will be negligible.
 3089:     if (scalar(keys(%Pending))) {
 3090:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3091:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3092:     } 
 3093:     if (scalar(keys(%Expired))) {
 3094:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3095:         my $time = pop(@sorted);
 3096:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3097:     }
 3098:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3099: }
 3100: 
 3101: sub save_cache {
 3102:     &purge_remembered();
 3103:     #&Apache::loncommon::validate_page();
 3104:     undef(%env);
 3105:     undef($env_loaded);
 3106: }
 3107: 
 3108: my $to_remember=-1;
 3109: my %remembered;
 3110: my %accessed;
 3111: my $kicks=0;
 3112: my $hits=0;
 3113: sub make_key {
 3114:     my ($name,$id) = @_;
 3115:     if (length($id) > 65 
 3116: 	&& length(&escape($id)) > 200) {
 3117: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3118:     }
 3119:     return &escape($name.':'.$id);
 3120: }
 3121: 
 3122: sub devalidate_cache_new {
 3123:     my ($name,$id,$debug) = @_;
 3124:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3125:     my $remembered_id=$name.':'.$id;
 3126:     $id=&make_key($name,$id);
 3127:     $memcache->delete($id);
 3128:     delete($remembered{$remembered_id});
 3129:     delete($accessed{$remembered_id});
 3130: }
 3131: 
 3132: sub is_cached_new {
 3133:     my ($name,$id,$debug) = @_;
 3134:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3135:     if (exists($remembered{$remembered_id})) {
 3136: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3137: 	$accessed{$remembered_id}=[&gettimeofday()];
 3138: 	$hits++;
 3139: 	return ($remembered{$remembered_id},1);
 3140:     }
 3141:     $id=&make_key($name,$id);
 3142:     my $value = $memcache->get($id);
 3143:     if (!(defined($value))) {
 3144: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3145: 	return (undef,undef);
 3146:     }
 3147:     if ($value eq '__undef__') {
 3148: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3149: 	$value=undef;
 3150:     }
 3151:     &make_room($remembered_id,$value,$debug);
 3152:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3153:     return ($value,1);
 3154: }
 3155: 
 3156: sub do_cache_new {
 3157:     my ($name,$id,$value,$time,$debug) = @_;
 3158:     my $remembered_id=$name.':'.$id;
 3159:     $id=&make_key($name,$id);
 3160:     my $setvalue=$value;
 3161:     if (!defined($setvalue)) {
 3162: 	$setvalue='__undef__';
 3163:     }
 3164:     if (!defined($time) ) {
 3165: 	$time=600;
 3166:     }
 3167:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3168:     my $result = $memcache->set($id,$setvalue,$time);
 3169:     if (! $result) {
 3170: 	&logthis("caching of id -> $id  failed");
 3171: 	$memcache->disconnect_all();
 3172:     }
 3173:     # need to make a copy of $value
 3174:     &make_room($remembered_id,$value,$debug);
 3175:     return $value;
 3176: }
 3177: 
 3178: sub make_room {
 3179:     my ($remembered_id,$value,$debug)=@_;
 3180: 
 3181:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3182:                                     : $value;
 3183:     if ($to_remember<0) { return; }
 3184:     $accessed{$remembered_id}=[&gettimeofday()];
 3185:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3186:     my $to_kick;
 3187:     my $max_time=0;
 3188:     foreach my $other (keys(%accessed)) {
 3189: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3190: 	    $to_kick=$other;
 3191: 	    $max_time=&tv_interval($accessed{$other});
 3192: 	}
 3193:     }
 3194:     delete($remembered{$to_kick});
 3195:     delete($accessed{$to_kick});
 3196:     $kicks++;
 3197:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3198:     return;
 3199: }
 3200: 
 3201: sub purge_remembered {
 3202:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3203:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3204:     undef(%remembered);
 3205:     undef(%accessed);
 3206: }
 3207: # ------------------------------------- Read an entry from a user's environment
 3208: 
 3209: sub userenvironment {
 3210:     my ($udom,$unam,@what)=@_;
 3211:     my $items;
 3212:     foreach my $item (@what) {
 3213:         $items.=&escape($item).'&';
 3214:     }
 3215:     $items=~s/\&$//;
 3216:     my %returnhash=();
 3217:     my $uhome = &homeserver($unam,$udom);
 3218:     unless ($uhome eq 'no_host') {
 3219:         my @answer=split(/\&/, 
 3220:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3221:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3222:             return %returnhash;
 3223:         }
 3224:         my $i;
 3225:         for ($i=0;$i<=$#what;$i++) {
 3226: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3227:         }
 3228:     }
 3229:     return %returnhash;
 3230: }
 3231: 
 3232: # ---------------------------------------------------------- Get a studentphoto
 3233: sub studentphoto {
 3234:     my ($udom,$unam,$ext) = @_;
 3235:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3236:     if (defined($env{'request.course.id'})) {
 3237:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3238:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3239:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3240:             } else {
 3241:                 my ($result,$perm_reqd)=
 3242: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3243:                 if ($result eq 'ok') {
 3244:                     if (!($perm_reqd eq 'yes')) {
 3245:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3246:                     }
 3247:                 }
 3248:             }
 3249:         }
 3250:     } else {
 3251:         my ($result,$perm_reqd) = 
 3252: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3253:         if ($result eq 'ok') {
 3254:             if (!($perm_reqd eq 'yes')) {
 3255:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3256:             }
 3257:         }
 3258:     }
 3259:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3260: }
 3261: 
 3262: sub retrievestudentphoto {
 3263:     my ($udom,$unam,$ext,$type) = @_;
 3264:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3265:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3266:     if ($ret eq 'ok') {
 3267:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3268:         if ($type eq 'thumbnail') {
 3269:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3270:         }
 3271:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3272:         return $tokenurl;
 3273:     } else {
 3274:         if ($type eq 'thumbnail') {
 3275:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3276:         } else { 
 3277:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3278:         }
 3279:     }
 3280: }
 3281: 
 3282: # -------------------------------------------------------------------- New chat
 3283: 
 3284: sub chatsend {
 3285:     my ($newentry,$anon,$group)=@_;
 3286:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3287:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3288:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3289:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3290: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3291: 		   &escape($newentry)).':'.$group,$chome);
 3292: }
 3293: 
 3294: # ------------------------------------------ Find current version of a resource
 3295: 
 3296: sub getversion {
 3297:     my $fname=&clutter(shift);
 3298:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3299:     return &currentversion(&filelocation('',$fname));
 3300: }
 3301: 
 3302: sub currentversion {
 3303:     my $fname=shift;
 3304:     my $author=$fname;
 3305:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3306:     my ($udom,$uname)=split(/\//,$author);
 3307:     my $home=&homeserver($uname,$udom);
 3308:     if ($home eq 'no_host') { 
 3309:         return -1; 
 3310:     }
 3311:     my $answer=&reply("currentversion:$fname",$home);
 3312:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3313: 	return -1;
 3314:     }
 3315:     return $answer;
 3316: }
 3317: 
 3318: #
 3319: # Return special version number of resource if set by override, empty otherwise
 3320: #
 3321: sub usedversion {
 3322:     my $fname=shift;
 3323:     unless ($fname) { $fname=$env{'request.uri'}; }
 3324:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3325:     if ($urlversion) { return $urlversion; }
 3326:     return '';
 3327: }
 3328: 
 3329: # ----------------------------- Subscribe to a resource, return URL if possible
 3330: 
 3331: sub subscribe {
 3332:     my $fname=shift;
 3333:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3334:     $fname=~s/[\n\r]//g;
 3335:     my $author=$fname;
 3336:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3337:     my ($udom,$uname)=split(/\//,$author);
 3338:     my $home=homeserver($uname,$udom);
 3339:     if ($home eq 'no_host') {
 3340:         return 'not_found';
 3341:     }
 3342:     my $answer=reply("sub:$fname",$home);
 3343:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3344: 	$answer.=' by '.$home;
 3345:     }
 3346:     return $answer;
 3347: }
 3348:     
 3349: # -------------------------------------------------------------- Replicate file
 3350: 
 3351: sub repcopy {
 3352:     my $filename=shift;
 3353:     $filename=~s/\/+/\//g;
 3354:     my $londocroot = $perlvar{'lonDocRoot'};
 3355:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3356:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3357:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3358: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3359: 	return &repcopy_userfile($filename);
 3360:     }
 3361:     $filename=~s/[\n\r]//g;
 3362:     my $transname="$filename.in.transfer";
 3363: # FIXME: this should flock
 3364:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3365:     my $remoteurl=subscribe($filename);
 3366:     if ($remoteurl =~ /^con_lost by/) {
 3367: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3368:            return 'unavailable';
 3369:     } elsif ($remoteurl eq 'not_found') {
 3370: 	   #&logthis("Subscribe returned not_found: $filename");
 3371: 	   return 'not_found';
 3372:     } elsif ($remoteurl =~ /^rejected by/) {
 3373: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3374:            return 'forbidden';
 3375:     } elsif ($remoteurl eq 'directory') {
 3376:            return 'ok';
 3377:     } else {
 3378:         my $author=$filename;
 3379:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3380:         my ($udom,$uname)=split(/\//,$author);
 3381:         my $home=homeserver($uname,$udom);
 3382:         unless ($home eq $perlvar{'lonHostID'}) {
 3383:            my @parts=split(/\//,$filename);
 3384:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3385:            if ($path ne "$londocroot/res") {
 3386:                &logthis("Malconfiguration for replication: $filename");
 3387: 	       return 'bad_request';
 3388:            }
 3389:            my $count;
 3390:            for ($count=5;$count<$#parts;$count++) {
 3391:                $path.="/$parts[$count]";
 3392:                if ((-e $path)!=1) {
 3393: 		   mkdir($path,0777);
 3394:                }
 3395:            }
 3396:            my $request=new HTTP::Request('GET',"$remoteurl");
 3397:            my $response;
 3398:            if ($remoteurl =~ m{/raw/}) {
 3399:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3400:            } else {
 3401:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3402:            }
 3403:            if ($response->is_error()) {
 3404: 	       unlink($transname);
 3405:                my $message=$response->status_line;
 3406:                &logthis("<font color=\"blue\">WARNING:"
 3407:                        ." LWP get: $message: $filename</font>");
 3408:                return 'unavailable';
 3409:            } else {
 3410: 	       if ($remoteurl!~/\.meta$/) {
 3411:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3412:                   my $mresponse;
 3413:                   if ($remoteurl =~ m{/raw/}) {
 3414:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3415:                   } else {
 3416:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3417:                   }
 3418:                   if ($mresponse->is_error()) {
 3419: 		      unlink($filename.'.meta');
 3420:                       &logthis(
 3421:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3422:                   }
 3423: 	       }
 3424:                rename($transname,$filename);
 3425:                return 'ok';
 3426:            }
 3427:        }
 3428:     }
 3429: }
 3430: 
 3431: # ------------------------------------------------- Unsubscribe from a resource
 3432: 
 3433: sub unsubscribe {
 3434:     my ($fname) = @_;
 3435:     my $answer;
 3436:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3437:     $fname=~s/[\n\r]//g;
 3438:     my $author=$fname;
 3439:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3440:     my ($udom,$uname)=split(/\//,$author);
 3441:     my $home=homeserver($uname,$udom);
 3442:     if ($home eq 'no_host') {
 3443:         $answer = 'no_host';
 3444:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3445:         $answer = 'home';
 3446:     } else {
 3447:         my $defdom = $perlvar{'lonDefDomain'};
 3448:         if (&will_trust('content',$defdom,$udom)) {
 3449:             $answer = reply("unsub:$fname",$home);
 3450:         } else {
 3451:             $answer = 'untrusted';
 3452:         }
 3453:     }
 3454:     return $answer;
 3455: }
 3456: 
 3457: # ------------------------------------------------ Get server side include body
 3458: sub ssi_body {
 3459:     my ($filelink,%form)=@_;
 3460:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3461:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3462:     }
 3463:     my $output='';
 3464:     my $response;
 3465:     if ($filelink=~/^https?\:/) {
 3466:        ($output,$response)=&externalssi($filelink);
 3467:     } else {
 3468:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3469:        $filelink .= 'inhibitmenu=yes';
 3470:        ($output,$response)=&ssi($filelink,%form);
 3471:     }
 3472:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3473:     $output=~s/^.*?\<body[^\>]*\>//si;
 3474:     $output=~s/\<\/body\s*\>.*?$//si;
 3475:     if (wantarray) {
 3476:         return ($output, $response);
 3477:     } else {
 3478:         return $output;
 3479:     }
 3480: }
 3481: 
 3482: # --------------------------------------------------------- Server Side Include
 3483: 
 3484: sub absolute_url {
 3485:     my ($host_name) = @_;
 3486:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3487:     if ($host_name eq '') {
 3488: 	$host_name = $ENV{'SERVER_NAME'};
 3489:     }
 3490:     return $protocol.$host_name;
 3491: }
 3492: 
 3493: #
 3494: #   Server side include.
 3495: # Parameters:
 3496: #  fn     Possibly encrypted resource name/id.
 3497: #  form   Hash that describes how the rendering should be done
 3498: #         and other things.
 3499: # Returns:
 3500: #   Scalar context: The content of the response.
 3501: #   Array context:  2 element list of the content and the full response object.
 3502: #     
 3503: sub ssi {
 3504: 
 3505:     my ($fn,%form)=@_;
 3506:     my $request;
 3507: 
 3508:     $form{'no_update_last_known'}=1;
 3509:     &Apache::lonenc::check_encrypt(\$fn);
 3510:     if (%form) {
 3511:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3512:       $request->content(join('&',map { 
 3513:             my $name = escape($_);
 3514:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3515:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3516:             : &escape($form{$_}) );    
 3517:         } keys(%form)));
 3518:     } else {
 3519:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3520:     }
 3521: 
 3522:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3523:     my $lonhost = $perlvar{'lonHostID'};
 3524:     my $islocal;
 3525:     if (($env{'request.course.id'}) &&
 3526:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3527:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3528:         ($form{'grade_symb'} ne '') &&
 3529:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3530:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3531:         $islocal = 1;
 3532:     }
 3533:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3534:                                                 '','','',$islocal);
 3535: 
 3536:     if (wantarray) {
 3537: 	return ($response->content, $response);
 3538:     } else {
 3539: 	return $response->content;
 3540:     }
 3541: }
 3542: 
 3543: sub externalssi {
 3544:     my ($url)=@_;
 3545:     my $request=new HTTP::Request('GET',$url);
 3546:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3547:     if (wantarray) {
 3548:         return ($response->content, $response);
 3549:     } else {
 3550:         return $response->content;
 3551:     }
 3552: }
 3553: 
 3554: 
 3555: # If the local copy of a replicated resource is outdated, trigger a  
 3556: # connection from the homeserver to flush the delayed queue. If no update 
 3557: # happens, remove local copies of outdated resource (and corresponding
 3558: # metadata file).
 3559: 
 3560: sub remove_stale_resfile {
 3561:     my ($url) = @_;
 3562:     my $removed;
 3563:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3564:         my $audom = $1;
 3565:         my $auname = $2;
 3566:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3567:             my $homeserver = &homeserver($auname,$audom);
 3568:             unless (($homeserver eq 'no_host') ||
 3569:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3570:                 my $fname = &filelocation('',$url);
 3571:                 if (-e $fname) {
 3572:                     my $hostname = &hostname($homeserver);
 3573:                     if ($hostname) {
 3574:                         my $protocol = $protocol{$homeserver};
 3575:                         $protocol = 'http' if ($protocol ne 'https');
 3576:                         my $uri = &declutter($url);
 3577:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3578:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3579:                         if ($response->is_success()) {
 3580:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3581:                             my $locmodtime = (stat($fname))[9];
 3582:                             if ($locmodtime < $remmodtime) {
 3583:                                 my $stale;
 3584:                                 my $answer = &reply('pong',$homeserver);
 3585:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3586:                                     sleep(0.2);
 3587:                                     $locmodtime = (stat($fname))[9];
 3588:                                     if ($locmodtime < $remmodtime) {
 3589:                                         my $posstransfer = $fname.'.in.transfer';
 3590:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3591:                                             $removed = 1;
 3592:                                         } else {
 3593:                                             $stale = 1;
 3594:                                         }
 3595:                                     } else {
 3596:                                         $removed = 1;
 3597:                                     }
 3598:                                 } else {
 3599:                                     $stale = 1;
 3600:                                 }
 3601:                                 if ($stale) {
 3602:                                     if (unlink($fname)) {
 3603:                                         if ($uri!~/\.meta$/) {
 3604:                                             if (-e $fname.'.meta') {
 3605:                                                 unlink($fname.'.meta');
 3606:                                             }
 3607:                                         }
 3608:                                         my $unsubresult = &unsubscribe($fname);
 3609:                                         unless ($unsubresult eq 'ok') {
 3610:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3611:                                         }
 3612:                                         $removed = 1;
 3613:                                     }
 3614:                                 }
 3615:                             }
 3616:                         }
 3617:                     }
 3618:                 }
 3619:             }
 3620:         }
 3621:     }
 3622:     return $removed;
 3623: }
 3624: 
 3625: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3626: 
 3627: sub allowuploaded {
 3628:     my ($srcurl,$url)=@_;
 3629:     $url=&clutter(&declutter($url));
 3630:     my $dir=$url;
 3631:     $dir=~s/\/[^\/]+$//;
 3632:     my %httpref=();
 3633:     my $httpurl=&hreflocation('',$url);
 3634:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3635:     &Apache::lonnet::appenv(\%httpref);
 3636: }
 3637: 
 3638: #
 3639: # Determine if the current user should be able to edit a particular resource,
 3640: # when viewing in course context.
 3641: # (a) When viewing resource used to determine if "Edit" item is included in 
 3642: #     Functions.
 3643: # (b) When displaying folder contents in course editor, used to determine if
 3644: #     "Edit" link will be displayed alongside resource.
 3645: #
 3646: #  input: six args -- filename (decluttered), course number, course domain,
 3647: #                   url, symb (if registered) and group (if this is a group
 3648: #                   item -- e.g., bulletin board, group page etc.).
 3649: #  output: array of five scalars -- 
 3650: #          $cfile -- url for file editing if editable on current server
 3651: #          $home -- homeserver of resource (i.e., for author if published,
 3652: #                                           or course if uploaded.).
 3653: #          $switchserver --  1 if server switch will be needed.
 3654: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3655: #          $forceview -- 1 if icon/link should be to go to view mode
 3656: #
 3657: 
 3658: sub can_edit_resource {
 3659:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3660:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3661: #
 3662: # For aboutme pages user can only edit his/her own.
 3663: #
 3664:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3665:         my ($sdom,$sname) = ($1,$2);
 3666:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3667:             $home = $env{'user.home'};
 3668:             $cfile = $resurl;
 3669:             if ($env{'form.forceedit'}) {
 3670:                 $forceview = 1;
 3671:             } else {
 3672:                 $forceedit = 1;
 3673:             }
 3674:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3675:         } else {
 3676:             return;
 3677:         }
 3678:     }
 3679: 
 3680:     if ($env{'request.course.id'}) {
 3681:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3682:         if ($group ne '') {
 3683: # if this is a group homepage or group bulletin board, check group privs
 3684:             my $allowed = 0;
 3685:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3686:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3687:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3688:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3689:                     $allowed = 1;
 3690:                 }
 3691:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3692:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3693:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3694:                     $allowed = 1;
 3695:                 }
 3696:             }
 3697:             if ($allowed) {
 3698:                 $home=&homeserver($cnum,$cdom);
 3699:                 if ($env{'form.forceedit'}) {
 3700:                     $forceview = 1;
 3701:                 } else {
 3702:                     $forceedit = 1;
 3703:                 }
 3704:                 $cfile = $resurl;
 3705:             } else {
 3706:                 return;
 3707:             }
 3708:         } else {
 3709:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3710:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3711:                     return;
 3712:                 }
 3713:             } elsif (!$crsedit) {
 3714: #
 3715: # No edit allowed where CC has switched to student role.
 3716: #
 3717:                 return;
 3718:             }
 3719:         }
 3720:     }
 3721: 
 3722:     if ($file ne '') {
 3723:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3724:             if (&is_course_upload($file,$cnum,$cdom)) {
 3725:                 $uploaded = 1;
 3726:                 $incourse = 1;
 3727:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3728:                     $cfile = &hreflocation('',$file);
 3729:                     if ($env{'form.forceedit'}) {
 3730:                         $forceview = 1;
 3731:                     } else {
 3732:                         $forceedit = 1;
 3733:                     }
 3734:                 }
 3735:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3736:                 $incourse = 1;
 3737:                 if ($env{'form.forceedit'}) {
 3738:                     $forceview = 1;
 3739:                 } else {
 3740:                     $forceedit = 1;
 3741:                 }
 3742:                 $cfile = $resurl;
 3743:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3744:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3745:                     $incourse = 1;
 3746:                     if ($env{'form.forceedit'}) {
 3747:                         $forceview = 1;
 3748:                     } else {
 3749:                         $forceedit = 1;
 3750:                     }
 3751:                     $cfile = $resurl;
 3752:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3753:                     $incourse = 1;
 3754:                     $cfile = $resurl.'/smpedit';
 3755:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3756:                     $incourse = 1;
 3757:                     if ($env{'form.forceedit'}) {
 3758:                         $forceview = 1;
 3759:                     } else {
 3760:                         $forceedit = 1;
 3761:                     }
 3762:                     $cfile = $resurl;
 3763:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3764:                     my ($map,$id,$res) = &decode_symb($symb);
 3765:                     if ($map =~ /\.page$/) {
 3766:                         $incourse = 1;
 3767:                         if ($env{'form.forceedit'}) {
 3768:                             $forceview = 1;
 3769:                             $cfile = $map;
 3770:                         } else {
 3771:                             $forceedit = 1;
 3772:                             $cfile =  '/adm/wrapper'.$resurl;
 3773:                         }
 3774:                     }
 3775:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3776:                     $incourse = 1;
 3777:                     if ($env{'form.forceedit'}) {
 3778:                         $forceview = 1;
 3779:                     } else {
 3780:                         $forceedit = 1;
 3781:                     }
 3782:                     $cfile = $resurl;
 3783:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3784:                     $incourse = 1;
 3785:                     if ($env{'form.forceedit'}) {
 3786:                         $forceview = 1;
 3787:                     } else {
 3788:                         $forceedit = 1;
 3789:                     }
 3790:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3791:                 }
 3792:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3793:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3794:                 if (&is_on_map($template)) { 
 3795:                     $incourse = 1;
 3796:                     $forceview = 1;
 3797:                     $cfile = $template;
 3798:                 }
 3799:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3800:                 $incourse = 1;
 3801:                 if ($env{'form.forceedit'}) {
 3802:                     $forceview = 1;
 3803:                 } else {
 3804:                     $forceedit = 1;
 3805:                 }
 3806:                 $cfile = $resurl;
 3807:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3808:                 $incourse = 1;
 3809:                 if ($env{'form.forceedit'}) {
 3810:                     $forceview = 1;
 3811:                 } else {
 3812:                     $forceedit = 1;
 3813:                 }
 3814:                 $cfile = $resurl;
 3815:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3816:                 $incourse = 1;
 3817:                 $forceview = 1;
 3818:                 if ($symb) {
 3819:                     my ($map,$id,$res)=&decode_symb($symb);
 3820:                     $env{'request.symb'} = $symb;
 3821:                     $cfile = &clutter($res);
 3822:                 } else {
 3823:                     $cfile = $env{'form.suppurl'};
 3824:                     my $escfile = &unescape($cfile);
 3825:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3826:                         $cfile = '/adm/wrapper'.$escfile;
 3827:                     } else {
 3828:                         $escfile =~ s{^http://}{};
 3829:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3830:                     }
 3831:                 }
 3832:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3833:                 if ($env{'form.forceedit'}) {
 3834:                     $forceview = 1;
 3835:                 } else {
 3836:                     $forceedit = 1;
 3837:                 }
 3838:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3839:             }
 3840:         }
 3841:         if ($uploaded || $incourse) {
 3842:             $home=&homeserver($cnum,$cdom);
 3843:         } elsif ($file !~ m{/$}) {
 3844:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3845:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3846:             # Check that the user has permission to edit this resource
 3847:             my $setpriv = 1;
 3848:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3849:             if (defined($cfudom)) {
 3850:                 $home=&homeserver($cfuname,$cfudom);
 3851:                 $cfile=$file;
 3852:             }
 3853:         }
 3854:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3855:             (($home ne '') && ($home ne 'no_host'))) {
 3856:             my @ids=&current_machine_ids();
 3857:             unless (grep(/^\Q$home\E$/,@ids)) {
 3858:                 $switchserver=1;
 3859:             }
 3860:         }
 3861:     }
 3862:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3863: }
 3864: 
 3865: sub is_course_upload {
 3866:     my ($file,$cnum,$cdom) = @_;
 3867:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3868:     $uploadpath =~ s{^\/}{};
 3869:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3870:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3871:         return 1;
 3872:     }
 3873:     return;
 3874: }
 3875: 
 3876: sub in_course {
 3877:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3878:     if ($hideprivileged) {
 3879:         my $skipuser;
 3880:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3881:         my @possdoms = ($cdom);  
 3882:         if ($coursehash{'checkforpriv'}) { 
 3883:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3884:         }
 3885:         if (&privileged($uname,$udom,\@possdoms)) {
 3886:             $skipuser = 1;
 3887:             if ($coursehash{'nothideprivileged'}) {
 3888:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3889:                     my $user;
 3890:                     if ($item =~ /:/) {
 3891:                         $user = $item;
 3892:                     } else {
 3893:                         $user = join(':',split(/[\@]/,$item));
 3894:                     }
 3895:                     if ($user eq $uname.':'.$udom) {
 3896:                         undef($skipuser);
 3897:                         last;
 3898:                     }
 3899:                 }
 3900:             }
 3901:             if ($skipuser) {
 3902:                 return 0;
 3903:             }
 3904:         }
 3905:     }
 3906:     $type ||= 'any';
 3907:     if (!defined($cdom) || !defined($cnum)) {
 3908:         my $cid  = $env{'request.course.id'};
 3909:         $cdom = $env{'course.'.$cid.'.domain'};
 3910:         $cnum = $env{'course.'.$cid.'.num'};
 3911:     }
 3912:     my $typesref;
 3913:     if (($type eq 'any') || ($type eq 'all')) {
 3914:         $typesref = ['active','previous','future'];
 3915:     } elsif ($type eq 'previous' || $type eq 'future') {
 3916:         $typesref = [$type];
 3917:     }
 3918:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3919:                               $typesref,undef,[$cdom]);
 3920:     my ($tmp) = keys(%roles);
 3921:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3922:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3923:     if (@course_roles > 0) {
 3924:         return 1;
 3925:     }
 3926:     return 0;
 3927: }
 3928: 
 3929: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3930: # input: action, courseID, current domain, intended
 3931: #        path to file, source of file, instruction to parse file for objects,
 3932: #        ref to hash for embedded objects,
 3933: #        ref to hash for codebase of java objects.
 3934: #        reference to scalar to accommodate mime type determined
 3935: #          from File::MMagic if $parser = parse.
 3936: #
 3937: # output: url to file (if action was uploaddoc), 
 3938: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3939: #
 3940: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3941: # course.
 3942: #
 3943: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3944: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3945: #          course's home server.
 3946: #
 3947: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3948: #          be copied from $source (current location) to 
 3949: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3950: #         and will then be copied to
 3951: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3952: #         course's home server.
 3953: #
 3954: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3955: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3956: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3957: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3958: #         in course's home server.
 3959: #
 3960: 
 3961: sub process_coursefile {
 3962:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3963:         $mimetype)=@_;
 3964:     my $fetchresult;
 3965:     my $home=&homeserver($docuname,$docudom);
 3966:     if ($action eq 'propagate') {
 3967:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3968: 			     $home);
 3969:     } else {
 3970:         my $fpath = '';
 3971:         my $fname = $file;
 3972:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3973:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3974:         my $filepath = &build_filepath($fpath);
 3975:         if ($action eq 'copy') {
 3976:             if ($source eq '') {
 3977:                 $fetchresult = 'no source file';
 3978:                 return $fetchresult;
 3979:             } else {
 3980:                 my $destination = $filepath.'/'.$fname;
 3981:                 rename($source,$destination);
 3982:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3983:                                  $home);
 3984:             }
 3985:         } elsif ($action eq 'uploaddoc') {
 3986:             open(my $fh,'>',$filepath.'/'.$fname);
 3987:             print $fh $env{'form.'.$source};
 3988:             close($fh);
 3989:             if ($parser eq 'parse') {
 3990:                 my $mm = new File::MMagic;
 3991:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3992:                 if ($type eq 'text/html') {
 3993:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3994:                     unless ($parse_result eq 'ok') {
 3995:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3996:                     }
 3997:                 }
 3998:                 if (ref($mimetype)) {
 3999:                     $$mimetype = $type;
 4000:                 } 
 4001:             }
 4002:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4003:                                  $home);
 4004:             if ($fetchresult eq 'ok') {
 4005:                 return '/uploaded/'.$fpath.'/'.$fname;
 4006:             } else {
 4007:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4008:                         ' to host '.$home.': '.$fetchresult);
 4009:                 return '/adm/notfound.html';
 4010:             }
 4011:         }
 4012:     }
 4013:     unless ( $fetchresult eq 'ok') {
 4014:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4015:              ' to host '.$home.': '.$fetchresult);
 4016:     }
 4017:     return $fetchresult;
 4018: }
 4019: 
 4020: sub build_filepath {
 4021:     my ($fpath) = @_;
 4022:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4023:     unless ($fpath eq '') {
 4024:         my @parts=split('/',$fpath);
 4025:         foreach my $part (@parts) {
 4026:             $filepath.= '/'.$part;
 4027:             if ((-e $filepath)!=1) {
 4028:                 mkdir($filepath,0777);
 4029:             }
 4030:         }
 4031:     }
 4032:     return $filepath;
 4033: }
 4034: 
 4035: sub store_edited_file {
 4036:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4037:     my $file = $primary_url;
 4038:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4039:     my $fpath = '';
 4040:     my $fname = $file;
 4041:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4042:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4043:     my $filepath = &build_filepath($fpath);
 4044:     open(my $fh,'>',$filepath.'/'.$fname);
 4045:     print $fh $content;
 4046:     close($fh);
 4047:     my $home=&homeserver($docuname,$docudom);
 4048:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4049: 			  $home);
 4050:     if ($$fetchresult eq 'ok') {
 4051:         return '/uploaded/'.$fpath.'/'.$fname;
 4052:     } else {
 4053:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4054: 		 ' to host '.$home.': '.$$fetchresult);
 4055:         return '/adm/notfound.html';
 4056:     }
 4057: }
 4058: 
 4059: sub clean_filename {
 4060:     my ($fname,$args)=@_;
 4061: # Replace Windows backslashes by forward slashes
 4062:     $fname=~s/\\/\//g;
 4063:     if (!$args->{'keep_path'}) {
 4064:         # Get rid of everything but the actual filename
 4065: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4066:     }
 4067: # Replace spaces by underscores
 4068:     $fname=~s/\s+/\_/g;
 4069: # Transliterate non-ascii text to ascii
 4070:     my $lang = &Apache::lonlocal::current_language();
 4071:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4072: # Replace all other weird characters by nothing
 4073:     $fname=~s{[^/\w\.\-]}{}g;
 4074: # Replace all .\d. sequences with _\d. so they no longer look like version
 4075: # numbers
 4076:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4077: # Replace three or more adjacent underscores with one for consistency 
 4078: # with loncfile::filename_check() so complete url can be extracted by
 4079: # lonnet::decode_symb()
 4080:     $fname=~s/_{3,}/_/g;
 4081:     return $fname;
 4082: }
 4083: 
 4084: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4085: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4086: # image with the same aspect ratio as the original, but with dimensions which do 
 4087: # not exceed $resizewidth and $resizeheight.
 4088:  
 4089: sub resizeImage {
 4090:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4091:     my $ima = Image::Magick->new;
 4092:     my $resized;
 4093:     if (-e $img_path) {
 4094:         $ima->Read($img_path);
 4095:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4096:             my $width = $ima->Get('width');
 4097:             my $height = $ima->Get('height');
 4098:             if ($width > $resizewidth) {
 4099: 	        my $factor = $width/$resizewidth;
 4100:                 my $newheight = $height/$factor;
 4101:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4102:                 $resized = 1;
 4103:             }
 4104:         }
 4105:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4106:             my $width = $ima->Get('width');
 4107:             my $height = $ima->Get('height');
 4108:             if ($height > $resizeheight) {
 4109:                 my $factor = $height/$resizeheight;
 4110:                 my $newwidth = $width/$factor;
 4111:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4112:                 $resized = 1;
 4113:             }
 4114:         }
 4115:         if ($resized) {
 4116:             $ima->Write($img_path);
 4117:         }
 4118:     }
 4119:     return;
 4120: }
 4121: 
 4122: # --------------- Take an uploaded file and put it into the userfiles directory
 4123: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4124: #                    the desired filename is in $env{"form.$formname.filename"}
 4125: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4126: #                                    canceloverwrite, scantron or ''.
 4127: #                   if 'coursedoc': upload to the current course
 4128: #                   if 'existingfile': write file to tmp/overwrites directory 
 4129: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4130: #                   $context is passed as argument to &finishuserfileupload
 4131: #        $subdir - directory in userfile to store the file into
 4132: #        $parser - instruction to parse file for objects ($parser = parse) or
 4133: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4134: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4135: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4136: #        $allfiles - reference to hash for embedded objects
 4137: #        $codebase - reference to hash for codebase of java objects
 4138: #        $desuname - username for permanent storage of uploaded file
 4139: #        $dsetudom - domain for permanaent storage of uploaded file
 4140: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4141: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4142: #        $resizewidth - width (pixels) to which to resize uploaded image
 4143: #        $resizeheight - height (pixels) to which to resize uploaded image
 4144: #        $mimetype - reference to scalar to accommodate mime type determined
 4145: #                    from File::MMagic.
 4146: # 
 4147: # output: url of file in userspace, or error: <message> 
 4148: #             or /adm/notfound.html if failure to upload occurse
 4149: 
 4150: sub userfileupload {
 4151:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4152:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4153:     if (!defined($subdir)) { $subdir='unknown'; }
 4154:     my $fname=$env{'form.'.$formname.'.filename'};
 4155:     $fname=&clean_filename($fname);
 4156:     # See if there is anything left
 4157:     unless ($fname) { return 'error: no uploaded file'; }
 4158:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4159:     if ($fname =~ /^\./) {
 4160:         my ($s,$usec) = &gettimeofday();
 4161:         while (length($usec) < 6) {
 4162:             $usec = '0'.$usec;
 4163:         }
 4164:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4165:     }
 4166:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4167:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4168:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4169:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4170:         my $now = time;
 4171:         my $filepath;
 4172:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4173:              $filepath = 'tmp/helprequests/'.$now;
 4174:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4175:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4176:                          '_'.$env{'user.domain'}.'/pending';
 4177:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4178:             my ($docuname,$docudom);
 4179:             if ($destudom =~ /^$match_domain$/) {
 4180:                 $docudom = $destudom;
 4181:             } else {
 4182:                 $docudom = $env{'user.domain'};
 4183:             }
 4184:             if ($destuname =~ /^$match_username$/) {
 4185:                 $docuname = $destuname;
 4186:             } else {
 4187:                 $docuname = $env{'user.name'};
 4188:             }
 4189:             if (exists($env{'form.group'})) {
 4190:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4191:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4192:             }
 4193:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4194:             if ($context eq 'canceloverwrite') {
 4195:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4196:                 if (-e  $tempfile) {
 4197:                     my @info = stat($tempfile);
 4198:                     if ($info[9] eq $env{'form.timestamp'}) {
 4199:                         unlink($tempfile);
 4200:                     }
 4201:                 }
 4202:                 return;
 4203:             }
 4204:         }
 4205:         # Create the directory if not present
 4206:         my @parts=split(/\//,$filepath);
 4207:         my $fullpath = $perlvar{'lonDaemons'};
 4208:         for (my $i=0;$i<@parts;$i++) {
 4209:             $fullpath .= '/'.$parts[$i];
 4210:             if ((-e $fullpath)!=1) {
 4211:                 mkdir($fullpath,0777);
 4212:             }
 4213:         }
 4214:         open(my $fh,'>',$fullpath.'/'.$fname);
 4215:         print $fh $env{'form.'.$formname};
 4216:         close($fh);
 4217:         if ($context eq 'existingfile') {
 4218:             my @info = stat($fullpath.'/'.$fname);
 4219:             return ($fullpath.'/'.$fname,$info[9]);
 4220:         } else {
 4221:             return $fullpath.'/'.$fname;
 4222:         }
 4223:     }
 4224:     if ($subdir eq 'scantron') {
 4225:         $fname = 'scantron_orig_'.$fname;
 4226:     } else {
 4227:         $fname="$subdir/$fname";
 4228:     }
 4229:     if ($context eq 'coursedoc') {
 4230: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4231: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4232:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4233:             return &finishuserfileupload($docuname,$docudom,
 4234: 					 $formname,$fname,$parser,$allfiles,
 4235: 					 $codebase,$thumbwidth,$thumbheight,
 4236:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4237:         } else {
 4238:             if ($env{'form.folder'}) {
 4239:                 $fname=$env{'form.folder'}.'/'.$fname;
 4240:             }
 4241:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4242: 				       $fname,$formname,$parser,
 4243: 				       $allfiles,$codebase,$mimetype);
 4244:         }
 4245:     } elsif (defined($destuname)) {
 4246:         my $docuname=$destuname;
 4247:         my $docudom=$destudom;
 4248: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4249: 				     $parser,$allfiles,$codebase,
 4250:                                      $thumbwidth,$thumbheight,
 4251:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4252:     } else {
 4253:         my $docuname=$env{'user.name'};
 4254:         my $docudom=$env{'user.domain'};
 4255:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4256:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4257:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4258:         }
 4259: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4260: 				     $parser,$allfiles,$codebase,
 4261:                                      $thumbwidth,$thumbheight,
 4262:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4263:     }
 4264: }
 4265: 
 4266: sub finishuserfileupload {
 4267:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4268:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4269:     my $path=$docudom.'/'.$docuname.'/';
 4270:     my $filepath=$perlvar{'lonDocRoot'};
 4271:   
 4272:     my ($fnamepath,$file,$fetchthumb);
 4273:     $file=$fname;
 4274:     if ($fname=~m|/|) {
 4275:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4276: 	$path.=$fnamepath.'/';
 4277:     }
 4278:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4279:     my $count;
 4280:     for ($count=4;$count<=$#parts;$count++) {
 4281:         $filepath.="/$parts[$count]";
 4282:         if ((-e $filepath)!=1) {
 4283: 	    mkdir($filepath,0777);
 4284:         }
 4285:     }
 4286: 
 4287: # Save the file
 4288:     {
 4289: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4290: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4291: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4292: 	    return '/adm/notfound.html';
 4293: 	}
 4294:         if ($context eq 'overwrite') {
 4295:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4296:             my $target = $filepath.'/'.$file;
 4297:             if (-e $source) {
 4298:                 my @info = stat($source);
 4299:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4300:                     unless (&File::Copy::move($source,$target)) {
 4301:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4302:                         return "Moving from $source failed";
 4303:                     }
 4304:                 } else {
 4305:                     return "Temporary file: $source had unexpected date/time for last modification";
 4306:                 }
 4307:             } else {
 4308:                 return "Temporary file: $source missing";
 4309:             }
 4310:         } elsif (!print FH ($env{'form.'.$formname})) {
 4311: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4312: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4313: 	    return '/adm/notfound.html';
 4314: 	}
 4315: 	close(FH);
 4316:         if ($resizewidth && $resizeheight) {
 4317:             my $mm = new File::MMagic;
 4318:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4319:             if ($mime_type =~ m{^image/}) {
 4320: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4321:             }  
 4322: 	}
 4323:     }
 4324:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4325:         if (ref($mimetype)) {
 4326:             if ($$mimetype eq '') {
 4327:                 my $mm = new File::MMagic;
 4328:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4329:                 $$mimetype = $type;
 4330:             }
 4331:         }
 4332:     }
 4333:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4334:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4335:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4336:                                                        $allfiles,$codebase);
 4337:             unless ($parse_result eq 'ok') {
 4338:                 &logthis('Failed to parse '.$filepath.$file.
 4339: 	   	         ' for embedded media: '.$parse_result); 
 4340:             }
 4341:         }
 4342:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4343:         my $format = $env{'form.scantron_format'};
 4344:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4345:     }
 4346:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4347:         my $input = $filepath.'/'.$file;
 4348:         my $output = $filepath.'/'.'tn-'.$file;
 4349:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4350:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4351:         system({$args[0]} @args);
 4352:         if (-e $filepath.'/'.'tn-'.$file) {
 4353:             $fetchthumb  = 1; 
 4354:         }
 4355:     }
 4356:  
 4357: # Notify homeserver to grep it
 4358: #
 4359:     my $docuhome=&homeserver($docuname,$docudom);	
 4360:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4361:     if ($fetchresult eq 'ok') {
 4362:         if ($fetchthumb) {
 4363:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4364:             if ($thumbresult ne 'ok') {
 4365:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4366:                          $docuhome.': '.$thumbresult);
 4367:             }
 4368:         }
 4369: #
 4370: # Return the URL to it
 4371:         return '/uploaded/'.$path.$file;
 4372:     } else {
 4373:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4374: 		 ': '.$fetchresult);
 4375:         return '/adm/notfound.html';
 4376:     }
 4377: }
 4378: 
 4379: sub extract_embedded_items {
 4380:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4381:     my @state = ();
 4382:     my (%lastids,%related,%shockwave,%flashvars);
 4383:     my %javafiles = (
 4384:                       codebase => '',
 4385:                       code => '',
 4386:                       archive => ''
 4387:                     );
 4388:     my %mediafiles = (
 4389:                       src => '',
 4390:                       movie => '',
 4391:                      );
 4392:     my $p;
 4393:     if ($content) {
 4394:         $p = HTML::LCParser->new($content);
 4395:     } else {
 4396:         $p = HTML::LCParser->new($fullpath);
 4397:     }
 4398:     while (my $t=$p->get_token()) {
 4399: 	if ($t->[0] eq 'S') {
 4400: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4401: 	    push(@state, $tagname);
 4402:             if (lc($tagname) eq 'allow') {
 4403:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4404:             }
 4405: 	    if (lc($tagname) eq 'img') {
 4406: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4407: 	    }
 4408: 	    if (lc($tagname) eq 'a') {
 4409:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4410:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4411:                 }
 4412: 	    }
 4413:             if (lc($tagname) eq 'script') {
 4414:                 my $src;
 4415:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4416:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4417:                 } else {
 4418:                     if ($attr->{'src'} ne '') {
 4419:                         $src = $attr->{'src'};
 4420:                         &add_filetype($allfiles,$src,'src');
 4421:                     }
 4422:                 }
 4423:                 my $text = $p->get_trimmed_text();
 4424:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4425:                     my @swfargs = split(/,/,$1);
 4426:                     foreach my $item (@swfargs) {
 4427:                         $item =~ s/["']//g;
 4428:                         $item =~ s/^\s+//;
 4429:                         $item =~ s/\s+$//;
 4430:                     }
 4431:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4432:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4433:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4434:                         } else {
 4435:                             $related{$swfargs[0]} = [$swfargs[2]];
 4436:                         }
 4437:                     }
 4438:                 }
 4439:             }
 4440:             if (lc($tagname) eq 'link') {
 4441:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4442:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4443:                 }
 4444:             }
 4445: 	    if (lc($tagname) eq 'object' ||
 4446: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4447: 		foreach my $item (keys(%javafiles)) {
 4448: 		    $javafiles{$item} = '';
 4449: 		}
 4450:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4451:                     $lastids{lc($tagname)} = $attr->{'id'};
 4452:                 }
 4453: 	    }
 4454: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4455: 		my $name = lc($attr->{'name'});
 4456: 		foreach my $item (keys(%javafiles)) {
 4457: 		    if ($name eq $item) {
 4458: 			$javafiles{$item} = $attr->{'value'};
 4459: 			last;
 4460: 		    }
 4461: 		}
 4462:                 my $pathfrom;
 4463: 		foreach my $item (keys(%mediafiles)) {
 4464: 		    if ($name eq $item) {
 4465:                         $pathfrom = $attr->{'value'};
 4466:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4467: 			&add_filetype($allfiles,$pathfrom,$name);
 4468: 			last;
 4469: 		    }
 4470: 		}
 4471:                 if ($name eq 'flashvars') {
 4472:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4473:                 }
 4474:                 if ($pathfrom ne '') {
 4475:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4476:                                          $pathfrom);
 4477:                 }
 4478: 	    }
 4479: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4480: 		foreach my $item (keys(%javafiles)) {
 4481: 		    if ($attr->{$item}) {
 4482: 			$javafiles{$item} = $attr->{$item};
 4483: 			last;
 4484: 		    }
 4485: 		}
 4486: 		foreach my $item (keys(%mediafiles)) {
 4487: 		    if ($attr->{$item}) {
 4488: 			&add_filetype($allfiles,$attr->{$item},$item);
 4489: 			last;
 4490: 		    }
 4491: 		}
 4492:                 if (lc($tagname) eq 'embed') {
 4493:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4494:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4495:                                              $attr->{'src'});
 4496:                     }
 4497:                 }
 4498: 	    }
 4499:             if (lc($tagname) eq 'iframe') {
 4500:                 my $src = $attr->{'src'} ;
 4501:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4502:                     &add_filetype($allfiles,$src,'src');
 4503:                 } elsif ($src =~ m{^/}) {
 4504:                     if ($env{'request.course.id'}) {
 4505:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4506:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4507:                         my $url = &hreflocation('',$fullpath);
 4508:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4509:                             my $relpath = $1;
 4510:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4511:                                 &add_filetype($allfiles,$1,'src');
 4512:                             }
 4513:                         }
 4514:                     }
 4515:                 }
 4516:             }
 4517:             if ($t->[4] =~ m{/>$}) {
 4518:                 pop(@state);
 4519:             }
 4520: 	} elsif ($t->[0] eq 'E') {
 4521: 	    my ($tagname) = ($t->[1]);
 4522: 	    if ($javafiles{'codebase'} ne '') {
 4523: 		$javafiles{'codebase'} .= '/';
 4524: 	    }  
 4525: 	    if (lc($tagname) eq 'applet' ||
 4526: 		lc($tagname) eq 'object' ||
 4527: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4528: 		) {
 4529: 		foreach my $item (keys(%javafiles)) {
 4530: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4531: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4532: 			&add_filetype($allfiles,$file,$item);
 4533: 		    }
 4534: 		}
 4535: 	    } 
 4536: 	    pop @state;
 4537: 	}
 4538:     }
 4539:     foreach my $id (sort(keys(%flashvars))) {
 4540:         if ($shockwave{$id} ne '') {
 4541:             my @pairs = split(/\&/,$flashvars{$id});
 4542:             foreach my $pair (@pairs) {
 4543:                 my ($key,$value) = split(/\=/,$pair);
 4544:                 if ($key eq 'thumb') {
 4545:                     &add_filetype($allfiles,$value,$key);
 4546:                 } elsif ($key eq 'content') {
 4547:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4548:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4549:                     if ($ext ne '') {
 4550:                         &add_filetype($allfiles,$path.$value,$ext);
 4551:                     }
 4552:                 }
 4553:             }
 4554:         }
 4555:     }
 4556:     return 'ok';
 4557: }
 4558: 
 4559: sub add_filetype {
 4560:     my ($allfiles,$file,$type)=@_;
 4561:     if (exists($allfiles->{$file})) {
 4562: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4563: 	    push(@{$allfiles->{$file}}, &escape($type));
 4564: 	}
 4565:     } else {
 4566: 	@{$allfiles->{$file}} = (&escape($type));
 4567:     }
 4568: }
 4569: 
 4570: sub embedded_dependency {
 4571:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4572:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4573:         if (($identifier ne '') &&
 4574:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4575:             ($pathfrom ne '')) {
 4576:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4577:             foreach my $dep (@{$related->{$identifier}}) {
 4578:                 &add_filetype($allfiles,$path.$dep,'object');
 4579:             }
 4580:         }
 4581:     }
 4582:     return;
 4583: }
 4584: 
 4585: sub bubblesheet_converter {
 4586:     my ($cdom,$fullpath,$config,$format) = @_;
 4587:     if ((&domain($cdom) ne '') &&
 4588:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4589:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4590:         my (%csvcols,%csvoptions);
 4591:         if (ref($config->{'fields'}) eq 'HASH') {  
 4592:             %csvcols = %{$config->{'fields'}};
 4593:         }
 4594:         if (ref($config->{'options'}) eq 'HASH') {
 4595:             %csvoptions = %{$config->{'options'}};
 4596:         }
 4597:         my %csvbynum = reverse(%csvcols);
 4598:         my %scantronconf = &get_scantron_config($format,$cdom);
 4599:         if (keys(%scantronconf)) {
 4600:             my %bynum = (
 4601:                           $scantronconf{CODEstart} => 'CODEstart',
 4602:                           $scantronconf{IDstart}   => 'IDstart',
 4603:                           $scantronconf{PaperID}   => 'PaperID',
 4604:                           $scantronconf{FirstName} => 'FirstName',
 4605:                           $scantronconf{LastName}  => 'LastName',
 4606:                           $scantronconf{Qstart}    => 'Qstart',
 4607:                         );
 4608:             my @ordered;
 4609:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4610:                 push(@ordered,$bynum{$item});
 4611:             }
 4612:             my %mapstart = (
 4613:                               CODEstart => 'CODE',
 4614:                               IDstart   => 'ID',
 4615:                               PaperID   => 'PaperID',
 4616:                               FirstName => 'FirstName',
 4617:                               LastName  => 'LastName',
 4618:                               Qstart    => 'FirstQuestion',
 4619:                            );
 4620:             my %maplength = (
 4621:                               CODEstart => 'CODElength',
 4622:                               IDstart   => 'IDlength',
 4623:                               PaperID   => 'PaperIDlength',
 4624:                               FirstName => 'FirstNamelength',
 4625:                               LastName  => 'LastNamelength',
 4626:             );
 4627:             if (open(my $fh,'<',$fullpath)) {
 4628:                 my $output;
 4629:                 my %lettdig = &letter_to_digits();
 4630:                 my %diglett = reverse(%lettdig);
 4631:                 my $numletts = scalar(keys(%lettdig));
 4632:                 my $num = 0;
 4633:                 while (my $line=<$fh>) {
 4634:                     $num ++;
 4635:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4636:                     $line =~ s{[\r\n]+$}{};
 4637:                     my %found;
 4638:                     my @values = split(/,/,$line);
 4639:                     my ($qstart,$record);
 4640:                     for (my $i=0; $i<@values; $i++) {
 4641:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4642:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4643:                             if ($values[$i] eq '') {
 4644:                                 $values[$i] = $scantronconf{'Qoff'};
 4645:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4646:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4647:                                     $values[$i] = $lettdig{uc($values[$i])};
 4648:                                 }
 4649:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4650:                                 if ($values[$i] =~ /^[0-9]$/) {
 4651:                                     $values[$i] = $diglett{$values[$i]};
 4652:                                 }
 4653:                             } else {
 4654:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4655:                                     my $digit;
 4656:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4657:                                         $digit = $lettdig{uc($values[$i])}-1;
 4658:                                         if ($values[$i] eq 'J') {
 4659:                                             $digit += $numletts;
 4660:                                         }
 4661:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4662:                                         $digit = $values[$i]-1;
 4663:                                         if ($values[$i] eq '0') {
 4664:                                             $digit += $numletts;
 4665:                                         }
 4666:                                     }
 4667:                                     my $qval='';
 4668:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4669:                                         if ($j == $digit) {
 4670:                                             $qval .= $scantronconf{'Qon'};
 4671:                                         } else {
 4672:                                             $qval .= $scantronconf{'Qoff'};
 4673:                                         }
 4674:                                     }
 4675:                                     $values[$i] = $qval;
 4676:                                 }
 4677:                             }
 4678:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4679:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4680:                             }
 4681:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4682:                             if ($numblank > 0) {
 4683:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4684:                             }
 4685:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4686:                                 $qstart = $i;
 4687:                                 $found{$csvbynum{$i}} = $values[$i];
 4688:                             } else {
 4689:                                 $found{'FirstQuestion'} .= $values[$i];
 4690:                             }
 4691:                         } elsif (exists($csvbynum{$i})) {
 4692:                             if ($csvoptions{'rem'}) {
 4693:                                 $values[$i] =~ s/^\s+//;
 4694:                             }
 4695:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4696:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4697:                                     $values[$i] = '0'.$values[$i];
 4698:                                 }
 4699:                             }
 4700:                             $found{$csvbynum{$i}} = $values[$i];
 4701:                         }
 4702:                     }
 4703:                     foreach my $item (@ordered) {
 4704:                         my $currlength = 1+length($record);
 4705:                         my $numspaces = $scantronconf{$item} - $currlength;
 4706:                         if ($numspaces > 0) {
 4707:                             $record .= (' ' x $numspaces);
 4708:                         }
 4709:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4710:                             unless ($item eq 'Qstart') {
 4711:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4712:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4713:                                 }
 4714:                             }
 4715:                             $record .= $found{$mapstart{$item}};
 4716:                         }
 4717:                     }
 4718:                     $output .= "$record\n";
 4719:                 }
 4720:                 close($fh);
 4721:                 if ($output) {
 4722:                     if (open(my $fh,'>',$fullpath)) {
 4723:                         print $fh $output;
 4724:                         close($fh);
 4725:                     }
 4726:                 }
 4727:             }
 4728:         }
 4729:         return;
 4730:     }
 4731: }
 4732: 
 4733: sub letter_to_digits {
 4734:     my %lettdig = (
 4735:                     A => 1,
 4736:                     B => 2,
 4737:                     C => 3,
 4738:                     D => 4,
 4739:                     E => 5,
 4740:                     F => 6,
 4741:                     G => 7,
 4742:                     H => 8,
 4743:                     I => 9,
 4744:                     J => 0,
 4745:                   );
 4746:     return %lettdig;
 4747: }
 4748: 
 4749: sub get_scantron_config {
 4750:     my ($which,$cdom) = @_;
 4751:     my @lines = &get_scantronformat_file($cdom);
 4752:     my %config;
 4753:     #FIXME probably should move to XML it has already gotten a bit much now
 4754:     foreach my $line (@lines) {
 4755:         my ($name,$descrip)=split(/:/,$line);
 4756:         if ($name ne $which ) { next; }
 4757:         chomp($line);
 4758:         my @config=split(/:/,$line);
 4759:         $config{'name'}=$config[0];
 4760:         $config{'description'}=$config[1];
 4761:         $config{'CODElocation'}=$config[2];
 4762:         $config{'CODEstart'}=$config[3];
 4763:         $config{'CODElength'}=$config[4];
 4764:         $config{'IDstart'}=$config[5];
 4765:         $config{'IDlength'}=$config[6];
 4766:         $config{'Qstart'}=$config[7];
 4767:         $config{'Qlength'}=$config[8];
 4768:         $config{'Qoff'}=$config[9];
 4769:         $config{'Qon'}=$config[10];
 4770:         $config{'PaperID'}=$config[11];
 4771:         $config{'PaperIDlength'}=$config[12];
 4772:         $config{'FirstName'}=$config[13];
 4773:         $config{'FirstNamelength'}=$config[14];
 4774:         $config{'LastName'}=$config[15];
 4775:         $config{'LastNamelength'}=$config[16];
 4776:         $config{'BubblesPerRow'}=$config[17];
 4777:         last;
 4778:     }
 4779:     return %config;
 4780: }
 4781: 
 4782: sub get_scantronformat_file {
 4783:     my ($cdom) = @_;
 4784:     if ($cdom eq '') {
 4785:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4786:     }
 4787:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4788:     my $gottab = 0;
 4789:     my @lines;
 4790:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4791:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4792:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4793:             if ($formatfile ne '-1') {
 4794:                 @lines = split("\n",$formatfile,-1);
 4795:                 $gottab = 1;
 4796:             }
 4797:         }
 4798:     }
 4799:     if (!$gottab) {
 4800:         my $confname = $cdom.'-domainconfig';
 4801:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4802:         my $formatfile = &getfile($default);
 4803:         if ($formatfile ne '-1') {
 4804:             @lines = split("\n",$formatfile,-1);
 4805:             $gottab = 1;
 4806:         }
 4807:     }
 4808:     if (!$gottab) {
 4809:         my @domains = &current_machine_domains();
 4810:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4811:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4812:                 @lines = <$fh>;
 4813:                 close($fh);
 4814:             }
 4815:         } else {
 4816:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4817:                 @lines = <$fh>;
 4818:                 close($fh);
 4819:             }
 4820:         }
 4821:     }
 4822:     return @lines;
 4823: }
 4824: 
 4825: sub removeuploadedurl {
 4826:     my ($url)=@_;	
 4827:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4828:     return &removeuserfile($uname,$udom,$fname);
 4829: }
 4830: 
 4831: sub removeuserfile {
 4832:     my ($docuname,$docudom,$fname)=@_;
 4833:     my $home=&homeserver($docuname,$docudom);    
 4834:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4835:     if ($result eq 'ok') {	
 4836:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4837:             my $metafile = $fname.'.meta';
 4838:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4839: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4840:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4841:             my $sqlresult = 
 4842:                 &update_portfolio_table($docuname,$docudom,$file,
 4843:                                         'portfolio_metadata',$group,
 4844:                                         'delete');
 4845:         }
 4846:     }
 4847:     return $result;
 4848: }
 4849: 
 4850: sub mkdiruserfile {
 4851:     my ($docuname,$docudom,$dir)=@_;
 4852:     my $home=&homeserver($docuname,$docudom);
 4853:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4854: }
 4855: 
 4856: sub renameuserfile {
 4857:     my ($docuname,$docudom,$old,$new)=@_;
 4858:     my $home=&homeserver($docuname,$docudom);
 4859:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4860:                         &escape("$old").':'.&escape("$new"),$home);
 4861:     if ($result eq 'ok') {
 4862:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4863:             my $oldmeta = $old.'.meta';
 4864:             my $newmeta = $new.'.meta';
 4865:             my $metaresult = 
 4866:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4867: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4868:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4869:             my $sqlresult = 
 4870:                 &update_portfolio_table($docuname,$docudom,$file,
 4871:                                         'portfolio_metadata',$group,
 4872:                                         'delete');
 4873:         }
 4874:     }
 4875:     return $result;
 4876: }
 4877: 
 4878: # ------------------------------------------------------------------------- Log
 4879: 
 4880: sub log {
 4881:     my ($dom,$nam,$hom,$what)=@_;
 4882:     return critical("log:$dom:$nam:$what",$hom);
 4883: }
 4884: 
 4885: # ------------------------------------------------------------------ Course Log
 4886: #
 4887: # This routine flushes several buffers of non-mission-critical nature
 4888: #
 4889: 
 4890: sub flushcourselogs {
 4891:     &logthis('Flushing log buffers');
 4892: #
 4893: # course logs
 4894: # This is a log of all transactions in a course, which can be used
 4895: # for data mining purposes
 4896: #
 4897: # It also collects the courseid database, which lists last transaction
 4898: # times and course titles for all courseids
 4899: #
 4900:     my %courseidbuffer=();
 4901:     foreach my $crsid (keys(%courselogs)) {
 4902:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4903: 		          &escape($courselogs{$crsid}),
 4904: 		          $coursehombuf{$crsid}) eq 'ok') {
 4905: 	    delete $courselogs{$crsid};
 4906:         } else {
 4907:             &logthis('Failed to flush log buffer for '.$crsid);
 4908:             if (length($courselogs{$crsid})>40000) {
 4909:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4910:                         " exceeded maximum size, deleting.</font>");
 4911:                delete $courselogs{$crsid};
 4912:             }
 4913:         }
 4914:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4915:             'description' => $coursedescrbuf{$crsid},
 4916:             'inst_code'    => $courseinstcodebuf{$crsid},
 4917:             'type'        => $coursetypebuf{$crsid},
 4918:             'owner'       => $courseownerbuf{$crsid},
 4919:         };
 4920:     }
 4921: #
 4922: # Write course id database (reverse lookup) to homeserver of courses 
 4923: # Is used in pickcourse
 4924: #
 4925:     foreach my $crs_home (keys(%courseidbuffer)) {
 4926:         my $response = &courseidput(&host_domain($crs_home),
 4927:                                     $courseidbuffer{$crs_home},
 4928:                                     $crs_home,'timeonly');
 4929:     }
 4930: #
 4931: # File accesses
 4932: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4933: #
 4934:     foreach my $entry (keys(%accesshash)) {
 4935:         if ($entry =~ /___count$/) {
 4936:             my ($dom,$name);
 4937:             ($dom,$name,undef)=
 4938: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4939:             if (! defined($dom) || $dom eq '' || 
 4940:                 ! defined($name) || $name eq '') {
 4941:                 my $cid = $env{'request.course.id'};
 4942:                 $dom  = $env{'request.'.$cid.'.domain'};
 4943:                 $name = $env{'request.'.$cid.'.num'};
 4944:             }
 4945:             my $value = $accesshash{$entry};
 4946:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4947:             my %temphash=($url => $value);
 4948:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4949:             if ($result eq 'ok') {
 4950:                 delete $accesshash{$entry};
 4951:             }
 4952:         } else {
 4953:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4954:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4955:             my %temphash=($entry => $accesshash{$entry});
 4956:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4957:                 delete $accesshash{$entry};
 4958:             }
 4959:         }
 4960:     }
 4961: #
 4962: # Roles
 4963: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4964: #
 4965:     foreach my $entry (keys(%userrolehash)) {
 4966:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4967: 	    split(/\:/,$entry);
 4968:         if (&Apache::lonnet::put('nohist_userroles',
 4969:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4970:                 $rudom,$runame) eq 'ok') {
 4971: 	    delete $userrolehash{$entry};
 4972:         }
 4973:     }
 4974: #
 4975: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4976: #
 4977:     my %domrolebuffer = ();
 4978:     foreach my $entry (keys(%domainrolehash)) {
 4979:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4980:         if ($domrolebuffer{$rudom}) {
 4981:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4982:                       '='.&escape($domainrolehash{$entry});
 4983:         } else {
 4984:             $domrolebuffer{$rudom}.=&escape($entry).
 4985:                       '='.&escape($domainrolehash{$entry});
 4986:         }
 4987:         delete $domainrolehash{$entry};
 4988:     }
 4989:     foreach my $dom (keys(%domrolebuffer)) {
 4990: 	my %servers;
 4991: 	if (defined(&domain($dom,'primary'))) {
 4992: 	    my $primary=&domain($dom,'primary');
 4993: 	    my $hostname=&hostname($primary);
 4994: 	    $servers{$primary} = $hostname;
 4995: 	} else { 
 4996: 	    %servers = &get_servers($dom,'library');
 4997: 	}
 4998: 	foreach my $tryserver (keys(%servers)) {
 4999: 	    if (&reply('domroleput:'.$dom.':'.
 5000: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5001: 		last;
 5002: 	    } else {  
 5003: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5004: 	    }
 5005:         }
 5006:     }
 5007:     $dumpcount++;
 5008: }
 5009: 
 5010: sub courselog {
 5011:     my $what=shift;
 5012:     $what=time.':'.$what;
 5013:     unless ($env{'request.course.id'}) { return ''; }
 5014:     $coursedombuf{$env{'request.course.id'}}=
 5015:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5016:     $coursenumbuf{$env{'request.course.id'}}=
 5017:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5018:     $coursehombuf{$env{'request.course.id'}}=
 5019:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5020:     $coursedescrbuf{$env{'request.course.id'}}=
 5021:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5022:     $courseinstcodebuf{$env{'request.course.id'}}=
 5023:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5024:     $courseownerbuf{$env{'request.course.id'}}=
 5025:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5026:     $coursetypebuf{$env{'request.course.id'}}=
 5027:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5028:     if (defined $courselogs{$env{'request.course.id'}}) {
 5029: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5030:     } else {
 5031: 	$courselogs{$env{'request.course.id'}}.=$what;
 5032:     }
 5033:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5034: 	&flushcourselogs();
 5035:     }
 5036: }
 5037: 
 5038: sub courseacclog {
 5039:     my $fnsymb=shift;
 5040:     unless ($env{'request.course.id'}) { return ''; }
 5041:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5042:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5043:         $what.=':POST';
 5044:         # FIXME: Probably ought to escape things....
 5045: 	foreach my $key (keys(%env)) {
 5046:             if ($key=~/^form\.(.*)/) {
 5047:                 my $formitem = $1;
 5048:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5049:                     $what.=':'.$formitem.'='.$env{$key};
 5050:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5051:                     if ($formitem eq 'proctorpassword') {
 5052:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5053:                     } else {
 5054:                         $what.=':'.$formitem.'='.$env{$key};
 5055:                     }
 5056:                 }
 5057:             }
 5058:         }
 5059:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5060:         # FIXME: We should not be depending on a form parameter that someone
 5061:         # editing lonsearchcat.pm might change in the future.
 5062:         if ($env{'form.phase'} eq 'course_search') {
 5063:             $what.= ':POST';
 5064:             # FIXME: Probably ought to escape things....
 5065:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5066:                                  'crsdiscuss') {
 5067:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5068:             }
 5069:         }
 5070:     }
 5071:     &courselog($what);
 5072: }
 5073: 
 5074: sub countacc {
 5075:     my $url=&declutter(shift);
 5076:     return if (! defined($url) || $url eq '');
 5077:     unless ($env{'request.course.id'}) { return ''; }
 5078: #
 5079: # Mark that this url was used in this course
 5080: #
 5081:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5082: #
 5083: # Increase the access count for this resource in this child process
 5084: #
 5085:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5086:     $accesshash{$key}++;
 5087: }
 5088: 
 5089: sub linklog {
 5090:     my ($from,$to)=@_;
 5091:     $from=&declutter($from);
 5092:     $to=&declutter($to);
 5093:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5094:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5095: }
 5096: 
 5097: sub statslog {
 5098:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5099:     if ($users<2) { return; }
 5100:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5101:             'course'       => $env{'request.course.id'},
 5102:             'sections'     => '"all"',
 5103:             'num_students' => $users,
 5104:             'part'         => $part,
 5105:             'symb'         => $symb,
 5106:             'mean_tries'   => $av_attempts,
 5107:             'deg_of_diff'  => $degdiff});
 5108:     foreach my $key (keys(%dynstore)) {
 5109:         $accesshash{$key}=$dynstore{$key};
 5110:     }
 5111: }
 5112:   
 5113: sub userrolelog {
 5114:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5115:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5116:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5117:        $userrolehash
 5118:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5119:                     =$tend.':'.$tstart;
 5120:     }
 5121:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5122:        $userrolehash
 5123:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5124:                     =$tend.':'.$tstart;
 5125:     }
 5126:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5127:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5128:        $domainrolehash
 5129:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5130:                     = $tend.':'.$tstart;
 5131:     }
 5132: }
 5133: 
 5134: sub courserolelog {
 5135:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5136:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5137:         my $cdom = $1;
 5138:         my $cnum = $2;
 5139:         my $sec = $3;
 5140:         my $namespace = 'rolelog';
 5141:         my %storehash = (
 5142:                            role    => $trole,
 5143:                            start   => $tstart,
 5144:                            end     => $tend,
 5145:                            selfenroll => $selfenroll,
 5146:                            context    => $context,
 5147:                         );
 5148:         if ($trole eq 'gr') {
 5149:             $namespace = 'groupslog';
 5150:             $storehash{'group'} = $sec;
 5151:         } else {
 5152:             $storehash{'section'} = $sec;
 5153:         }
 5154:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5155:                    $domain,$cnum,$cdom);
 5156:         if (($trole ne 'st') || ($sec ne '')) {
 5157:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5158:         }
 5159:     }
 5160:     return;
 5161: }
 5162: 
 5163: sub domainrolelog {
 5164:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5165:     if ($area =~ m{^/($match_domain)/$}) {
 5166:         my $cdom = $1;
 5167:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5168:         my $namespace = 'rolelog';
 5169:         my %storehash = (
 5170:                            role    => $trole,
 5171:                            start   => $tstart,
 5172:                            end     => $tend,
 5173:                            context => $context,
 5174:                         );
 5175:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5176:                    $domain,$domconfiguser,$cdom);
 5177:     }
 5178:     return;
 5179: 
 5180: }
 5181: 
 5182: sub coauthorrolelog {
 5183:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5184:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5185:         my $audom = $1;
 5186:         my $auname = $2;
 5187:         my $namespace = 'rolelog';
 5188:         my %storehash = (
 5189:                            role    => $trole,
 5190:                            start   => $tstart,
 5191:                            end     => $tend,
 5192:                            context => $context,
 5193:                         );
 5194:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5195:                    $domain,$auname,$audom);
 5196:     }
 5197:     return;
 5198: }
 5199: 
 5200: sub get_course_adv_roles {
 5201:     my ($cid,$codes) = @_;
 5202:     $cid=$env{'request.course.id'} unless (defined($cid));
 5203:     my %coursehash=&coursedescription($cid);
 5204:     my $crstype = &Apache::loncommon::course_type($cid);
 5205:     my %nothide=();
 5206:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5207:         if ($user !~ /:/) {
 5208: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5209:         } else {
 5210:             $nothide{$user}=1;
 5211:         }
 5212:     }
 5213:     my @possdoms = ($coursehash{'domain'});
 5214:     if ($coursehash{'checkforpriv'}) {
 5215:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5216:     }
 5217:     my %returnhash=();
 5218:     my %dumphash=
 5219:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5220:     my $now=time;
 5221:     my %privileged;
 5222:     foreach my $entry (keys(%dumphash)) {
 5223: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5224:         if (($tstart) && ($tstart<0)) { next; }
 5225:         if (($tend) && ($tend<$now)) { next; }
 5226:         if (($tstart) && ($now<$tstart)) { next; }
 5227:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5228: 	if ($username eq '' || $domain eq '') { next; }
 5229:         if ((&privileged($username,$domain,\@possdoms)) &&
 5230:             (!$nothide{$username.':'.$domain})) { next; }
 5231: 	if ($role eq 'cr') { next; }
 5232:         if ($codes) {
 5233:             if ($section) { $role .= ':'.$section; }
 5234:             if ($returnhash{$role}) {
 5235:                 $returnhash{$role}.=','.$username.':'.$domain;
 5236:             } else {
 5237:                 $returnhash{$role}=$username.':'.$domain;
 5238:             }
 5239:         } else {
 5240:             my $key=&plaintext($role,$crstype);
 5241:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5242:             if ($returnhash{$key}) {
 5243: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5244:             } else {
 5245:                 $returnhash{$key}=$username.':'.$domain;
 5246:             }
 5247:         }
 5248:     }
 5249:     return %returnhash;
 5250: }
 5251: 
 5252: sub get_my_roles {
 5253:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5254:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5255:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5256:     my (%dumphash,%nothide);
 5257:     if ($context eq 'userroles') {
 5258:         %dumphash = &dump('roles',$udom,$uname);
 5259:     } else {
 5260:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5261:         if ($hidepriv) {
 5262:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5263:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5264:                 if ($user !~ /:/) {
 5265:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5266:                 } else {
 5267:                     $nothide{$user} = 1;
 5268:                 }
 5269:             }
 5270:         }
 5271:     }
 5272:     my %returnhash=();
 5273:     my $now=time;
 5274:     my %privileged;
 5275:     foreach my $entry (keys(%dumphash)) {
 5276:         my ($role,$tend,$tstart);
 5277:         if ($context eq 'userroles') {
 5278:             next if ($entry =~ /^rolesdef/);
 5279: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5280:         } else {
 5281:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5282:         }
 5283:         if (($tstart) && ($tstart<0)) { next; }
 5284:         my $status = 'active';
 5285:         if (($tend) && ($tend<=$now)) {
 5286:             $status = 'previous';
 5287:         } 
 5288:         if (($tstart) && ($now<$tstart)) {
 5289:             $status = 'future';
 5290:         }
 5291:         if (ref($types) eq 'ARRAY') {
 5292:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5293:                 next;
 5294:             } 
 5295:         } else {
 5296:             if ($status ne 'active') {
 5297:                 next;
 5298:             }
 5299:         }
 5300:         my ($rolecode,$username,$domain,$section,$area);
 5301:         if ($context eq 'userroles') {
 5302:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5303:             (undef,$domain,$username,$section) = split(/\//,$area);
 5304:         } else {
 5305:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5306:         }
 5307:         if (ref($roledoms) eq 'ARRAY') {
 5308:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5309:                 next;
 5310:             }
 5311:         }
 5312:         if (ref($roles) eq 'ARRAY') {
 5313:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5314:                 if ($role =~ /^cr\//) {
 5315:                     if (!grep(/^cr$/,@{$roles})) {
 5316:                         next;
 5317:                     }
 5318:                 } elsif ($role =~ /^gr\//) {
 5319:                     if (!grep(/^gr$/,@{$roles})) {
 5320:                         next;
 5321:                     }
 5322:                 } else {
 5323:                     next;
 5324:                 }
 5325:             }
 5326:         }
 5327:         if ($hidepriv) {
 5328:             my @privroles = ('dc','su');
 5329:             if ($context eq 'userroles') {
 5330:                 next if (grep(/^\Q$role\E$/,@privroles));
 5331:             } else {
 5332:                 my $possdoms = [$domain];
 5333:                 if (ref($roledoms) eq 'ARRAY') {
 5334:                    push(@{$possdoms},@{$roledoms}); 
 5335:                 }
 5336:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5337:                     if (!$nothide{$username.':'.$domain}) {
 5338:                         next;
 5339:                     }
 5340:                 }
 5341:             }
 5342:         }
 5343:         if ($withsec) {
 5344:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5345:                 $tstart.':'.$tend;
 5346:         } else {
 5347:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5348:         }
 5349:     }
 5350:     return %returnhash;
 5351: }
 5352: 
 5353: sub get_all_adhocroles {
 5354:     my ($dom) = @_;
 5355:     my @roles_by_num = ();
 5356:     my %domdefaults = &get_domain_defaults($dom);
 5357:     my (%description,%access_in_dom,%access_info);
 5358:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5359:         my $count = 0;
 5360:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5361:         my %ordered;
 5362:         foreach my $role (sort(keys(%domcurrent))) {
 5363:             my ($order,$desc,$access_in_dom);
 5364:             if (ref($domcurrent{$role}) eq 'HASH') {
 5365:                 $order = $domcurrent{$role}{'order'};
 5366:                 $desc = $domcurrent{$role}{'desc'};
 5367:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5368:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5369:             }
 5370:             if ($order eq '') {
 5371:                 $order = $count;
 5372:             }
 5373:             $ordered{$order} = $role;
 5374:             if ($desc ne '') {
 5375:                 $description{$role} = $desc;
 5376:             } else {
 5377:                 $description{$role}= $role;
 5378:             }
 5379:             $count++;
 5380:         }
 5381:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5382:             push(@roles_by_num,$ordered{$item});
 5383:         }
 5384:     }
 5385:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5386: }
 5387: 
 5388: sub get_my_adhocroles {
 5389:     my ($cid,$checkreg) = @_;
 5390:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5391:     if ($env{'request.course.id'} eq $cid) {
 5392:         $cdom = $env{'course.'.$cid.'.domain'};
 5393:         $cnum = $env{'course.'.$cid.'.num'};
 5394:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5395:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5396:         $cdom = $1;
 5397:         $cnum = $2;
 5398:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5399:                                      $cdom,$cnum);
 5400:     }
 5401:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5402:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5403:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5404:         if ($rosterhash{$user} ne '') {
 5405:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5406:             return ([],{}) if ($type eq 'auto');
 5407:         }
 5408:     }
 5409:     if (($cdom ne '') && ($cnum ne ''))  {
 5410:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5411:             my $then=$env{'user.login.time'};
 5412:             my $update=$env{'user.update.time'};
 5413:             if (!$update) {
 5414:                 $update = $then;
 5415:             }
 5416:             my @liveroles;
 5417:             foreach my $role ('dh','da') {
 5418:                 if ($env{"user.role.$role./$cdom/"}) {
 5419:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5420:                     my $limit = $update;
 5421:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5422:                         $limit = $then;
 5423:                     }
 5424:                     my $activerole = 1;
 5425:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5426:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5427:                     if ($activerole) {
 5428:                         push(@liveroles,$role);
 5429:                     }
 5430:                 }
 5431:             }
 5432:             if (@liveroles) {
 5433:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5434:                     my ($accessref,$accessinfo,%access_in_dom);
 5435:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5436:                     if (ref($roles_by_num) eq 'ARRAY') {
 5437:                         if (@{$roles_by_num}) {
 5438:                             my %settings;
 5439:                             if ($env{'request.course.id'} eq $cid) {
 5440:                                 foreach my $envkey (keys(%env)) {
 5441:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5442:                                         $settings{$1} = $env{$envkey};
 5443:                                     }
 5444:                                 }
 5445:                             } else {
 5446:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5447:                             }
 5448:                             my %setincrs;
 5449:                             if ($settings{'internal.adhocaccess'}) {
 5450:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5451:                             }
 5452:                             my @statuses;
 5453:                             if ($env{'environment.inststatus'}) {
 5454:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5455:                             }
 5456:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5457:                             if (ref($accessref) eq 'HASH') {
 5458:                                 %access_in_dom = %{$accessref};
 5459:                             }
 5460:                             foreach my $role (@{$roles_by_num}) {
 5461:                                 my ($curraccess,@okstatus,@personnel);
 5462:                                 if ($setincrs{$role}) {
 5463:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5464:                                     if ($curraccess eq 'status') {
 5465:                                         @okstatus = split(/\&/,$rest);
 5466:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5467:                                         @personnel = split(/\&/,$rest);
 5468:                                     }
 5469:                                 } else {
 5470:                                     $curraccess = $access_in_dom{$role};
 5471:                                     if (ref($accessinfo) eq 'HASH') {
 5472:                                         if ($curraccess eq 'status') {
 5473:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5474:                                                 @okstatus = @{$accessinfo->{$role}};
 5475:                                             }
 5476:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5477:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5478:                                                 @personnel = @{$accessinfo->{$role}};
 5479:                                             }
 5480:                                         }
 5481:                                     }
 5482:                                 }
 5483:                                 if ($curraccess eq 'none') {
 5484:                                     next;
 5485:                                 } elsif ($curraccess eq 'all') {
 5486:                                     push(@possroles,$role);
 5487:                                 } elsif ($curraccess eq 'dh') {
 5488:                                     if (grep(/^dh$/,@liveroles)) {
 5489:                                         push(@possroles,$role);
 5490:                                     } else {
 5491:                                         next;
 5492:                                     }
 5493:                                 } elsif ($curraccess eq 'da') {
 5494:                                     if (grep(/^da$/,@liveroles)) {
 5495:                                         push(@possroles,$role);
 5496:                                     } else {
 5497:                                         next;
 5498:                                     }
 5499:                                 } elsif ($curraccess eq 'status') {
 5500:                                     if (@okstatus) {
 5501:                                         if (!@statuses) {
 5502:                                             if (grep(/^default$/,@okstatus)) {
 5503:                                                 push(@possroles,$role);
 5504:                                             }
 5505:                                         } else {
 5506:                                             foreach my $status (@okstatus) {
 5507:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5508:                                                     push(@possroles,$role);
 5509:                                                     last;
 5510:                                                 }
 5511:                                             }
 5512:                                         }
 5513:                                     }
 5514:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5515:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5516:                                         if ($curraccess eq 'exc') {
 5517:                                             push(@possroles,$role);
 5518:                                         }
 5519:                                     } elsif ($curraccess eq 'inc') {
 5520:                                         push(@possroles,$role);
 5521:                                     }
 5522:                                 }
 5523:                             }
 5524:                         }
 5525:                     }
 5526:                 }
 5527:             }
 5528:         }
 5529:     }
 5530:     unless (ref($description) eq 'HASH') {
 5531:         if (ref($roles_by_num) eq 'ARRAY') {
 5532:             my %desc;
 5533:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5534:             $description = \%desc;
 5535:         } else {
 5536:             $description = {};
 5537:         }
 5538:     }
 5539:     return (\@possroles,$description);
 5540: }
 5541: 
 5542: # ----------------------------------------------------- Frontpage Announcements
 5543: #
 5544: #
 5545: 
 5546: sub postannounce {
 5547:     my ($server,$text)=@_;
 5548:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5549:     unless ($text=~/\w/) { $text=''; }
 5550:     return &reply('setannounce:'.&escape($text),$server);
 5551: }
 5552: 
 5553: sub getannounce {
 5554: 
 5555:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5556: 	my $announcement='';
 5557: 	while (my $line = <$fh>) { $announcement .= $line; }
 5558: 	close($fh);
 5559: 	if ($announcement=~/\w/) { 
 5560: 	    return 
 5561:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5562:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5563: 	} else {
 5564: 	    return '';
 5565: 	}
 5566:     } else {
 5567: 	return '';
 5568:     }
 5569: }
 5570: 
 5571: # ---------------------------------------------------------- Course ID routines
 5572: # Deal with domain's nohist_courseid.db files
 5573: #
 5574: 
 5575: sub courseidput {
 5576:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5577:     return unless (ref($storehash) eq 'HASH');
 5578:     my $outcome;
 5579:     if ($caller eq 'timeonly') {
 5580:         my $cids = '';
 5581:         foreach my $item (keys(%$storehash)) {
 5582:             $cids.=&escape($item).'&';
 5583:         }
 5584:         $cids=~s/\&$//;
 5585:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5586:                           $coursehome);       
 5587:     } else {
 5588:         my $items = '';
 5589:         foreach my $item (keys(%$storehash)) {
 5590:             $items.= &escape($item).'='.
 5591:                      &freeze_escape($$storehash{$item}).'&';
 5592:         }
 5593:         $items=~s/\&$//;
 5594:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5595:                           $coursehome);
 5596:     }
 5597:     if ($outcome eq 'unknown_cmd') {
 5598:         my $what;
 5599:         foreach my $cid (keys(%$storehash)) {
 5600:             $what .= &escape($cid).'=';
 5601:             foreach my $item ('description','inst_code','owner','type') {
 5602:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5603:             }
 5604:             $what =~ s/\:$/&/;
 5605:         }
 5606:         $what =~ s/\&$//;  
 5607:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5608:     } else {
 5609:         return $outcome;
 5610:     }
 5611: }
 5612: 
 5613: sub courseiddump {
 5614:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5615:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5616:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5617:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5618:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5619:     my $as_hash = 1;
 5620:     my %returnhash;
 5621:     if (!$domfilter) { $domfilter=''; }
 5622:     my %libserv = &all_library();
 5623:     foreach my $tryserver (keys(%libserv)) {
 5624:         if ( (  $hostidflag == 1 
 5625: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5626: 	     || (!defined($hostidflag)) ) {
 5627: 
 5628: 	    if (($domfilter eq '') ||
 5629: 		(&host_domain($tryserver) eq $domfilter)) {
 5630:                 my $rep;
 5631:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5632:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5633:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5634:                                 &escape($descfilter), &escape($instcodefilter), 
 5635:                                 &escape($ownerfilter), &escape($coursefilter),
 5636:                                 &escape($typefilter), &escape($regexp_ok), 
 5637:                                 $as_hash, &escape($selfenrollonly), 
 5638:                                 &escape($catfilter), $showhidden, $caller, 
 5639:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5640:                                 &escape($createdbefore), &escape($createdafter), 
 5641:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5642:                                 $reqcrsdom,&escape($reqinstcode))));
 5643:                 } else {
 5644:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5645:                              $sincefilter.':'.&escape($descfilter).':'.
 5646:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5647:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5648:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5649:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5650:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5651:                              &escape($cc_clone).':'.$cloneonly.':'.
 5652:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5653:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5654:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5655:                 }
 5656:                      
 5657:                 my @pairs=split(/\&/,$rep);
 5658:                 foreach my $item (@pairs) {
 5659:                     my ($key,$value)=split(/\=/,$item,2);
 5660:                     $key = &unescape($key);
 5661:                     next if ($key =~ /^error: 2 /);
 5662:                     my $result = &thaw_unescape($value);
 5663:                     if (ref($result) eq 'HASH') {
 5664:                         $returnhash{$key}=$result;
 5665:                     } else {
 5666:                         my @responses = split(/:/,$value);
 5667:                         my @items = ('description','inst_code','owner','type');
 5668:                         for (my $i=0; $i<@responses; $i++) {
 5669:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5670:                         }
 5671:                     }
 5672:                 }
 5673:             }
 5674:         }
 5675:     }
 5676:     return %returnhash;
 5677: }
 5678: 
 5679: sub courselastaccess {
 5680:     my ($cdom,$cnum,$hostidref) = @_;
 5681:     my %returnhash;
 5682:     if ($cdom && $cnum) {
 5683:         my $chome = &homeserver($cnum,$cdom);
 5684:         if ($chome ne 'no_host') {
 5685:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5686:             &extract_lastaccess(\%returnhash,$rep);
 5687:         }
 5688:     } else {
 5689:         if (!$cdom) { $cdom=''; }
 5690:         my %libserv = &all_library();
 5691:         foreach my $tryserver (keys(%libserv)) {
 5692:             if (ref($hostidref) eq 'ARRAY') {
 5693:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5694:             } 
 5695:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5696:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5697:                 &extract_lastaccess(\%returnhash,$rep);
 5698:             }
 5699:         }
 5700:     }
 5701:     return %returnhash;
 5702: }
 5703: 
 5704: sub extract_lastaccess {
 5705:     my ($returnhash,$rep) = @_;
 5706:     if (ref($returnhash) eq 'HASH') {
 5707:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5708:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5709:                  $rep eq '') {
 5710:             my @pairs=split(/\&/,$rep);
 5711:             foreach my $item (@pairs) {
 5712:                 my ($key,$value)=split(/\=/,$item,2);
 5713:                 $key = &unescape($key);
 5714:                 next if ($key =~ /^error: 2 /);
 5715:                 $returnhash->{$key} = &thaw_unescape($value);
 5716:             }
 5717:         }
 5718:     }
 5719:     return;
 5720: }
 5721: 
 5722: # ---------------------------------------------------------- DC e-mail
 5723: 
 5724: sub dcmailput {
 5725:     my ($domain,$msgid,$message,$server)=@_;
 5726:     my $status = &Apache::lonnet::critical(
 5727:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5728:        &escape($message),$server);
 5729:     return $status;
 5730: }
 5731: 
 5732: sub dcmaildump {
 5733:     my ($dom,$startdate,$enddate,$senders) = @_;
 5734:     my %returnhash=();
 5735: 
 5736:     if (defined(&domain($dom,'primary'))) {
 5737:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5738:                                                          &escape($enddate).':';
 5739: 	my @esc_senders=map { &escape($_)} @$senders;
 5740: 	$cmd.=&escape(join('&',@esc_senders));
 5741: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5742:             my ($key,$value) = split(/\=/,$line,2);
 5743:             if (($key) && ($value)) {
 5744:                 $returnhash{&unescape($key)} = &unescape($value);
 5745:             }
 5746:         }
 5747:     }
 5748:     return %returnhash;
 5749: }
 5750: # ---------------------------------------------------------- Domain roles
 5751: 
 5752: sub get_domain_roles {
 5753:     my ($dom,$roles,$startdate,$enddate)=@_;
 5754:     if ((!defined($startdate)) || ($startdate eq '')) {
 5755:         $startdate = '.';
 5756:     }
 5757:     if ((!defined($enddate)) || ($enddate eq '')) {
 5758:         $enddate = '.';
 5759:     }
 5760:     my $rolelist;
 5761:     if (ref($roles) eq 'ARRAY') {
 5762:         $rolelist = join('&',@{$roles});
 5763:     }
 5764:     my %personnel = ();
 5765: 
 5766:     my %servers = &get_servers($dom,'library');
 5767:     foreach my $tryserver (keys(%servers)) {
 5768: 	%{$personnel{$tryserver}}=();
 5769: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5770: 					    &escape($startdate).':'.
 5771: 					    &escape($enddate).':'.
 5772: 					    &escape($rolelist), $tryserver))) {
 5773: 	    my ($key,$value) = split(/\=/,$line,2);
 5774: 	    if (($key) && ($value)) {
 5775: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5776: 	    }
 5777: 	}
 5778:     }
 5779:     return %personnel;
 5780: }
 5781: 
 5782: sub get_active_domroles {
 5783:     my ($dom,$roles) = @_;
 5784:     return () unless (ref($roles) eq 'ARRAY');
 5785:     my $now = time;
 5786:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5787:     my %domroles;
 5788:     foreach my $server (keys(%dompersonnel)) {
 5789:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5790:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5791:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5792:         }
 5793:     }
 5794:     return %domroles;
 5795: }
 5796: 
 5797: # ----------------------------------------------------------- Interval timing 
 5798: 
 5799: {
 5800: # Caches needed for speedup of navmaps
 5801: # We don't want to cache this for very long at all (5 seconds at most)
 5802: # 
 5803: # The user for whom we cache
 5804: my $cachedkey='';
 5805: # The cached times for this user
 5806: my %cachedtimes=();
 5807: # When this was last done
 5808: my $cachedtime='';
 5809: 
 5810: sub load_all_first_access {
 5811:     my ($uname,$udom,$ignorecache)=@_;
 5812:     if (($cachedkey eq $uname.':'.$udom) &&
 5813:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5814:         (!$ignorecache)) {
 5815:         return;
 5816:     }
 5817:     $cachedtime=time;
 5818:     $cachedkey=$uname.':'.$udom;
 5819:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5820: }
 5821: 
 5822: sub get_first_access {
 5823:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5824:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5825:     if ($argsymb) { $symb=$argsymb; }
 5826:     my ($map,$id,$res)=&decode_symb($symb);
 5827:     if ($argmap) { $map = $argmap; }
 5828:     if ($type eq 'course') {
 5829: 	$res='course';
 5830:     } elsif ($type eq 'map') {
 5831: 	$res=&symbread($map);
 5832:     } else {
 5833: 	$res=$symb;
 5834:     }
 5835:     &load_all_first_access($uname,$udom,$ignorecache);
 5836:     return $cachedtimes{"$courseid\0$res"};
 5837: }
 5838: 
 5839: sub set_first_access {
 5840:     my ($type,$interval)=@_;
 5841:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5842:     my ($map,$id,$res)=&decode_symb($symb);
 5843:     if ($type eq 'course') {
 5844: 	$res='course';
 5845:     } elsif ($type eq 'map') {
 5846: 	$res=&symbread($map);
 5847:     } else {
 5848: 	$res=$symb;
 5849:     }
 5850:     $cachedkey='';
 5851:     my $firstaccess=&get_first_access($type,$symb,$map);
 5852:     if ($firstaccess) {
 5853:         &logthis("First access time already set ($firstaccess) when attempting ".
 5854:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5855:                  "in $courseid");
 5856:         return 'already_set';
 5857:     } else {
 5858:         my $start = time;
 5859: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5860:                           $udom,$uname);
 5861:         if ($putres eq 'ok') {
 5862:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5863:                  $udom,$uname); 
 5864:             &appenv(
 5865:                      {
 5866:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5867:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5868:                      }
 5869:                   );
 5870:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5871:                 $cachedtimes{"$courseid\0$res"} = $start;
 5872:             }
 5873:         } elsif ($putres ne 'refused') {
 5874:             &logthis("Result: $putres when attempting to set first access time ".
 5875:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5876:         }
 5877:         return $putres;
 5878:     }
 5879:     return 'already_set';
 5880: }
 5881: }
 5882: 
 5883: # --------------------------------------------- Set Expire Date for Spreadsheet
 5884: 
 5885: sub expirespread {
 5886:     my ($uname,$udom,$stype,$usymb)=@_;
 5887:     my $cid=$env{'request.course.id'}; 
 5888:     if ($cid) {
 5889:        my $now=time;
 5890:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5891:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5892:                             $env{'course.'.$cid.'.num'}.
 5893: 	        	    ':nohist_expirationdates:'.
 5894:                             &escape($key).'='.$now,
 5895:                             $env{'course.'.$cid.'.home'})
 5896:     }
 5897:     return 'ok';
 5898: }
 5899: 
 5900: # ----------------------------------------------------- Devalidate Spreadsheets
 5901: 
 5902: sub devalidate {
 5903:     my ($symb,$uname,$udom)=@_;
 5904:     my $cid=$env{'request.course.id'}; 
 5905:     if ($cid) {
 5906:         # delete the stored spreadsheets for
 5907:         # - the student level sheet of this user in course's homespace
 5908:         # - the assessment level sheet for this resource 
 5909:         #   for this user in user's homespace
 5910: 	# - current conditional state info
 5911: 	my $key=$uname.':'.$udom.':';
 5912:         my $status=
 5913: 	    &del('nohist_calculatedsheets',
 5914: 		 [$key.'studentcalc:'],
 5915: 		 $env{'course.'.$cid.'.domain'},
 5916: 		 $env{'course.'.$cid.'.num'})
 5917: 		.' '.
 5918: 	    &del('nohist_calculatedsheets_'.$cid,
 5919: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5920:         unless ($status eq 'ok ok') {
 5921:            &logthis('Could not devalidate spreadsheet '.
 5922:                     $uname.' at '.$udom.' for '.
 5923: 		    $symb.': '.$status);
 5924:         }
 5925: 	&delenv('user.state.'.$cid);
 5926:     }
 5927: }
 5928: 
 5929: sub get_scalar {
 5930:     my ($string,$end) = @_;
 5931:     my $value;
 5932:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5933: 	$value = $1;
 5934:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5935: 	$value = $1;
 5936:     }
 5937:     return &unescape($value);
 5938: }
 5939: 
 5940: sub array2str {
 5941:   my (@array) = @_;
 5942:   my $result=&arrayref2str(\@array);
 5943:   $result=~s/^__ARRAY_REF__//;
 5944:   $result=~s/__END_ARRAY_REF__$//;
 5945:   return $result;
 5946: }
 5947: 
 5948: sub arrayref2str {
 5949:   my ($arrayref) = @_;
 5950:   my $result='__ARRAY_REF__';
 5951:   foreach my $elem (@$arrayref) {
 5952:     if(ref($elem) eq 'ARRAY') {
 5953:       $result.=&arrayref2str($elem).'&';
 5954:     } elsif(ref($elem) eq 'HASH') {
 5955:       $result.=&hashref2str($elem).'&';
 5956:     } elsif(ref($elem)) {
 5957:       #print("Got a ref of ".(ref($elem))." skipping.");
 5958:     } else {
 5959:       $result.=&escape($elem).'&';
 5960:     }
 5961:   }
 5962:   $result=~s/\&$//;
 5963:   $result .= '__END_ARRAY_REF__';
 5964:   return $result;
 5965: }
 5966: 
 5967: sub hash2str {
 5968:   my (%hash) = @_;
 5969:   my $result=&hashref2str(\%hash);
 5970:   $result=~s/^__HASH_REF__//;
 5971:   $result=~s/__END_HASH_REF__$//;
 5972:   return $result;
 5973: }
 5974: 
 5975: sub hashref2str {
 5976:   my ($hashref)=@_;
 5977:   my $result='__HASH_REF__';
 5978:   foreach my $key (sort(keys(%$hashref))) {
 5979:     if (ref($key) eq 'ARRAY') {
 5980:       $result.=&arrayref2str($key).'=';
 5981:     } elsif (ref($key) eq 'HASH') {
 5982:       $result.=&hashref2str($key).'=';
 5983:     } elsif (ref($key)) {
 5984:       $result.='=';
 5985:       #print("Got a ref of ".(ref($key))." skipping.");
 5986:     } else {
 5987: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5988:     }
 5989: 
 5990:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5991:       $result.=&arrayref2str($hashref->{$key}).'&';
 5992:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5993:       $result.=&hashref2str($hashref->{$key}).'&';
 5994:     } elsif(ref($hashref->{$key})) {
 5995:        $result.='&';
 5996:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5997:     } else {
 5998:       $result.=&escape($hashref->{$key}).'&';
 5999:     }
 6000:   }
 6001:   $result=~s/\&$//;
 6002:   $result .= '__END_HASH_REF__';
 6003:   return $result;
 6004: }
 6005: 
 6006: sub str2hash {
 6007:     my ($string)=@_;
 6008:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6009:     return %$hash;
 6010: }
 6011: 
 6012: sub str2hashref {
 6013:   my ($string) = @_;
 6014: 
 6015:   my %hash;
 6016: 
 6017:   if($string !~ /^__HASH_REF__/) {
 6018:       if (! ($string eq '' || !defined($string))) {
 6019: 	  $hash{'error'}='Not hash reference';
 6020:       }
 6021:       return (\%hash, $string);
 6022:   }
 6023: 
 6024:   $string =~ s/^__HASH_REF__//;
 6025: 
 6026:   while($string !~ /^__END_HASH_REF__/) {
 6027:       #key
 6028:       my $key='';
 6029:       if($string =~ /^__HASH_REF__/) {
 6030:           ($key, $string)=&str2hashref($string);
 6031:           if(defined($key->{'error'})) {
 6032:               $hash{'error'}='Bad data';
 6033:               return (\%hash, $string);
 6034:           }
 6035:       } elsif($string =~ /^__ARRAY_REF__/) {
 6036:           ($key, $string)=&str2arrayref($string);
 6037:           if($key->[0] eq 'Array reference error') {
 6038:               $hash{'error'}='Bad data';
 6039:               return (\%hash, $string);
 6040:           }
 6041:       } else {
 6042:           $string =~ s/^(.*?)=//;
 6043: 	  $key=&unescape($1);
 6044:       }
 6045:       $string =~ s/^=//;
 6046: 
 6047:       #value
 6048:       my $value='';
 6049:       if($string =~ /^__HASH_REF__/) {
 6050:           ($value, $string)=&str2hashref($string);
 6051:           if(defined($value->{'error'})) {
 6052:               $hash{'error'}='Bad data';
 6053:               return (\%hash, $string);
 6054:           }
 6055:       } elsif($string =~ /^__ARRAY_REF__/) {
 6056:           ($value, $string)=&str2arrayref($string);
 6057:           if($value->[0] eq 'Array reference error') {
 6058:               $hash{'error'}='Bad data';
 6059:               return (\%hash, $string);
 6060:           }
 6061:       } else {
 6062: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6063:       }
 6064:       $string =~ s/^&//;
 6065: 
 6066:       $hash{$key}=$value;
 6067:   }
 6068: 
 6069:   $string =~ s/^__END_HASH_REF__//;
 6070: 
 6071:   return (\%hash, $string);
 6072: }
 6073: 
 6074: sub str2array {
 6075:     my ($string)=@_;
 6076:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6077:     return @$array;
 6078: }
 6079: 
 6080: sub str2arrayref {
 6081:   my ($string) = @_;
 6082:   my @array;
 6083: 
 6084:   if($string !~ /^__ARRAY_REF__/) {
 6085:       if (! ($string eq '' || !defined($string))) {
 6086: 	  $array[0]='Array reference error';
 6087:       }
 6088:       return (\@array, $string);
 6089:   }
 6090: 
 6091:   $string =~ s/^__ARRAY_REF__//;
 6092: 
 6093:   while($string !~ /^__END_ARRAY_REF__/) {
 6094:       my $value='';
 6095:       if($string =~ /^__HASH_REF__/) {
 6096:           ($value, $string)=&str2hashref($string);
 6097:           if(defined($value->{'error'})) {
 6098:               $array[0] ='Array reference error';
 6099:               return (\@array, $string);
 6100:           }
 6101:       } elsif($string =~ /^__ARRAY_REF__/) {
 6102:           ($value, $string)=&str2arrayref($string);
 6103:           if($value->[0] eq 'Array reference error') {
 6104:               $array[0] ='Array reference error';
 6105:               return (\@array, $string);
 6106:           }
 6107:       } else {
 6108: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6109:       }
 6110:       $string =~ s/^&//;
 6111: 
 6112:       push(@array, $value);
 6113:   }
 6114: 
 6115:   $string =~ s/^__END_ARRAY_REF__//;
 6116: 
 6117:   return (\@array, $string);
 6118: }
 6119: 
 6120: # -------------------------------------------------------------------Temp Store
 6121: 
 6122: sub tmpreset {
 6123:   my ($symb,$namespace,$domain,$stuname) = @_;
 6124:   if (!$symb) {
 6125:     $symb=&symbread();
 6126:     if (!$symb) { $symb= $env{'request.url'}; }
 6127:   }
 6128:   $symb=escape($symb);
 6129: 
 6130:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6131:   $namespace=~s/\//\_/g;
 6132:   $namespace=~s/\W//g;
 6133: 
 6134:   if (!$domain) { $domain=$env{'user.domain'}; }
 6135:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6136:   if ($domain eq 'public' && $stuname eq 'public') {
 6137:       $stuname=&get_requestor_ip();
 6138:   }
 6139:   my $path=LONCAPA::tempdir();
 6140:   my %hash;
 6141:   if (tie(%hash,'GDBM_File',
 6142: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6143: 	  &GDBM_WRCREAT(),0640)) {
 6144:     foreach my $key (keys(%hash)) {
 6145:       if ($key=~ /:$symb/) {
 6146: 	delete($hash{$key});
 6147:       }
 6148:     }
 6149:   }
 6150: }
 6151: 
 6152: sub tmpstore {
 6153:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6154: 
 6155:   if (!$symb) {
 6156:     $symb=&symbread();
 6157:     if (!$symb) { $symb= $env{'request.url'}; }
 6158:   }
 6159:   $symb=escape($symb);
 6160: 
 6161:   if (!$namespace) {
 6162:     # I don't think we would ever want to store this for a course.
 6163:     # it seems this will only be used if we don't have a course.
 6164:     #$namespace=$env{'request.course.id'};
 6165:     #if (!$namespace) {
 6166:       $namespace=$env{'request.state'};
 6167:     #}
 6168:   }
 6169:   $namespace=~s/\//\_/g;
 6170:   $namespace=~s/\W//g;
 6171:   if (!$domain) { $domain=$env{'user.domain'}; }
 6172:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6173:   if ($domain eq 'public' && $stuname eq 'public') {
 6174:       $stuname=&get_requestor_ip();
 6175:   }
 6176:   my $now=time;
 6177:   my %hash;
 6178:   my $path=LONCAPA::tempdir();
 6179:   if (tie(%hash,'GDBM_File',
 6180: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6181: 	  &GDBM_WRCREAT(),0640)) {
 6182:     $hash{"version:$symb"}++;
 6183:     my $version=$hash{"version:$symb"};
 6184:     my $allkeys=''; 
 6185:     foreach my $key (keys(%$storehash)) {
 6186:       $allkeys.=$key.':';
 6187:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6188:     }
 6189:     $hash{"$version:$symb:timestamp"}=$now;
 6190:     $allkeys.='timestamp';
 6191:     $hash{"$version:keys:$symb"}=$allkeys;
 6192:     if (untie(%hash)) {
 6193:       return 'ok';
 6194:     } else {
 6195:       return "error:$!";
 6196:     }
 6197:   } else {
 6198:     return "error:$!";
 6199:   }
 6200: }
 6201: 
 6202: # -----------------------------------------------------------------Temp Restore
 6203: 
 6204: sub tmprestore {
 6205:   my ($symb,$namespace,$domain,$stuname) = @_;
 6206: 
 6207:   if (!$symb) {
 6208:     $symb=&symbread();
 6209:     if (!$symb) { $symb= $env{'request.url'}; }
 6210:   }
 6211:   $symb=escape($symb);
 6212: 
 6213:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6214: 
 6215:   if (!$domain) { $domain=$env{'user.domain'}; }
 6216:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6217:   if ($domain eq 'public' && $stuname eq 'public') {
 6218:       $stuname=&get_requestor_ip();
 6219:   }
 6220:   my %returnhash;
 6221:   $namespace=~s/\//\_/g;
 6222:   $namespace=~s/\W//g;
 6223:   my %hash;
 6224:   my $path=LONCAPA::tempdir();
 6225:   if (tie(%hash,'GDBM_File',
 6226: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6227: 	  &GDBM_READER(),0640)) {
 6228:     my $version=$hash{"version:$symb"};
 6229:     $returnhash{'version'}=$version;
 6230:     my $scope;
 6231:     for ($scope=1;$scope<=$version;$scope++) {
 6232:       my $vkeys=$hash{"$scope:keys:$symb"};
 6233:       my @keys=split(/:/,$vkeys);
 6234:       my $key;
 6235:       $returnhash{"$scope:keys"}=$vkeys;
 6236:       foreach $key (@keys) {
 6237: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6238: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6239:       }
 6240:     }
 6241:     if (!(untie(%hash))) {
 6242:       return "error:$!";
 6243:     }
 6244:   } else {
 6245:     return "error:$!";
 6246:   }
 6247:   return %returnhash;
 6248: }
 6249: 
 6250: # ----------------------------------------------------------------------- Store
 6251: 
 6252: sub store {
 6253:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6254:     my $home='';
 6255: 
 6256:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6257: 
 6258:     $symb=&symbclean($symb);
 6259:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6260: 
 6261:     if (!$domain) { $domain=$env{'user.domain'}; }
 6262:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6263: 
 6264:     &devalidate($symb,$stuname,$domain);
 6265: 
 6266:     $symb=escape($symb);
 6267:     if (!$namespace) { 
 6268:        unless ($namespace=$env{'request.course.id'}) { 
 6269:           return ''; 
 6270:        } 
 6271:     }
 6272:     if (!$home) { $home=$env{'user.home'}; }
 6273: 
 6274:     $$storehash{'ip'}=&get_requestor_ip();
 6275:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6276: 
 6277:     my $namevalue='';
 6278:     foreach my $key (keys(%$storehash)) {
 6279:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6280:     }
 6281:     $namevalue=~s/\&$//;
 6282:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6283:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6284: }
 6285: 
 6286: # -------------------------------------------------------------- Critical Store
 6287: 
 6288: sub cstore {
 6289:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6290:     my $home='';
 6291: 
 6292:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6293: 
 6294:     $symb=&symbclean($symb);
 6295:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6296: 
 6297:     if (!$domain) { $domain=$env{'user.domain'}; }
 6298:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6299: 
 6300:     &devalidate($symb,$stuname,$domain);
 6301: 
 6302:     $symb=escape($symb);
 6303:     if (!$namespace) { 
 6304:        unless ($namespace=$env{'request.course.id'}) { 
 6305:           return ''; 
 6306:        } 
 6307:     }
 6308:     if (!$home) { $home=$env{'user.home'}; }
 6309: 
 6310:     $$storehash{'ip'}=&get_requestor_ip();
 6311:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6312: 
 6313:     my $namevalue='';
 6314:     foreach my $key (keys(%$storehash)) {
 6315:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6316:     }
 6317:     $namevalue=~s/\&$//;
 6318:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6319:     return critical
 6320:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6321: }
 6322: 
 6323: # --------------------------------------------------------------------- Restore
 6324: 
 6325: sub restore {
 6326:     my ($symb,$namespace,$domain,$stuname) = @_;
 6327:     my $home='';
 6328: 
 6329:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6330: 
 6331:     if (!$symb) {
 6332:         return if ($namespace eq 'courserequests');
 6333:         unless ($symb=escape(&symbread())) { return ''; }
 6334:     } else {
 6335:         unless ($namespace eq 'courserequests') {
 6336:             $symb=&escape(&symbclean($symb));
 6337:         }
 6338:     }
 6339:     if (!$namespace) { 
 6340:        unless ($namespace=$env{'request.course.id'}) { 
 6341:           return ''; 
 6342:        } 
 6343:     }
 6344:     if (!$domain) { $domain=$env{'user.domain'}; }
 6345:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6346:     if (!$home) { $home=$env{'user.home'}; }
 6347:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6348: 
 6349:     my %returnhash=();
 6350:     foreach my $line (split(/\&/,$answer)) {
 6351: 	my ($name,$value)=split(/\=/,$line);
 6352:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6353:     }
 6354:     my $version;
 6355:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6356:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6357:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6358:        }
 6359:     }
 6360:     return %returnhash;
 6361: }
 6362: 
 6363: # ---------------------------------------------------------- Course Description
 6364: #
 6365: #  
 6366: 
 6367: sub coursedescription {
 6368:     my ($courseid,$args)=@_;
 6369:     $courseid=~s/^\///;
 6370:     $courseid=~s/\_/\//g;
 6371:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6372:     my $chome=&homeserver($cnum,$cdomain);
 6373:     my $normalid=$cdomain.'_'.$cnum;
 6374:     # need to always cache even if we get errors otherwise we keep 
 6375:     # trying and trying and trying to get the course description.
 6376:     my %envhash=();
 6377:     my %returnhash=();
 6378:     
 6379:     my $expiretime=600;
 6380:     if ($env{'request.course.id'} eq $normalid) {
 6381: 	$expiretime=120;
 6382:     }
 6383: 
 6384:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6385:     if (!$args->{'freshen_cache'}
 6386: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6387: 	foreach my $key (keys(%env)) {
 6388: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6389: 	    my ($setting) = $1;
 6390: 	    $returnhash{$setting} = $env{$key};
 6391: 	}
 6392: 	return %returnhash;
 6393:     }
 6394: 
 6395:     # get the data again
 6396: 
 6397:     if (!$args->{'one_time'}) {
 6398: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6399:     }
 6400: 
 6401:     if ($chome ne 'no_host') {
 6402:        %returnhash=&dump('environment',$cdomain,$cnum);
 6403:        if (!exists($returnhash{'con_lost'})) {
 6404: 	   my $username = $env{'user.name'}; # Defult username
 6405: 	   if(defined $args->{'user'}) {
 6406: 	       $username = $args->{'user'};
 6407: 	   }
 6408:            $returnhash{'home'}= $chome;
 6409: 	   $returnhash{'domain'} = $cdomain;
 6410: 	   $returnhash{'num'} = $cnum;
 6411:            if (!defined($returnhash{'type'})) {
 6412:                $returnhash{'type'} = 'Course';
 6413:            }
 6414:            while (my ($name,$value) = each %returnhash) {
 6415:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6416:            }
 6417:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6418:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6419: 	       $username.'_'.$cdomain.'_'.$cnum;
 6420:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6421:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6422:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6423:        }
 6424:     }
 6425:     if (!$args->{'one_time'}) {
 6426: 	&appenv(\%envhash);
 6427:     }
 6428:     return %returnhash;
 6429: }
 6430: 
 6431: sub update_released_required {
 6432:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6433:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6434:         $cid = $env{'request.course.id'};
 6435:         $cdom = $env{'course.'.$cid.'.domain'};
 6436:         $cnum = $env{'course.'.$cid.'.num'};
 6437:         $chome = $env{'course.'.$cid.'.home'};
 6438:     }
 6439:     if ($needsrelease) {
 6440:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6441:         my $needsupdate;
 6442:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6443:             $needsupdate = 1;
 6444:         } else {
 6445:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6446:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6447:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6448:                 $needsupdate = 1;
 6449:             }
 6450:         }
 6451:         if ($needsupdate) {
 6452:             my %needshash = (
 6453:                              'internal.releaserequired' => $needsrelease,
 6454:                             );
 6455:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6456:             if ($putresult eq 'ok') {
 6457:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6458:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6459:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6460:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6461:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6462:                 }
 6463:             }
 6464:         }
 6465:     }
 6466:     return;
 6467: }
 6468: 
 6469: # -------------------------------------------------See if a user is privileged
 6470: 
 6471: sub privileged {
 6472:     my ($username,$domain,$possdomains,$possroles)=@_;
 6473:     my $now = time;
 6474:     my $roles;
 6475:     if (ref($possroles) eq 'ARRAY') {
 6476:         $roles = $possroles; 
 6477:     } else {
 6478:         $roles = ['dc','su'];
 6479:     }
 6480:     if (ref($possdomains) eq 'ARRAY') {
 6481:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6482:         foreach my $dom (@{$possdomains}) {
 6483:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6484:                 (ref($privileged{$dom}) eq 'HASH')) {
 6485:                 foreach my $role (@{$roles}) {
 6486:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6487:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6488:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6489:                             return 1 unless (($end && $end < $now) ||
 6490:                                              ($start && $start > $now));
 6491:                         }
 6492:                     }
 6493:                 }
 6494:             }
 6495:         }
 6496:     } else {
 6497:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6498:         my $now = time;
 6499: 
 6500:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6501:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6502:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6503:                 return 1 unless ($tend && $tend < $now) 
 6504:                         or ($tstart && $tstart > $now);
 6505:             }
 6506:         }
 6507:     }
 6508:     return 0;
 6509: }
 6510: 
 6511: sub privileged_by_domain {
 6512:     my ($domains,$roles) = @_;
 6513:     my %privileged = ();
 6514:     my $cachetime = 60*60*24;
 6515:     my $now = time;
 6516:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6517:         return %privileged;
 6518:     }
 6519:     foreach my $dom (@{$domains}) {
 6520:         next if (ref($privileged{$dom}) eq 'HASH');
 6521:         my $needroles;
 6522:         foreach my $role (@{$roles}) {
 6523:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6524:             if (defined($cached)) {
 6525:                 if (ref($result) eq 'HASH') {
 6526:                     $privileged{$dom}{$role} = $result;
 6527:                 }
 6528:             } else {
 6529:                 $needroles = 1;
 6530:             }
 6531:         }
 6532:         if ($needroles) {
 6533:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6534:             $privileged{$dom} = {};
 6535:             foreach my $server (keys(%dompersonnel)) {
 6536:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6537:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6538:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6539:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6540:                         next if ($end && $end < $now);
 6541:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6542:                             $dompersonnel{$server}{$item};
 6543:                     }
 6544:                 }
 6545:             }
 6546:             if (ref($privileged{$dom}) eq 'HASH') {
 6547:                 foreach my $role (@{$roles}) {
 6548:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6549:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6550:                     } else {
 6551:                         my %hash = ();
 6552:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6553:                     }
 6554:                 }
 6555:             }
 6556:         }
 6557:     }
 6558:     return %privileged;
 6559: }
 6560: 
 6561: # -------------------------------------------------------- Get user privileges
 6562: 
 6563: sub rolesinit {
 6564:     my ($domain, $username) = @_;
 6565:     my %userroles = ('user.login.time' => time);
 6566:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6567: 
 6568:     # firstaccess and timerinterval are related to timed maps/resources. 
 6569:     # also, blocking can be triggered by an activating timer
 6570:     # it's saved in the user's %env.
 6571:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6572:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6573:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6574:         %timerintchk, %timerintenv);
 6575: 
 6576:     foreach my $key (keys(%firstaccess)) {
 6577:         my ($cid, $rest) = split(/\0/, $key);
 6578:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6579:     }
 6580: 
 6581:     foreach my $key (keys(%timerinterval)) {
 6582:         my ($cid,$rest) = split(/\0/,$key);
 6583:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6584:     }
 6585: 
 6586:     my %allroles=();
 6587:     my %allgroups=();
 6588: 
 6589:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6590:         my $role = $rolesdump{$area};
 6591:         $area =~ s/\_\w\w$//;
 6592: 
 6593:         my ($trole, $tend, $tstart, $group_privs);
 6594: 
 6595:         if ($role =~ /^cr/) {
 6596:         # Custom role, defined by a user 
 6597:         # e.g., user.role.cr/msu/smith/mynewrole
 6598:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6599:                 $trole = $1;
 6600:                 ($tend, $tstart) = split('_', $2);
 6601:             } else {
 6602:                 $trole = $role;
 6603:             }
 6604:         } elsif ($role =~ m|^gr/|) {
 6605:         # Role of member in a group, defined within a course/community
 6606:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6607:             ($trole, $tend, $tstart) = split(/_/, $role);
 6608:             next if $tstart eq '-1';
 6609:             ($trole, $group_privs) = split(/\//, $trole);
 6610:             $group_privs = &unescape($group_privs);
 6611:         } else {
 6612:         # Just a normal role, defined in roles.tab
 6613:             ($trole, $tend, $tstart) = split(/_/,$role);
 6614:         }
 6615: 
 6616:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6617:                  $username);
 6618:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6619: 
 6620:         # role expired or not available yet?
 6621:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6622:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6623: 
 6624:         next if $area eq '' or $trole eq '';
 6625: 
 6626:         my $spec = "$trole.$area";
 6627:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6628: 
 6629:         if ($trole =~ /^cr\//) {
 6630:         # Custom role, defined by a user
 6631:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6632:         } elsif ($trole eq 'gr') {
 6633:         # Role of a member in a group, defined within a course/community
 6634:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6635:             next;
 6636:         } else {
 6637:         # Normal role, defined in roles.tab
 6638:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6639:         }
 6640: 
 6641:         my $cid = $tdomain.'_'.$trest;
 6642:         unless ($firstaccchk{$cid}) {
 6643:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6644:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6645:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6646:                         $coursetimerstarts{$cid}{$item}; 
 6647:                 }
 6648:             }
 6649:             $firstaccchk{$cid} = 1;
 6650:         }
 6651:         unless ($timerintchk{$cid}) {
 6652:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6653:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6654:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6655:                        $coursetimerintervals{$cid}{$item};
 6656:                 }
 6657:             }
 6658:             $timerintchk{$cid} = 1;
 6659:         }
 6660:     }
 6661: 
 6662:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6663:                                                           \%allroles, \%allgroups);
 6664:     $env{'user.adv'} = $userroles{'user.adv'};
 6665:     $env{'user.rar'} = $userroles{'user.rar'};
 6666: 
 6667:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6668: }
 6669: 
 6670: sub set_arearole {
 6671:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6672:     unless ($nolog) {
 6673: # log the associated role with the area
 6674:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6675:     }
 6676:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6677: }
 6678: 
 6679: sub custom_roleprivs {
 6680:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6681:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6682:     my $homsvr = &homeserver($rauthor,$rdomain);
 6683:     if (&hostname($homsvr) ne '') {
 6684:         my ($rdummy,$roledef)=
 6685:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6686:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6687:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6688:             if (defined($syspriv)) {
 6689:                 if ($trest =~ /^$match_community$/) {
 6690:                     $syspriv =~ s/bre\&S//; 
 6691:                 }
 6692:                 $$allroles{'cm./'}.=':'.$syspriv;
 6693:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6694:             }
 6695:             if ($tdomain ne '') {
 6696:                 if (defined($dompriv)) {
 6697:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6698:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6699:                 }
 6700:                 if (($trest ne '') && (defined($coursepriv))) {
 6701:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6702:                         my $rolename = $1;
 6703:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6704:                     }
 6705:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6706:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6707:                 }
 6708:             }
 6709:         }
 6710:     }
 6711: }
 6712: 
 6713: sub course_adhocrole_privs {
 6714:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6715:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6716:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6717:         my (%currprivs,%storeprivs);
 6718:         foreach my $item (split(/:/,$coursepriv)) {
 6719:             my ($priv,$restrict) = split(/\&/,$item);
 6720:             $currprivs{$priv} = $restrict;
 6721:         }
 6722:         my (%possadd,%possremove,%full);
 6723:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6724:             my ($priv,$restrict)=split(/\&/,$item);
 6725:             $full{$priv} = $restrict;
 6726:         }
 6727:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6728:              next if ($item eq '');
 6729:              my ($rule,$rest) = split(/=/,$item);
 6730:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6731:              foreach my $priv (split(/:/,$rest)) {
 6732:                  if ($priv ne '') {
 6733:                      if ($rule eq 'off') {
 6734:                          $possremove{$priv} = 1;
 6735:                      } else {
 6736:                          $possadd{$priv} = 1;
 6737:                      }
 6738:                  }
 6739:              }
 6740:          }
 6741:          foreach my $priv (sort(keys(%full))) {
 6742:              if (exists($currprivs{$priv})) {
 6743:                  unless (exists($possremove{$priv})) {
 6744:                      $storeprivs{$priv} = $currprivs{$priv};
 6745:                  }
 6746:              } elsif (exists($possadd{$priv})) {
 6747:                  $storeprivs{$priv} = $full{$priv};
 6748:              }
 6749:          }
 6750:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6751:      }
 6752:      return $coursepriv;
 6753: }
 6754: 
 6755: sub group_roleprivs {
 6756:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6757:     my $access = 1;
 6758:     my $now = time;
 6759:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6760:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6761:     if ($access) {
 6762:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6763:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6764:     }
 6765: }
 6766: 
 6767: sub standard_roleprivs {
 6768:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6769:     if (defined($pr{$trole.':s'})) {
 6770:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6771:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6772:     }
 6773:     if ($tdomain ne '') {
 6774:         if (defined($pr{$trole.':d'})) {
 6775:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6776:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6777:         }
 6778:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6779:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6780:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6781:         }
 6782:     }
 6783: }
 6784: 
 6785: sub set_userprivs {
 6786:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6787:     my $author=0;
 6788:     my $adv=0;
 6789:     my $rar=0;
 6790:     my %grouproles = ();
 6791:     if (keys(%{$allgroups}) > 0) {
 6792:         my @groupkeys; 
 6793:         foreach my $role (keys(%{$allroles})) {
 6794:             push(@groupkeys,$role);
 6795:         }
 6796:         if (ref($groups_roles) eq 'HASH') {
 6797:             foreach my $key (keys(%{$groups_roles})) {
 6798:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6799:                     push(@groupkeys,$key);
 6800:                 }
 6801:             }
 6802:         }
 6803:         if (@groupkeys > 0) {
 6804:             foreach my $role (@groupkeys) {
 6805:                 my ($trole,$area,$sec,$extendedarea);
 6806:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6807:                     $trole = $1;
 6808:                     $area = $2;
 6809:                     $sec = $3;
 6810:                     $extendedarea = $area.$sec;
 6811:                     if (exists($$allgroups{$area})) {
 6812:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6813:                             my $spec = $trole.'.'.$extendedarea;
 6814:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6815:                                                 $$allgroups{$area}{$group};
 6816:                         }
 6817:                     }
 6818:                 }
 6819:             }
 6820:         }
 6821:     }
 6822:     foreach my $group (keys(%grouproles)) {
 6823:         $$allroles{$group} = $grouproles{$group};
 6824:     }
 6825:     foreach my $role (keys(%{$allroles})) {
 6826:         my %thesepriv;
 6827:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6828:         foreach my $item (split(/:/,$$allroles{$role})) {
 6829:             if ($item ne '') {
 6830:                 my ($privilege,$restrictions)=split(/&/,$item);
 6831:                 if ($restrictions eq '') {
 6832:                     $thesepriv{$privilege}='F';
 6833:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6834:                     $thesepriv{$privilege}.=$restrictions;
 6835:                 }
 6836:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6837:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6838:             }
 6839:         }
 6840:         my $thesestr='';
 6841:         foreach my $priv (sort(keys(%thesepriv))) {
 6842: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6843: 	}
 6844:         $userroles->{'user.priv.'.$role} = $thesestr;
 6845:     }
 6846:     return ($author,$adv,$rar);
 6847: }
 6848: 
 6849: sub role_status {
 6850:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6851:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6852:         my ($one,$two) = split(m{\./},$rolekey,2);
 6853:         (undef,undef,$$role) = split(/\./,$one,3);
 6854:         unless (!defined($$role) || $$role eq '') {
 6855:             $$where = '/'.$two;
 6856:             $$trolecode=$$role.'.'.$$where;
 6857:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6858:             $$tstatus='is';
 6859:             if ($$tstart && $$tstart>$update) {
 6860:                 $$tstatus='future';
 6861:                 if ($$tstart<$now) {
 6862:                     if ($$tstart && $$tstart>$refresh) {
 6863:                         if (($$where ne '') && ($$role ne '')) {
 6864:                             my (%allroles,%allgroups,$group_privs,
 6865:                                 %groups_roles,@rolecodes);
 6866:                             my %userroles = (
 6867:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6868:                             );
 6869:                             @rolecodes = ('cm'); 
 6870:                             my $spec=$$role.'.'.$$where;
 6871:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6872:                             if ($$role =~ /^cr\//) {
 6873:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6874:                                 push(@rolecodes,'cr');
 6875:                             } elsif ($$role eq 'gr') {
 6876:                                 push(@rolecodes,$$role);
 6877:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6878:                                                     $env{'user.name'});
 6879:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6880:                                 (undef,my $group_privs) = split(/\//,$trole);
 6881:                                 $group_privs = &unescape($group_privs);
 6882:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6883:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6884:                                 &get_groups_roles($tdomain,$trest,
 6885:                                                   \%course_roles,\@rolecodes,
 6886:                                                   \%groups_roles);
 6887:                             } else {
 6888:                                 push(@rolecodes,$$role);
 6889:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6890:                             }
 6891:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6892:                                                                    \%groups_roles);
 6893:                             &appenv(\%userroles,\@rolecodes);
 6894:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6895:                         }
 6896:                     }
 6897:                     $$tstatus = 'is';
 6898:                 }
 6899:             }
 6900:             if ($$tend) {
 6901:                 if ($$tend<$update) {
 6902:                     $$tstatus='expired';
 6903:                 } elsif ($$tend<$now) {
 6904:                     $$tstatus='will_not';
 6905:                 }
 6906:             }
 6907:         }
 6908:     }
 6909: }
 6910: 
 6911: sub get_groups_roles {
 6912:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6913:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6914:                   (ref($rolecodes) eq 'ARRAY') && 
 6915:                   (ref($groups_roles) eq 'HASH')); 
 6916:     if (keys(%{$cdom_courseroles}) > 0) {
 6917:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6918:         if ($cdom ne '' && $cnum ne '') {
 6919:             foreach my $key (keys(%{$cdom_courseroles})) {
 6920:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6921:                     my $crsrole = $1;
 6922:                     my $crssec = $2;
 6923:                     if ($crsrole =~ /^cr/) {
 6924:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6925:                             push(@{$rolecodes},'cr');
 6926:                         }
 6927:                     } else {
 6928:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6929:                             push(@{$rolecodes},$crsrole);
 6930:                         }
 6931:                     }
 6932:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6933:                     if ($crssec ne '') {
 6934:                         $rolekey .= "/$crssec";
 6935:                     }
 6936:                     $rolekey .= './';
 6937:                     $groups_roles->{$rolekey} = $rolecodes;
 6938:                 }
 6939:             }
 6940:         }
 6941:     }
 6942:     return;
 6943: }
 6944: 
 6945: sub delete_env_groupprivs {
 6946:     my ($where,$courseroles,$possroles) = @_;
 6947:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6948:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6949:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6950:         %{$courseroles->{$udom}} =
 6951:             &get_my_roles('','','userroles',['active'],
 6952:                           $possroles,[$udom],1);
 6953:     }
 6954:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6955:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6956:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6957:             my $area = '/'.$cdom.'/'.$cnum;
 6958:             my $privkey = "user.priv.$crsrole.$area";
 6959:             if ($crssec ne '') {
 6960:                 $privkey .= '/'.$crssec;
 6961:             }
 6962:             $privkey .= ".$area/$group";
 6963:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6964:         }
 6965:     }
 6966:     return;
 6967: }
 6968: 
 6969: sub check_adhoc_privs {
 6970:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6971:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6972:     if ($sec) {
 6973:         $cckey .= '/'.$sec;
 6974:     } 
 6975:     my $setprivs;
 6976:     if ($env{$cckey}) {
 6977:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6978:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6979:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6980:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6981:             $setprivs = 1;
 6982:         }
 6983:     } else {
 6984:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6985:         $setprivs = 1;
 6986:     }
 6987:     return $setprivs;
 6988: }
 6989: 
 6990: sub set_adhoc_privileges {
 6991: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6992:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6993:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6994:     if ($sec ne '') {
 6995:         $area .= '/'.$sec;
 6996:     }
 6997:     my $spec = $role.'.'.$area;
 6998:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6999:                                   $env{'user.name'},1);
 7000:     my %rolehash = ();
 7001:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7002:         my $rolename = $1;
 7003:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7004:         my %domdef = &get_domain_defaults($dcdom);
 7005:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7006:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7007:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7008:             }
 7009:         }
 7010:     } else {
 7011:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7012:     }
 7013:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7014:     &appenv(\%userroles,[$role,'cm']);
 7015:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7016:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7017:             ($caller eq 'tiny')) {
 7018:         &appenv( {'request.role'        => $spec,
 7019:                   'request.role.domain' => $dcdom,
 7020:                   'request.course.sec'  => $sec,
 7021:                  }
 7022:                );
 7023:         my $tadv=0;
 7024:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7025:         &appenv({'request.role.adv'    => $tadv});
 7026:     }
 7027: }
 7028: 
 7029: # --------------------------------------------------------------- get interface
 7030: 
 7031: sub get {
 7032:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7033:    my $items='';
 7034:    foreach my $item (@$storearr) {
 7035:        $items.=&escape($item).'&';
 7036:    }
 7037:    $items=~s/\&$//;
 7038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7039:    if (!$uname) { $uname=$env{'user.name'}; }
 7040:    my $uhome=&homeserver($uname,$udomain);
 7041: 
 7042:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7043:    my @pairs=split(/\&/,$rep);
 7044:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7045:      return @pairs;
 7046:    }
 7047:    my %returnhash=();
 7048:    my $i=0;
 7049:    foreach my $item (@$storearr) {
 7050:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7051:       $i++;
 7052:    }
 7053:    return %returnhash;
 7054: }
 7055: 
 7056: # --------------------------------------------------------------- del interface
 7057: 
 7058: sub del {
 7059:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7060:    my $items='';
 7061:    foreach my $item (@$storearr) {
 7062:        $items.=&escape($item).'&';
 7063:    }
 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:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7070: }
 7071: 
 7072: # -------------------------------------------------------------- dump interface
 7073: 
 7074: sub unserialize {
 7075:     my ($rep, $escapedkeys) = @_;
 7076: 
 7077:     return {} if $rep =~ /^error/;
 7078: 
 7079:     my %returnhash=();
 7080: 	foreach my $item (split(/\&/,$rep)) {
 7081: 	    my ($key, $value) = split(/=/, $item, 2);
 7082: 	    $key = unescape($key) unless $escapedkeys;
 7083: 	    next if $key =~ /^error: 2 /;
 7084: 	    $returnhash{$key} = &thaw_unescape($value);
 7085: 	}
 7086:     #return %returnhash;
 7087:     return \%returnhash;
 7088: }        
 7089: 
 7090: # see Lond::dump_with_regexp
 7091: # if $escapedkeys hash keys won't get unescaped.
 7092: sub dump {
 7093:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 7094:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7095:     if (!$uname) { $uname=$env{'user.name'}; }
 7096:     my $uhome=&homeserver($uname,$udomain);
 7097: 
 7098:     if ($regexp) {
 7099:         $regexp=&escape($regexp);
 7100:     } else {
 7101:         $regexp='.';
 7102:     }
 7103:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7104:         # user is hosted on this machine
 7105:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7106:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7107:         return %{unserialize($reply, $escapedkeys)};
 7108:     }
 7109:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7110:     my @pairs=split(/\&/,$rep);
 7111:     my %returnhash=();
 7112:     if (!($rep =~ /^error/ )) {
 7113: 	foreach my $item (@pairs) {
 7114: 	    my ($key,$value)=split(/=/,$item,2);
 7115:         $key = unescape($key) unless $escapedkeys;
 7116:         #$key = &unescape($key);
 7117: 	    next if ($key =~ /^error: 2 /);
 7118: 	    $returnhash{$key}=&thaw_unescape($value);
 7119: 	}
 7120:     }
 7121:     return %returnhash;
 7122: }
 7123: 
 7124: 
 7125: # --------------------------------------------------------- dumpstore interface
 7126: 
 7127: sub dumpstore {
 7128:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7129:    # same as dump but keys must be escaped. They may contain colon separated
 7130:    # lists of values that may themself contain colons (e.g. symbs).
 7131:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7132: }
 7133: 
 7134: # -------------------------------------------------------------- keys interface
 7135: 
 7136: sub getkeys {
 7137:    my ($namespace,$udomain,$uname)=@_;
 7138:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7139:    if (!$uname) { $uname=$env{'user.name'}; }
 7140:    my $uhome=&homeserver($uname,$udomain);
 7141:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7142:    my @keyarray=();
 7143:    foreach my $key (split(/\&/,$rep)) {
 7144:       next if ($key =~ /^error: 2 /);
 7145:       push(@keyarray,&unescape($key));
 7146:    }
 7147:    return @keyarray;
 7148: }
 7149: 
 7150: # --------------------------------------------------------------- currentdump
 7151: sub currentdump {
 7152:    my ($courseid,$sdom,$sname)=@_;
 7153:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7154:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7155:    $sname    = $env{'user.name'}         if (! defined($sname));
 7156:    my $uhome = &homeserver($sname,$sdom);
 7157:    my $rep;
 7158: 
 7159:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7160:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7161:                    $courseid)));
 7162:    } else {
 7163:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7164:    }
 7165: 
 7166:    return if ($rep =~ /^(error:|no_such_host)/);
 7167:    #
 7168:    my %returnhash=();
 7169:    #
 7170:    if ($rep eq 'unknown_cmd') {
 7171:        # an old lond will not know currentdump
 7172:        # Do a dump and make it look like a currentdump
 7173:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7174:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7175:        my %hash = @tmp;
 7176:        @tmp=();
 7177:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7178:    } else {
 7179:        my @pairs=split(/\&/,$rep);
 7180:        foreach my $pair (@pairs) {
 7181:            my ($key,$value)=split(/=/,$pair,2);
 7182:            my ($symb,$param) = split(/:/,$key);
 7183:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7184:                                                         &thaw_unescape($value);
 7185:        }
 7186:    }
 7187:    return %returnhash;
 7188: }
 7189: 
 7190: sub convert_dump_to_currentdump{
 7191:     my %hash = %{shift()};
 7192:     my %returnhash;
 7193:     # Code ripped from lond, essentially.  The only difference
 7194:     # here is the unescaping done by lonnet::dump().  Conceivably
 7195:     # we might run in to problems with parameter names =~ /^v\./
 7196:     while (my ($key,$value) = each(%hash)) {
 7197:         my ($v,$symb,$param) = split(/:/,$key);
 7198: 	$symb  = &unescape($symb);
 7199: 	$param = &unescape($param);
 7200:         next if ($v eq 'version' || $symb eq 'keys');
 7201:         next if (exists($returnhash{$symb}) &&
 7202:                  exists($returnhash{$symb}->{$param}) &&
 7203:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7204:         $returnhash{$symb}->{$param}=$value;
 7205:         $returnhash{$symb}->{'v.'.$param}=$v;
 7206:     }
 7207:     #
 7208:     # Remove all of the keys in the hashes which keep track of
 7209:     # the version of the parameter.
 7210:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7211:         # use a foreach because we are going to delete from the hash.
 7212:         foreach my $key (keys(%$param_hash)) {
 7213:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7214:         }
 7215:     }
 7216:     return \%returnhash;
 7217: }
 7218: 
 7219: # ------------------------------------------------------ critical inc interface
 7220: 
 7221: sub cinc {
 7222:     return &inc(@_,'critical');
 7223: }
 7224: 
 7225: # --------------------------------------------------------------- inc interface
 7226: 
 7227: sub inc {
 7228:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7229:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7230:     if (!$uname) { $uname=$env{'user.name'}; }
 7231:     my $uhome=&homeserver($uname,$udomain);
 7232:     my $items='';
 7233:     if (! ref($store)) {
 7234:         # got a single value, so use that instead
 7235:         $items = &escape($store).'=&';
 7236:     } elsif (ref($store) eq 'SCALAR') {
 7237:         $items = &escape($$store).'=&';        
 7238:     } elsif (ref($store) eq 'ARRAY') {
 7239:         $items = join('=&',map {&escape($_);} @{$store});
 7240:     } elsif (ref($store) eq 'HASH') {
 7241:         while (my($key,$value) = each(%{$store})) {
 7242:             $items.= &escape($key).'='.&escape($value).'&';
 7243:         }
 7244:     }
 7245:     $items=~s/\&$//;
 7246:     if ($critical) {
 7247: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7248:     } else {
 7249: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7250:     }
 7251: }
 7252: 
 7253: # --------------------------------------------------------------- put interface
 7254: 
 7255: sub put {
 7256:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7257:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7258:    if (!$uname) { $uname=$env{'user.name'}; }
 7259:    my $uhome=&homeserver($uname,$udomain);
 7260:    my $items='';
 7261:    foreach my $item (keys(%$storehash)) {
 7262:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7263:    }
 7264:    $items=~s/\&$//;
 7265:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7266: }
 7267: 
 7268: # ------------------------------------------------------------ newput interface
 7269: 
 7270: sub newput {
 7271:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7272:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7273:    if (!$uname) { $uname=$env{'user.name'}; }
 7274:    my $uhome=&homeserver($uname,$udomain);
 7275:    my $items='';
 7276:    foreach my $key (keys(%$storehash)) {
 7277:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7278:    }
 7279:    $items=~s/\&$//;
 7280:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7281: }
 7282: 
 7283: # ---------------------------------------------------------  putstore interface
 7284: 
 7285: sub putstore {
 7286:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7287:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7288:    if (!$uname) { $uname=$env{'user.name'}; }
 7289:    my $uhome=&homeserver($uname,$udomain);
 7290:    my $items='';
 7291:    foreach my $key (keys(%$storehash)) {
 7292:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7293:    }
 7294:    $items=~s/\&$//;
 7295:    my $esc_symb=&escape($symb);
 7296:    my $esc_v=&escape($version);
 7297:    my $reply =
 7298:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7299: 	      $uhome);
 7300:    if (($tolog) && ($reply eq 'ok')) {
 7301:        my $namevalue='';
 7302:        foreach my $key (keys(%{$storehash})) {
 7303:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7304:        }
 7305:        my $ip = &get_requestor_ip();
 7306:        $namevalue .= 'ip='.&escape($ip).
 7307:                      '&host='.&escape($perlvar{'lonHostID'}).
 7308:                      '&version='.$esc_v.
 7309:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7310:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7311:    }
 7312:    if ($reply eq 'unknown_cmd') {
 7313:        # gfall back to way things use to be done
 7314:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7315: 			    $uname);
 7316:    }
 7317:    return $reply;
 7318: }
 7319: 
 7320: sub old_putstore {
 7321:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7322:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7323:     if (!$uname) { $uname=$env{'user.name'}; }
 7324:     my $uhome=&homeserver($uname,$udomain);
 7325:     my %newstorehash;
 7326:     foreach my $item (keys(%$storehash)) {
 7327: 	my $key = $version.':'.&escape($symb).':'.$item;
 7328: 	$newstorehash{$key} = $storehash->{$item};
 7329:     }
 7330:     my $items='';
 7331:     my %allitems = ();
 7332:     foreach my $item (keys(%newstorehash)) {
 7333: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7334: 	    my $key = $1.':keys:'.$2;
 7335: 	    $allitems{$key} .= $3.':';
 7336: 	}
 7337: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7338:     }
 7339:     foreach my $item (keys(%allitems)) {
 7340: 	$allitems{$item} =~ s/\:$//;
 7341: 	$items.= $item.'='.$allitems{$item}.'&';
 7342:     }
 7343:     $items=~s/\&$//;
 7344:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7345: }
 7346: 
 7347: # ------------------------------------------------------ critical put interface
 7348: 
 7349: sub cput {
 7350:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7351:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7352:    if (!$uname) { $uname=$env{'user.name'}; }
 7353:    my $uhome=&homeserver($uname,$udomain);
 7354:    my $items='';
 7355:    foreach my $item (keys(%$storehash)) {
 7356:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7357:    }
 7358:    $items=~s/\&$//;
 7359:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7360: }
 7361: 
 7362: # -------------------------------------------------------------- eget interface
 7363: 
 7364: sub eget {
 7365:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7366:    my $items='';
 7367:    foreach my $item (@$storearr) {
 7368:        $items.=&escape($item).'&';
 7369:    }
 7370:    $items=~s/\&$//;
 7371:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7372:    if (!$uname) { $uname=$env{'user.name'}; }
 7373:    my $uhome=&homeserver($uname,$udomain);
 7374:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7375:    my @pairs=split(/\&/,$rep);
 7376:    my %returnhash=();
 7377:    my $i=0;
 7378:    foreach my $item (@$storearr) {
 7379:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7380:       $i++;
 7381:    }
 7382:    return %returnhash;
 7383: }
 7384: 
 7385: # ------------------------------------------------------------ tmpput interface
 7386: sub tmpput {
 7387:     my ($storehash,$server,$context)=@_;
 7388:     my $items='';
 7389:     foreach my $item (keys(%$storehash)) {
 7390: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7391:     }
 7392:     $items=~s/\&$//;
 7393:     if (defined($context)) {
 7394:         $items .= ':'.&escape($context);
 7395:     }
 7396:     return &reply("tmpput:$items",$server);
 7397: }
 7398: 
 7399: # ------------------------------------------------------------ tmpget interface
 7400: sub tmpget {
 7401:     my ($token,$server)=@_;
 7402:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7403:     my $rep=&reply("tmpget:$token",$server);
 7404:     my %returnhash;
 7405:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7406:         return %returnhash;
 7407:     }
 7408:     foreach my $item (split(/\&/,$rep)) {
 7409: 	my ($key,$value)=split(/=/,$item);
 7410: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7411:     }
 7412:     return %returnhash;
 7413: }
 7414: 
 7415: # ------------------------------------------------------------ tmpdel interface
 7416: sub tmpdel {
 7417:     my ($token,$server)=@_;
 7418:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7419:     return &reply("tmpdel:$token",$server);
 7420: }
 7421: 
 7422: # ------------------------------------------------------------ get_timebased_id 
 7423: 
 7424: sub get_timebased_id {
 7425:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7426:         $maxtries) = @_;
 7427:     my ($newid,$error,$dellock);
 7428:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7429:         return ('','ok','invalid call to get suffix');
 7430:     }
 7431: 
 7432: # set defaults for any optional args for which values were not supplied
 7433:     if ($who eq '') {
 7434:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7435:     }
 7436:     if (!$locktries) {
 7437:         $locktries = 3;
 7438:     }
 7439:     if (!$maxtries) {
 7440:         $maxtries = 10;
 7441:     }
 7442:     
 7443:     if (($cdom eq '') || ($cnum eq '')) {
 7444:         if ($env{'request.course.id'}) {
 7445:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7446:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7447:         }
 7448:         if (($cdom eq '') || ($cnum eq '')) {
 7449:             return ('','ok','call to get suffix not in course context');
 7450:         }
 7451:     }
 7452: 
 7453: # construct locking item
 7454:     my $lockhash = {
 7455:                       $prefix."\0".'locked_'.$keyid => $who,
 7456:                    };
 7457:     my $tries = 0;
 7458: 
 7459: # attempt to get lock on nohist_$namespace file
 7460:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7461:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7462:         $tries ++;
 7463:         sleep 1;
 7464:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7465:     }
 7466: 
 7467: # attempt to get unique identifier, based on current timestamp
 7468:     if ($gotlock eq 'ok') {
 7469:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7470:         my $id = time;
 7471:         $newid = $id;
 7472:         if ($idtype eq 'addcode') {
 7473:             $newid .= &sixnum_code();
 7474:         }
 7475:         my $idtries = 0;
 7476:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7477:             if ($idtype eq 'concat') {
 7478:                 $newid = $id.$idtries;
 7479:             } elsif ($idtype eq 'addcode') {
 7480:                 $newid = $newid.&sixnum_code();
 7481:             } else {
 7482:                 $newid ++;
 7483:             }
 7484:             $idtries ++;
 7485:         }
 7486:         if (!exists($inuse{$prefix."\0".$newid})) {
 7487:             my %new_item =  (
 7488:                               $prefix."\0".$newid => $who,
 7489:                             );
 7490:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7491:                                                  $cdom,$cnum);
 7492:             if ($putresult ne 'ok') {
 7493:                 undef($newid);
 7494:                 $error = 'error saving new item: '.$putresult;
 7495:             }
 7496:         } else {
 7497:              undef($newid);
 7498:              $error = ('error: no unique suffix available for the new item ');
 7499:         }
 7500: #  remove lock
 7501:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7502:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7503:     } else {
 7504:         $error = "error: could not obtain lockfile\n";
 7505:         $dellock = 'ok';
 7506:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7507:             $dellock = 'nolock';
 7508:         }
 7509:     }
 7510:     return ($newid,$dellock,$error);
 7511: }
 7512: 
 7513: sub sixnum_code {
 7514:     my $code;
 7515:     for (0..6) {
 7516:         $code .= int( rand(9) );
 7517:     }
 7518:     return $code;
 7519: }
 7520: 
 7521: # -------------------------------------------------- portfolio access checking
 7522: 
 7523: sub portfolio_access {
 7524:     my ($requrl,$clientip) = @_;
 7525:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7526:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7527:     if ($result) {
 7528:         my %setters;
 7529:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7530:             my ($startblock,$endblock) =
 7531:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7532:             if ($startblock && $endblock) {
 7533:                 return 'B';
 7534:             }
 7535:         } else {
 7536:             my ($startblock,$endblock) =
 7537:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7538:             if ($startblock && $endblock) {
 7539:                 return 'B';
 7540:             }
 7541:         }
 7542:     }
 7543:     if ($result eq 'ok') {
 7544:        return 'F';
 7545:     } elsif ($result =~ /^[^:]+:guest_/) {
 7546:        return 'A';
 7547:     }
 7548:     return '';
 7549: }
 7550: 
 7551: sub get_portfolio_access {
 7552:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7553: 
 7554:     if (!ref($access_hash)) {
 7555: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7556: 	my %access_controls = &get_access_controls($current_perms,$group,
 7557: 						   $file_name);
 7558: 	$access_hash = $access_controls{$file_name};
 7559:     }
 7560: 
 7561:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7562:     my $now = time;
 7563:     if (ref($access_hash) eq 'HASH') {
 7564:         foreach my $key (keys(%{$access_hash})) {
 7565:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7566:             if ($start > $now) {
 7567:                 next;
 7568:             }
 7569:             if ($end && $end<$now) {
 7570:                 next;
 7571:             }
 7572:             if ($scope eq 'public') {
 7573:                 $public = $key;
 7574:                 last;
 7575:             } elsif ($scope eq 'guest') {
 7576:                 $guest = $key;
 7577:             } elsif ($scope eq 'domains') {
 7578:                 push(@domains,$key);
 7579:             } elsif ($scope eq 'users') {
 7580:                 push(@users,$key);
 7581:             } elsif ($scope eq 'course') {
 7582:                 push(@courses,$key);
 7583:             } elsif ($scope eq 'group') {
 7584:                 push(@groups,$key);
 7585:             } elsif ($scope eq 'ip') {
 7586:                 push(@ips,$key);
 7587:             }
 7588:         }
 7589:         if ($public) {
 7590:             return 'ok';
 7591:         } elsif (@ips > 0) {
 7592:             my $allowed;
 7593:             foreach my $ipkey (@ips) {
 7594:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7595:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7596:                         $allowed = 1;
 7597:                         last; 
 7598:                     }
 7599:                 }
 7600:             }
 7601:             if ($allowed) {
 7602:                 return 'ok';
 7603:             }
 7604:         }
 7605:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7606:             if ($guest) {
 7607:                 return $guest;
 7608:             }
 7609:         } else {
 7610:             if (@domains > 0) {
 7611:                 foreach my $domkey (@domains) {
 7612:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7613:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7614:                             return 'ok';
 7615:                         }
 7616:                     }
 7617:                 }
 7618:             }
 7619:             if (@users > 0) {
 7620:                 foreach my $userkey (@users) {
 7621:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7622:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7623:                             if (ref($item) eq 'HASH') {
 7624:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7625:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7626:                                     return 'ok';
 7627:                                 }
 7628:                             }
 7629:                         }
 7630:                     } 
 7631:                 }
 7632:             }
 7633:             my %roleshash;
 7634:             my @courses_and_groups = @courses;
 7635:             push(@courses_and_groups,@groups); 
 7636:             if (@courses_and_groups > 0) {
 7637:                 my (%allgroups,%allroles); 
 7638:                 my ($start,$end,$role,$sec,$group);
 7639:                 foreach my $envkey (%env) {
 7640:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7641:                         my $cid = $2.'_'.$3; 
 7642:                         if ($1 eq 'gr') {
 7643:                             $group = $4;
 7644:                             $allgroups{$cid}{$group} = $env{$envkey};
 7645:                         } else {
 7646:                             if ($4 eq '') {
 7647:                                 $sec = 'none';
 7648:                             } else {
 7649:                                 $sec = $4;
 7650:                             }
 7651:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7652:                         }
 7653:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7654:                         my $cid = $2.'_'.$3;
 7655:                         if ($4 eq '') {
 7656:                             $sec = 'none';
 7657:                         } else {
 7658:                             $sec = $4;
 7659:                         }
 7660:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7661:                     }
 7662:                 }
 7663:                 if (keys(%allroles) == 0) {
 7664:                     return;
 7665:                 }
 7666:                 foreach my $key (@courses_and_groups) {
 7667:                     my %content = %{$$access_hash{$key}};
 7668:                     my $cnum = $content{'number'};
 7669:                     my $cdom = $content{'domain'};
 7670:                     my $cid = $cdom.'_'.$cnum;
 7671:                     if (!exists($allroles{$cid})) {
 7672:                         next;
 7673:                     }    
 7674:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7675:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7676:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7677:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7678:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7679:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7680:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7681:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7682:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7683:                                         if (grep/^all$/,@sections) {
 7684:                                             return 'ok';
 7685:                                         } else {
 7686:                                             if (grep/^$sec$/,@sections) {
 7687:                                                 return 'ok';
 7688:                                             }
 7689:                                         }
 7690:                                     }
 7691:                                 }
 7692:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7693:                                     if (grep/^none$/,@groups) {
 7694:                                         return 'ok';
 7695:                                     }
 7696:                                 } else {
 7697:                                     if (grep/^all$/,@groups) {
 7698:                                         return 'ok';
 7699:                                     } 
 7700:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7701:                                         if (grep/^$group$/,@groups) {
 7702:                                             return 'ok';
 7703:                                         }
 7704:                                     }
 7705:                                 } 
 7706:                             }
 7707:                         }
 7708:                     }
 7709:                 }
 7710:             }
 7711:             if ($guest) {
 7712:                 return $guest;
 7713:             }
 7714:         }
 7715:     }
 7716:     return;
 7717: }
 7718: 
 7719: sub course_group_datechecker {
 7720:     my ($dates,$now,$status) = @_;
 7721:     my ($start,$end) = split(/\./,$dates);
 7722:     if (!$start && !$end) {
 7723:         return 'ok';
 7724:     }
 7725:     if (grep/^active$/,@{$status}) {
 7726:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7727:             return 'ok';
 7728:         }
 7729:     }
 7730:     if (grep/^previous$/,@{$status}) {
 7731:         if ($end > $now ) {
 7732:             return 'ok';
 7733:         }
 7734:     }
 7735:     if (grep/^future$/,@{$status}) {
 7736:         if ($start > $now) {
 7737:             return 'ok';
 7738:         }
 7739:     }
 7740:     return; 
 7741: }
 7742: 
 7743: sub parse_portfolio_url {
 7744:     my ($url) = @_;
 7745: 
 7746:     my ($type,$udom,$unum,$group,$file_name);
 7747:     
 7748:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7749: 	$type = 1;
 7750:         $udom = $1;
 7751:         $unum = $2;
 7752:         $file_name = $3;
 7753:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7754: 	$type = 2;
 7755:         $udom = $1;
 7756:         $unum = $2;
 7757:         $group = $3;
 7758:         $file_name = $3.'/'.$4;
 7759:     }
 7760:     if (wantarray) {
 7761: 	return ($type,$udom,$unum,$file_name,$group);
 7762:     }
 7763:     return $type;
 7764: }
 7765: 
 7766: sub is_portfolio_url {
 7767:     my ($url) = @_;
 7768:     return scalar(&parse_portfolio_url($url));
 7769: }
 7770: 
 7771: sub is_portfolio_file {
 7772:     my ($file) = @_;
 7773:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7774:         return 1;
 7775:     }
 7776:     return;
 7777: }
 7778: 
 7779: sub usertools_access {
 7780:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7781:     my ($access,%tools);
 7782:     if ($context eq '') {
 7783:         $context = 'tools';
 7784:     }
 7785:     if ($context eq 'requestcourses') {
 7786:         %tools = (
 7787:                       official   => 1,
 7788:                       unofficial => 1,
 7789:                       community  => 1,
 7790:                       textbook   => 1,
 7791:                       placement  => 1,
 7792:                       lti        => 1,
 7793:                  );
 7794:     } elsif ($context eq 'requestauthor') {
 7795:         %tools = (
 7796:                       requestauthor => 1,
 7797:                  );
 7798:     } else {
 7799:         %tools = (
 7800:                       aboutme   => 1,
 7801:                       blog      => 1,
 7802:                       webdav    => 1,
 7803:                       portfolio => 1,
 7804:                  );
 7805:     }
 7806:     return if (!defined($tools{$tool}));
 7807: 
 7808:     if (($udom eq '') || ($uname eq '')) {
 7809:         $udom = $env{'user.domain'};
 7810:         $uname = $env{'user.name'};
 7811:     }
 7812: 
 7813:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7814:         if ($action ne 'reload') {
 7815:             if ($context eq 'requestcourses') {
 7816:                 return $env{'environment.canrequest.'.$tool};
 7817:             } elsif ($context eq 'requestauthor') {
 7818:                 return $env{'environment.canrequest.author'};
 7819:             } else {
 7820:                 return $env{'environment.availabletools.'.$tool};
 7821:             }
 7822:         }
 7823:     }
 7824: 
 7825:     my ($toolstatus,$inststatus,$envkey);
 7826:     if ($context eq 'requestauthor') {
 7827:         $envkey = $context; 
 7828:     } else {
 7829:         $envkey = $context.'.'.$tool;
 7830:     }
 7831: 
 7832:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7833:          ($action ne 'reload')) {
 7834:         $toolstatus = $env{'environment.'.$envkey};
 7835:         $inststatus = $env{'environment.inststatus'};
 7836:     } else {
 7837:         if (ref($userenvref) eq 'HASH') {
 7838:             $toolstatus = $userenvref->{$envkey};
 7839:             $inststatus = $userenvref->{'inststatus'};
 7840:         } else {
 7841:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7842:             $toolstatus = $userenv{$envkey};
 7843:             $inststatus = $userenv{'inststatus'};
 7844:         }
 7845:     }
 7846: 
 7847:     if ($toolstatus ne '') {
 7848:         if ($toolstatus) {
 7849:             $access = 1;
 7850:         } else {
 7851:             $access = 0;
 7852:         }
 7853:         return $access;
 7854:     }
 7855: 
 7856:     my ($is_adv,%domdef);
 7857:     if (ref($is_advref) eq 'HASH') {
 7858:         $is_adv = $is_advref->{'is_adv'};
 7859:     } else {
 7860:         $is_adv = &is_advanced_user($udom,$uname);
 7861:     }
 7862:     if (ref($domdefref) eq 'HASH') {
 7863:         %domdef = %{$domdefref};
 7864:     } else {
 7865:         %domdef = &get_domain_defaults($udom);
 7866:     }
 7867:     if (ref($domdef{$tool}) eq 'HASH') {
 7868:         if ($is_adv) {
 7869:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7870:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7871:                     $access = 1;
 7872:                 } else {
 7873:                     $access = 0;
 7874:                 }
 7875:                 return $access;
 7876:             }
 7877:         }
 7878:         if ($inststatus ne '') {
 7879:             my ($hasaccess,$hasnoaccess);
 7880:             foreach my $affiliation (split(/:/,$inststatus)) {
 7881:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7882:                     if ($domdef{$tool}{$affiliation}) {
 7883:                         $hasaccess = 1;
 7884:                     } else {
 7885:                         $hasnoaccess = 1;
 7886:                     }
 7887:                 }
 7888:             }
 7889:             if ($hasaccess || $hasnoaccess) {
 7890:                 if ($hasaccess) {
 7891:                     $access = 1;
 7892:                 } elsif ($hasnoaccess) {
 7893:                     $access = 0; 
 7894:                 }
 7895:                 return $access;
 7896:             }
 7897:         } else {
 7898:             if ($domdef{$tool}{'default'} ne '') {
 7899:                 if ($domdef{$tool}{'default'}) {
 7900:                     $access = 1;
 7901:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7902:                     $access = 0;
 7903:                 }
 7904:                 return $access;
 7905:             }
 7906:         }
 7907:     } else {
 7908:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7909:             $access = 1;
 7910:         } else {
 7911:             $access = 0;
 7912:         }
 7913:         return $access;
 7914:     }
 7915: }
 7916: 
 7917: sub is_course_owner {
 7918:     my ($cdom,$cnum,$udom,$uname) = @_;
 7919:     if (($udom eq '') || ($uname eq '')) {
 7920:         $udom = $env{'user.domain'};
 7921:         $uname = $env{'user.name'};
 7922:     }
 7923:     unless (($udom eq '') || ($uname eq '')) {
 7924:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7925:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7926:                 return 1;
 7927:             } else {
 7928:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7929:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7930:                     return 1;
 7931:                 }
 7932:             }
 7933:         }
 7934:     }
 7935:     return;
 7936: }
 7937: 
 7938: sub is_advanced_user {
 7939:     my ($udom,$uname) = @_;
 7940:     if ($udom ne '' && $uname ne '') {
 7941:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7942:             if (wantarray) {
 7943:                 return ($env{'user.adv'},$env{'user.author'});
 7944:             } else {
 7945:                 return $env{'user.adv'};
 7946:             }
 7947:         }
 7948:     }
 7949:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7950:     my %allroles;
 7951:     my ($is_adv,$is_author);
 7952:     foreach my $role (keys(%roleshash)) {
 7953:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7954:         my $area = '/'.$tdomain.'/'.$trest;
 7955:         if ($sec ne '') {
 7956:             $area .= '/'.$sec;
 7957:         }
 7958:         if (($area ne '') && ($trole ne '')) {
 7959:             my $spec=$trole.'.'.$area;
 7960:             if ($trole =~ /^cr\//) {
 7961:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7962:             } elsif ($trole ne 'gr') {
 7963:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7964:             }
 7965:             if ($trole eq 'au') {
 7966:                 $is_author = 1;
 7967:             }
 7968:         }
 7969:     }
 7970:     foreach my $role (keys(%allroles)) {
 7971:         last if ($is_adv);
 7972:         foreach my $item (split(/:/,$allroles{$role})) {
 7973:             if ($item ne '') {
 7974:                 my ($privilege,$restrictions)=split(/&/,$item);
 7975:                 if ($privilege eq 'adv') {
 7976:                     $is_adv = 1;
 7977:                     last;
 7978:                 }
 7979:             }
 7980:         }
 7981:     }
 7982:     if (wantarray) {
 7983:         return ($is_adv,$is_author);
 7984:     }
 7985:     return $is_adv;
 7986: }
 7987: 
 7988: sub check_can_request {
 7989:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7990:     my $canreq = 0;
 7991:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7992:         $uname = $env{'user.name'};
 7993:         $udom = $env{'user.domain'};
 7994:     }
 7995:     my ($types,$typename) = &Apache::loncommon::course_types();
 7996:     my @options = ('approval','validate','autolimit');
 7997:     my $optregex = join('|',@options);
 7998:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7999:         foreach my $type (@{$types}) {
 8000:             if (&usertools_access($uname,$udom,$type,undef,
 8001:                                   'requestcourses')) {
 8002:                 $canreq ++;
 8003:                 if (ref($request_domains) eq 'HASH') {
 8004:                     push(@{$request_domains->{$type}},$udom);
 8005:                 }
 8006:                 if ($dom eq $udom) {
 8007:                     $can_request->{$type} = 1;
 8008:                 }
 8009:             }
 8010:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8011:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8012:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8013:                 if (@curr > 0) {
 8014:                     foreach my $item (@curr) {
 8015:                         if (ref($request_domains) eq 'HASH') {
 8016:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8017:                             if ($otherdom ne '') {
 8018:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 8019:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8020:                                         push(@{$request_domains->{$type}},$otherdom);
 8021:                                     }
 8022:                                 } else {
 8023:                                     push(@{$request_domains->{$type}},$otherdom);
 8024:                                 }
 8025:                             }
 8026:                         }
 8027:                     }
 8028:                     unless ($dom eq $env{'user.domain'}) {
 8029:                         $canreq ++;
 8030:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8031:                             $can_request->{$type} = 1;
 8032:                         }
 8033:                     }
 8034:                 }
 8035:             }
 8036:         }
 8037:     }
 8038:     return $canreq;
 8039: }
 8040: 
 8041: # ---------------------------------------------- Custom access rule evaluation
 8042: 
 8043: sub customaccess {
 8044:     my ($priv,$uri)=@_;
 8045:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8046:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8047:     $udom = &LONCAPA::clean_domain($udom);
 8048:     $ucrs = &LONCAPA::clean_username($ucrs);
 8049:     my $access=0;
 8050:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8051: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8052: 	if ($type eq 'user') {
 8053: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8054: 		my ($tdom,$tuname)=split(m{/},$scope);
 8055: 		if ($tdom) {
 8056: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8057: 		}
 8058: 		if ($tuname) {
 8059: 		    if ($tuname ne $env{'user.name'}) { next; }
 8060: 		}
 8061: 		$access=($effect eq 'allow');
 8062: 		last;
 8063: 	    }
 8064: 	} else {
 8065: 	    if ($role) {
 8066: 		if ($role ne $urole) { next; }
 8067: 	    }
 8068: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8069: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8070: 		if ($tdom) {
 8071: 		    if ($tdom ne $udom) { next; }
 8072: 		}
 8073: 		if ($tcrs) {
 8074: 		    if ($tcrs ne $ucrs) { next; }
 8075: 		}
 8076: 		if ($tsec) {
 8077: 		    if ($tsec ne $usec) { next; }
 8078: 		}
 8079: 		$access=($effect eq 'allow');
 8080: 		last;
 8081: 	    }
 8082: 	    if ($realm eq '' && $role eq '') {
 8083: 		$access=($effect eq 'allow');
 8084: 	    }
 8085: 	}
 8086:     }
 8087:     return $access;
 8088: }
 8089: 
 8090: # ------------------------------------------------- Check for a user privilege
 8091: 
 8092: sub allowed {
 8093:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 8094:     my $ver_orguri=$uri;
 8095:     $uri=&deversion($uri);
 8096:     my $orguri=$uri;
 8097:     $uri=&declutter($uri);
 8098: 
 8099:     if ($priv eq 'evb') {
 8100: # Evade communication block restrictions for specified role in a course
 8101:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8102:             return $1;
 8103:         } else {
 8104:             return;
 8105:         }
 8106:     }
 8107: 
 8108:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8109: # Free bre access to adm and meta resources
 8110:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8111: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8112: 	&& ($priv eq 'bre')) {
 8113: 	return 'F';
 8114:     }
 8115: 
 8116: # Free bre access to user's own portfolio contents
 8117:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8118:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8119: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8120:         my %setters;
 8121:         my ($startblock,$endblock) = 
 8122:             &Apache::loncommon::blockcheck(\%setters,'port');
 8123:         if ($startblock && $endblock) {
 8124:             return 'B';
 8125:         } else {
 8126:             return 'F';
 8127:         }
 8128:     }
 8129: 
 8130: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8131:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8132:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8133:         if (exists($env{'request.course.id'})) {
 8134:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8135:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8136:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8137:                 my $courseprivid=$env{'request.course.id'};
 8138:                 $courseprivid=~s/\_/\//;
 8139:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8140:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8141:                     return $1; 
 8142:                 } else {
 8143:                     if ($env{'request.course.sec'}) {
 8144:                         $courseprivid.='/'.$env{'request.course.sec'};
 8145:                     }
 8146:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8147:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8148:                         return $2;
 8149:                     }
 8150:                 }
 8151:             }
 8152:         }
 8153:     }
 8154: 
 8155: # Free bre to public access
 8156: 
 8157:     if ($priv eq 'bre') {
 8158:         my $copyright;
 8159:         unless ($uri =~ /ext\.tool/) {
 8160:             $copyright=&metadata($uri,'copyright');
 8161:         }
 8162: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8163:            return 'F'; 
 8164:         }
 8165:         if ($copyright eq 'priv') {
 8166:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8167: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8168: 		return '';
 8169:             }
 8170:         }
 8171:         if ($copyright eq 'domain') {
 8172:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8173: 	    unless (($env{'user.domain'} eq $1) ||
 8174:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8175: 		return '';
 8176:             }
 8177:         }
 8178:         if ($env{'request.role'}=~ /li\.\//) {
 8179:             # Library role, so allow browsing of resources in this domain.
 8180:             return 'F';
 8181:         }
 8182:         if ($copyright eq 'custom') {
 8183: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8184:         }
 8185:     }
 8186:     # Domain coordinator is trying to create a course
 8187:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8188:         # uri is the requested domain in this case.
 8189:         # comparison to 'request.role.domain' shows if the user has selected
 8190:         # a role of dc for the domain in question.
 8191:         return 'F' if ($uri eq $env{'request.role.domain'});
 8192:     }
 8193: 
 8194:     my $thisallowed='';
 8195:     my $statecond=0;
 8196:     my $courseprivid='';
 8197: 
 8198:     my $ownaccess;
 8199:     # Community Coordinator or Assistant Co-author browsing resource space.
 8200:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8201:         if ($uri eq '') {
 8202:             $ownaccess = 1;
 8203:         } else {
 8204:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8205:                 my $udom = $env{'user.domain'};
 8206:                 my $uname = $env{'user.name'};
 8207:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8208:                     $ownaccess = 1;
 8209:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8210:                     unless ($uri =~ m{\.\./}) {
 8211:                         $ownaccess = 1;
 8212:                     }
 8213:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8214:                     my $now = time;
 8215:                     if ($uri =~ m{^([^/]+)/?$}) {
 8216:                         my $adom = $1;
 8217:                         foreach my $key (keys(%env)) {
 8218:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8219:                                 my ($start,$end) = split('.',$env{$key});
 8220:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8221:                                     $ownaccess = 1;
 8222:                                     last;
 8223:                                 }
 8224:                             }
 8225:                         }
 8226:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8227:                         my $adom = $1;
 8228:                         my $aname = $2;
 8229:                         foreach my $role ('ca','aa') { 
 8230:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8231:                                 my ($start,$end) =
 8232:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 8233:                                 if (($now >= $start) && (!$end || $end < $now)) {
 8234:                                     $ownaccess = 1;
 8235:                                     last;
 8236:                                 }
 8237:                             }
 8238:                         }
 8239:                     }
 8240:                 }
 8241:             }
 8242:         }
 8243:     }
 8244: 
 8245: # Course
 8246: 
 8247:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8248:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8249:             $thisallowed.=$1;
 8250:         }
 8251:     }
 8252: 
 8253: # Domain
 8254: 
 8255:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8256:        =~/\Q$priv\E\&([^\:]*)/) {
 8257:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8258:             $thisallowed.=$1;
 8259:         }
 8260:     }
 8261: 
 8262: # User who is not author or co-author might still be able to edit
 8263: # resource of an author in the domain (e.g., if Domain Coordinator).
 8264:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8265:         (&allowed('mdc',$env{'request.course.id'}))) {
 8266:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8267:             $thisallowed.=$1;
 8268:         }
 8269:     }
 8270: 
 8271: # Course: uri itself is a course
 8272:     my $courseuri=$uri;
 8273:     $courseuri=~s/\_(\d)/\/$1/;
 8274:     $courseuri=~s/^([^\/])/\/$1/;
 8275: 
 8276:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8277:        =~/\Q$priv\E\&([^\:]*)/) {
 8278:         if ($priv eq 'mip') {
 8279:             my $rem = $1;
 8280:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8281:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8282:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8283:                 if ($cdom ne '') {
 8284:                     my %passwdconf = &get_passwdconf($cdom);
 8285:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8286:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8287:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8288:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8289:                                 unless (@inststatuses) {
 8290:                                     @inststatuses = ('default');
 8291:                                 }
 8292:                                 foreach my $status (@inststatuses) {
 8293:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8294:                                         $thisallowed.=$rem;
 8295:                                     }
 8296:                                 }
 8297:                             }
 8298:                         }
 8299:                     }
 8300:                 }
 8301:             }
 8302:         } else {
 8303:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8304:                 $thisallowed.=$1;
 8305:             }
 8306:         }
 8307:     }
 8308: 
 8309: # URI is an uploaded document for this course, default permissions don't matter
 8310: # not allowing 'edit' access (editupload) to uploaded course docs
 8311:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8312: 	$thisallowed='';
 8313:         my ($match)=&is_on_map($uri);
 8314:         if ($match) {
 8315:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8316:                   =~/\Q$priv\E\&([^\:]*)/) {
 8317:                 my $value = $1;
 8318:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8319:                 if ($deeplinkblock) {
 8320:                     $thisallowed='D';
 8321:                 } elsif ($noblockcheck) {
 8322:                     $thisallowed.=$value;
 8323:                 } else {
 8324:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8325:                     if (@blockers > 0) {
 8326:                         $thisallowed = 'B';
 8327:                     } else {
 8328:                         $thisallowed.=$value;
 8329:                     }
 8330:                 }
 8331:             }
 8332:         } else {
 8333:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8334:             if ($refuri) {
 8335:                 if ($refuri =~ m|^/adm/|) {
 8336:                     $thisallowed='F';
 8337:                 } else {
 8338:                     $refuri=&declutter($refuri);
 8339:                     my ($match) = &is_on_map($refuri);
 8340:                     if ($match) {
 8341:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8342:                         if ($deeplinkblock) {
 8343:                             $thisallowed='D';
 8344:                         } elsif ($noblockcheck) {
 8345:                             $thisallowed='F';
 8346:                         } else {
 8347:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8348:                             if (@blockers > 0) {
 8349:                                 $thisallowed = 'B';
 8350:                             } else {
 8351:                                 $thisallowed='F';
 8352:                             }
 8353:                         }
 8354:                     }
 8355:                 }
 8356:             }
 8357:         }
 8358:     }
 8359: 
 8360:     if ($priv eq 'bre'
 8361: 	&& $thisallowed ne 'F' 
 8362: 	&& $thisallowed ne '2'
 8363: 	&& &is_portfolio_url($uri)) {
 8364: 	$thisallowed = &portfolio_access($uri,$clientip);
 8365:     }
 8366: 
 8367: # Full access at system, domain or course-wide level? Exit.
 8368:     if ($thisallowed=~/F/) {
 8369: 	return 'F';
 8370:     }
 8371: 
 8372: # If this is generating or modifying users, exit with special codes
 8373: 
 8374:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8375: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8376: 	    my ($audom,$auname)=split('/',$uri);
 8377: # no author name given, so this just checks on the general right to make a co-author in this domain
 8378: 	    unless ($auname) { return $thisallowed; }
 8379: # an author name is given, so we are about to actually make a co-author for a certain account
 8380: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8381: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8382: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8383: 	}
 8384: 	return $thisallowed;
 8385:     }
 8386: #
 8387: # Gathered so far: system, domain and course wide privileges
 8388: #
 8389: # Course: See if uri or referer is an individual resource that is part of 
 8390: # the course
 8391: 
 8392:     if ($env{'request.course.id'}) {
 8393: 
 8394: # If this is modifying password (internal auth) domains must match for user and user's role.
 8395: 
 8396:         if ($priv eq 'mip') {
 8397:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8398:                 return $thisallowed;
 8399:             } else {
 8400:                 return '';
 8401:             }
 8402:         }
 8403: 
 8404:        $courseprivid=$env{'request.course.id'};
 8405:        if ($env{'request.course.sec'}) {
 8406:           $courseprivid.='/'.$env{'request.course.sec'};
 8407:        }
 8408:        $courseprivid=~s/\_/\//;
 8409:        my $checkreferer=1;
 8410:        my ($match,$cond)=&is_on_map($uri);
 8411:        if ($match) {
 8412:            $statecond=$cond;
 8413:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8414:                =~/\Q$priv\E\&([^\:]*)/) {
 8415:                my $value = $1;
 8416:                if ($priv eq 'bre') {
 8417:                    if ($noblockcheck) {
 8418:                        $thisallowed.=$value;
 8419:                    } else {
 8420:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8421:                        if (@blockers > 0) {
 8422:                            $thisallowed = 'B';
 8423:                        } else {
 8424:                            $thisallowed.=$value;
 8425:                        }
 8426:                    }
 8427:                } else {
 8428:                    $thisallowed.=$value;
 8429:                }
 8430:                $checkreferer=0;
 8431:            }
 8432:        }
 8433: 
 8434:        if ($checkreferer) {
 8435: 	  my $refuri=$env{'httpref.'.$orguri};
 8436:             unless ($refuri) {
 8437:                 foreach my $key (keys(%env)) {
 8438: 		    if ($key=~/^httpref\..*\*/) {
 8439: 			my $pattern=$key;
 8440:                         $pattern=~s/^httpref\.\/res\///;
 8441:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8442:                         $pattern=~s/\//\\\//g;
 8443:                         if ($orguri=~/$pattern/) {
 8444: 			    $refuri=$env{$key};
 8445:                         }
 8446:                     }
 8447:                 }
 8448:             }
 8449: 
 8450:          if ($refuri) { 
 8451: 	  $refuri=&declutter($refuri);
 8452:           my ($match,$cond)=&is_on_map($refuri);
 8453:             if ($match) {
 8454:               my $refstatecond=$cond;
 8455:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8456:                   =~/\Q$priv\E\&([^\:]*)/) {
 8457:                   my $value = $1;
 8458:                   if ($priv eq 'bre') {
 8459:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8460:                       if ($deeplinkblock) {
 8461:                           $thisallowed = 'D';
 8462:                       } elsif ($noblockcheck) {
 8463:                           $thisallowed.=$value;
 8464:                       } else {
 8465:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8466:                           if (@blockers > 0) {
 8467:                               $thisallowed = 'B';
 8468:                           } else {
 8469:                               $thisallowed.=$value;
 8470:                           }
 8471:                       }
 8472:                   } else {
 8473:                       $thisallowed.=$value;
 8474:                   }
 8475:                   $uri=$refuri;
 8476:                   $statecond=$refstatecond;
 8477:               }
 8478:           }
 8479:         }
 8480:        }
 8481:    }
 8482: 
 8483: #
 8484: # Gathered now: all privileges that could apply, and condition number
 8485: # 
 8486: #
 8487: # Full or no access?
 8488: #
 8489: 
 8490:     if ($thisallowed=~/F/) {
 8491: 	return 'F';
 8492:     }
 8493: 
 8494:     unless ($thisallowed) {
 8495:         return '';
 8496:     }
 8497: 
 8498: # Restrictions exist, deal with them
 8499: #
 8500: #   C:according to course preferences
 8501: #   R:according to resource settings
 8502: #   L:unless locked
 8503: #   X:according to user session state
 8504: #
 8505: 
 8506: # Possibly locked functionality, check all courses
 8507: # Locks might take effect only after 10 minutes cache expiration for other
 8508: # courses, and 2 minutes for current course
 8509: 
 8510:     my $envkey;
 8511:     if ($thisallowed=~/L/) {
 8512:         foreach $envkey (keys(%env)) {
 8513:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8514:                my $courseid=$2;
 8515:                my $roleid=$1.'.'.$2;
 8516:                $courseid=~s/^\///;
 8517:                my $expiretime=600;
 8518:                if ($env{'request.role'} eq $roleid) {
 8519: 		  $expiretime=120;
 8520:                }
 8521: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8522:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8523:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8524: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8525:                }
 8526:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8527:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8528: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8529:                        &log($env{'user.domain'},$env{'user.name'},
 8530:                             $env{'user.home'},
 8531:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8532:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8533:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8534: 		       return '';
 8535:                    }
 8536:                }
 8537:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8538:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8539: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8540:                        &log($env{'user.domain'},$env{'user.name'},
 8541:                             $env{'user.home'},
 8542:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8543:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8544:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8545: 		       return '';
 8546:                    }
 8547:                }
 8548: 	   }
 8549:        }
 8550:     }
 8551: 
 8552: #
 8553: # Rest of the restrictions depend on selected course
 8554: #
 8555: 
 8556:     unless ($env{'request.course.id'}) {
 8557: 	if ($thisallowed eq 'A') {
 8558: 	    return 'A';
 8559:         } elsif ($thisallowed eq 'B') {
 8560:             return 'B';
 8561: 	} else {
 8562: 	    return '1';
 8563: 	}
 8564:     }
 8565: 
 8566: #
 8567: # Now user is definitely in a course
 8568: #
 8569: 
 8570: 
 8571: # Course preferences
 8572: 
 8573:    if ($thisallowed=~/C/) {
 8574:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8575:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8576:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8577: 	   =~/\Q$rolecode\E/) {
 8578: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8579: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8580: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8581: 			$env{'request.course.id'});
 8582: 	   }
 8583:            return '';
 8584:        }
 8585: 
 8586:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8587: 	   =~/\Q$unamedom\E/) {
 8588: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8589: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8590: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8591: 			$env{'request.course.id'});
 8592: 	   }
 8593:            return '';
 8594:        }
 8595:    }
 8596: 
 8597: # Resource preferences
 8598: 
 8599:    if ($thisallowed=~/R/) {
 8600:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8601:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8602: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8603: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8604: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8605: 	   }
 8606: 	   return '';
 8607:        }
 8608:    }
 8609: 
 8610: # Restricted by state or randomout?
 8611: 
 8612:    if ($thisallowed=~/X/) {
 8613:       if ($env{'acc.randomout'}) {
 8614: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8615:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8616:             return ''; 
 8617:          }
 8618:       }
 8619:       if (&condval($statecond)) {
 8620: 	 return '2';
 8621:       } else {
 8622:          return '';
 8623:       }
 8624:    }
 8625: 
 8626:     if ($thisallowed eq 'A') {
 8627: 	return 'A';
 8628:     } elsif ($thisallowed eq 'B') {
 8629:         return 'B';
 8630:     } elsif ($thisallowed eq 'D') {
 8631:         return 'D';
 8632:     }
 8633:    return 'F';
 8634: }
 8635: 
 8636: # ------------------------------------------- Check construction space access
 8637: 
 8638: sub constructaccess {
 8639:     my ($url,$setpriv)=@_;
 8640: 
 8641: # We do not allow editing of previous versions of files
 8642:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8643: 
 8644: # Get username and domain from URL
 8645:     my ($ownername,$ownerdomain,$ownerhome);
 8646: 
 8647:     ($ownerdomain,$ownername) =
 8648:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8649: 
 8650: # The URL does not really point to any authorspace, forget it
 8651:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8652: 
 8653: # Now we need to see if the user has access to the authorspace of
 8654: # $ownername at $ownerdomain
 8655: 
 8656:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8657: # Real author for this?
 8658:        $ownerhome = $env{'user.home'};
 8659:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8660:           return ($ownername,$ownerdomain,$ownerhome);
 8661:        }
 8662:     } else {
 8663: # Co-author for this?
 8664:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8665:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8666:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8667:             return ($ownername,$ownerdomain,$ownerhome);
 8668:         }
 8669:         if ($env{'request.course.id'}) {
 8670:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8671:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8672:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8673:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8674:                     return ($ownername,$ownerdomain,$ownerhome);
 8675:                 }
 8676:             }
 8677:         }
 8678:     }
 8679: 
 8680: # We don't have any access right now. If we are not possibly going to do anything about this,
 8681: # we might as well leave
 8682:    unless ($setpriv) { return ''; }
 8683: 
 8684: # Backdoor access?
 8685:     my $allowed=&allowed('eco',$ownerdomain);
 8686: # Nope
 8687:     unless ($allowed) { return ''; }
 8688: # Looks like we may have access, but could be locked by the owner of the construction space
 8689:     if ($allowed eq 'U') {
 8690:         my %blocked=&get('environment',['domcoord.author'],
 8691:                          $ownerdomain,$ownername);
 8692: # Is blocked by owner
 8693:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8694:     }
 8695:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8696: # Grant temporary access
 8697:         my $then=$env{'user.login.time'};
 8698:         my $update=$env{'user.update.time'};
 8699:         if (!$update) { $update = $then; }
 8700:         my $refresh=$env{'user.refresh.time'};
 8701:         if (!$refresh) { $refresh = $update; }
 8702:         my $now = time;
 8703:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8704:                            $now,'ca','constructaccess');
 8705:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8706:         return($ownername,$ownerdomain,$ownerhome);
 8707:     }
 8708: # No business here
 8709:     return '';
 8710: }
 8711: 
 8712: # ----------------------------------------------------------- Content Blocking
 8713: 
 8714: {
 8715: # Caches for faster Course Contents display where content blocking
 8716: # is in operation (i.e., interval param set) for timed quiz.
 8717: #
 8718: # User for whom data are being temporarily cached.
 8719: my $cacheduser='';
 8720: # Course for which data are being temporarily cached.
 8721: my $cachedcid='';
 8722: # Cached blockers for this user (a hash of blocking items). 
 8723: my %cachedblockers=();
 8724: # When the data were last cached.
 8725: my $cachedlast='';
 8726: 
 8727: sub load_all_blockers {
 8728:     my ($uname,$udom)=@_;
 8729:     if (($uname ne '') && ($udom ne '')) { 
 8730:         if (($cacheduser eq $uname.':'.$udom) &&
 8731:             ($cachedcid eq $env{'request.course.id'}) &&
 8732:             (abs($cachedlast-time)<5)) {
 8733:             return;
 8734:         }
 8735:     }
 8736:     $cachedlast=time;
 8737:     $cacheduser=$uname.':'.$udom;
 8738:     $cachedcid=$env{'request.course.id'};
 8739:     %cachedblockers = &get_commblock_resources();
 8740:     return;
 8741: }
 8742: 
 8743: sub get_comm_blocks {
 8744:     my ($cdom,$cnum) = @_;
 8745:     if ($cdom eq '' || $cnum eq '') {
 8746:         return unless ($env{'request.course.id'});
 8747:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8748:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8749:     }
 8750:     my %commblocks;
 8751:     my $hashid=$cdom.'_'.$cnum;
 8752:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8753:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8754:         %commblocks = %{$blocksref};
 8755:     } else {
 8756:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8757:         my $cachetime = 600;
 8758:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8759:     }
 8760:     return %commblocks;
 8761: }
 8762: 
 8763: sub get_commblock_resources {
 8764:     my ($blocks) = @_;
 8765:     my %blockers = ();
 8766:     return %blockers unless ($env{'request.course.id'});
 8767:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8768:     my %commblocks;
 8769:     if (ref($blocks) eq 'HASH') {
 8770:         %commblocks = %{$blocks};
 8771:     } else {
 8772:         %commblocks = &get_comm_blocks();
 8773:     }
 8774:     return %blockers unless (keys(%commblocks) > 0); 
 8775:     my $navmap = Apache::lonnavmaps::navmap->new();
 8776:     return %blockers unless (ref($navmap));
 8777:     my $now = time;
 8778:     foreach my $block (keys(%commblocks)) {
 8779:         if ($block =~ /^(\d+)____(\d+)$/) {
 8780:             my ($start,$end) = ($1,$2);
 8781:             if ($start <= $now && $end >= $now) {
 8782:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8783:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8784:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8785:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8786:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8787:                             }
 8788:                         }
 8789:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8790:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8791:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8792:                             }
 8793:                         }
 8794:                     }
 8795:                 }
 8796:             }
 8797:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8798:             my $item = $1;
 8799:             my @to_test;
 8800:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8801:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8802:                     my @interval;
 8803:                     my $type = 'map';
 8804:                     if ($item eq 'course') {
 8805:                         $type = 'course';
 8806:                         @interval=&EXT("resource.0.interval");
 8807:                     } else {
 8808:                         if ($item =~ /___\d+___/) {
 8809:                             $type = 'resource';
 8810:                             @interval=&EXT("resource.0.interval",$item);
 8811:                             if (ref($navmap)) {                        
 8812:                                 my $res = $navmap->getBySymb($item); 
 8813:                                 push(@to_test,$res);
 8814:                             }
 8815:                         } else {
 8816:                             my $mapsymb = &symbread($item,1);
 8817:                             if ($mapsymb) {
 8818:                                 if (ref($navmap)) {
 8819:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8820:                                     if (ref($mapres)) {
 8821:                                         my $first = $mapres->map_start();
 8822:                                         my $finish = $mapres->map_finish();
 8823:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8824:                                         if (ref($it)) {
 8825:                                             my $res;
 8826:                                             while ($res = $it->next(undef,1)) {
 8827:                                                 next unless (ref($res));
 8828:                                                 my $symb = $res->symb();
 8829:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
 8830:                                                 @interval=&EXT("resource.0.interval",$symb);
 8831:                                                 if ($interval[1] eq 'map') {
 8832:                                                     if ($res->answerable()) {
 8833:                                                         push(@to_test,$res);
 8834:                                                         last;
 8835:                                                     }
 8836:                                                 }
 8837:                                             }
 8838:                                         }
 8839:                                     }
 8840:                                 }
 8841:                             }
 8842:                         }
 8843:                     }
 8844:                     if ($interval[0] =~ /^(\d+)/) {
 8845:                         my $timelimit = $1; 
 8846:                         my $first_access;
 8847:                         if ($type eq 'resource') {
 8848:                             $first_access=&get_first_access($interval[1],$item);
 8849:                         } elsif ($type eq 'map') {
 8850:                             $first_access=&get_first_access($interval[1],undef,$item);
 8851:                         } else {
 8852:                             $first_access=&get_first_access($interval[1]);
 8853:                         }
 8854:                         if ($first_access) {
 8855:                             my $timesup = $first_access+$timelimit;
 8856:                             if ($timesup > $now) {
 8857:                                 my $activeblock;
 8858:                                 foreach my $res (@to_test) {
 8859:                                     if ($res->answerable()) {
 8860:                                         $activeblock = 1;
 8861:                                         last;
 8862:                                     }
 8863:                                 }
 8864:                                 if ($activeblock) {
 8865:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8866:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8867:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8868:                                          }
 8869:                                     }
 8870:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8871:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8872:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8873:                                         }
 8874:                                     }
 8875:                                 }
 8876:                             }
 8877:                         }
 8878:                     }
 8879:                 }
 8880:             }
 8881:         }
 8882:     }
 8883:     return %blockers;
 8884: }
 8885: 
 8886: sub has_comm_blocking {
 8887:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8888:     my @blockers;
 8889:     return unless ($env{'request.course.id'});
 8890:     return unless ($priv eq 'bre');
 8891:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8892:     return if ($env{'request.state'} eq 'construct');
 8893:     my %blockinfo;
 8894:     if (ref($blocks) eq 'HASH') {
 8895:         %blockinfo = &get_commblock_resources($blocks);
 8896:     } else {
 8897:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8898:         %blockinfo = %cachedblockers;
 8899:     }
 8900:     return unless (keys(%blockinfo) > 0);
 8901:     my (%possibles,@symbs);
 8902:     if (!$symb) {
 8903:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8904:     }
 8905:     if ($symb) {
 8906:         @symbs = ($symb);
 8907:     } elsif (keys(%possibles)) { 
 8908:         @symbs = keys(%possibles);
 8909:     }
 8910:     my $noblock;
 8911:     foreach my $symb (@symbs) {
 8912:         last if ($noblock);
 8913:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8914:         foreach my $block (keys(%blockinfo)) {
 8915:             if ($block =~ /^firstaccess____(.+)$/) {
 8916:                 my $item = $1;
 8917:                 unless ($blocked) {
 8918:                     if (($item eq $map) || ($item eq $symb)) {
 8919:                         $noblock = 1;
 8920:                         last;
 8921:                     }
 8922:                 }
 8923:             }
 8924:             if (ref($blockinfo{$block}) eq 'HASH') {
 8925:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8926:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8927:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8928:                             push(@blockers,$block);
 8929:                         }
 8930:                     }
 8931:                 }
 8932:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8933:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8934:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8935:                             push(@blockers,$block);
 8936:                         }
 8937:                     }
 8938:                 }
 8939:             }
 8940:         }
 8941:     }
 8942:     unless ($noblock) { 
 8943:         return @blockers;
 8944:     }
 8945:     return;
 8946: }
 8947: }
 8948: 
 8949: sub deeplink_check {
 8950:     my ($priv,$symb,$uri) = @_;
 8951:     return unless ($env{'request.course.id'});
 8952:     return unless ($priv eq 'bre');
 8953:     return if ($env{'request.state'} eq 'construct');
 8954:     return if ($env{'request.role.adv'});
 8955:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8956:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8957:     my (%possibles,@symbs);
 8958:     if (!$symb) {
 8959:         $symb = &symbread($uri,1,1,1,\%possibles);
 8960:     }
 8961:     if ($symb) {
 8962:         @symbs = ($symb);
 8963:     } elsif (keys(%possibles)) {
 8964:         @symbs = keys(%possibles);
 8965:     }
 8966: 
 8967:     my ($login,$switchrole,$allow);
 8968:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8969:         my $key = $1;
 8970:         my $tinyurl;
 8971:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 8972:         if (defined($cached)) {
 8973:              $tinyurl = $result;
 8974:         } else {
 8975:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 8976:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 8977:              if ($currtiny{$key} ne '') {
 8978:                  $tinyurl = $currtiny{$key};
 8979:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 8980:              }
 8981:         }
 8982:         if ($tinyurl ne '') {
 8983:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 8984:             if ($cnumreq eq $cnum) {
 8985:                 $login = $posslogin;
 8986:             } else {
 8987:                 $switchrole = 1;
 8988:             }
 8989:         }
 8990:     }
 8991:     foreach my $symb (@symbs) {
 8992:         last if ($allow);
 8993:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 8994:         if ($deeplink eq '') {
 8995:             $allow = 1;
 8996:         } else {
 8997:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 8998:             if ($access eq 'any') {
 8999:                 $allow = 1;
 9000:             } elsif ($login) {
 9001:                 if ($access eq 'only') {
 9002:                     if ($scope eq 'res') {
 9003:                         if ($symb eq $login) {
 9004:                             $allow = 1;
 9005:                         }
 9006:                     } elsif ($scope eq 'map') {
 9007: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 9008:                     } elsif ($scope eq 'rec') {
 9009: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 9010:                     }
 9011:                 } else {
 9012:                     my ($acctype,$item) = split(/:/,$access);
 9013:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 9014:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 9015:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 9016:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 9017:                                 $allow = 1;
 9018:                             }
 9019:                         }
 9020:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9021:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9022:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 9023:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 9024:                                 $allow = 1;
 9025:                             }
 9026:                         }
 9027:                     }
 9028:                 }
 9029:             }
 9030:         }
 9031:     }
 9032:     return if ($allow);
 9033:     return 1;
 9034: }
 9035: 
 9036: # -------------------------------- Deversion and split uri into path an filename   
 9037: 
 9038: #
 9039: #   Removes the version from a URI and
 9040: #   splits it in to its filename and path to the filename.
 9041: #   Seems like File::Basename could have done this more clearly.
 9042: #   Parameters:
 9043: #      $uri   - input URI
 9044: #   Returns:
 9045: #     Two element list consisting of 
 9046: #     $pathname  - the URI up to and excluding the trailing /
 9047: #     $filename  - The part of the URI following the last /
 9048: #  NOTE:
 9049: #    Another realization of this is simply:
 9050: #    use File::Basename;
 9051: #    ...
 9052: #    $uri = shift;
 9053: #    $filename = basename($uri);
 9054: #    $path     = dirname($uri);
 9055: #    return ($filename, $path);
 9056: #
 9057: #     The implementation below is probably faster however.
 9058: #
 9059: sub split_uri_for_cond {
 9060:     my $uri=&deversion(&declutter(shift));
 9061:     my @uriparts=split(/\//,$uri);
 9062:     my $filename=pop(@uriparts);
 9063:     my $pathname=join('/',@uriparts);
 9064:     return ($pathname,$filename);
 9065: }
 9066: # --------------------------------------------------- Is a resource on the map?
 9067: 
 9068: sub is_on_map {
 9069:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9070:     #Trying to find the conditional for the file
 9071:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9072: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9073:     if ($match) {
 9074: 	return (1,$1);
 9075:     } else {
 9076: 	return (0,0);
 9077:     }
 9078: }
 9079: 
 9080: # --------------------------------------------------------- Get symb from alias
 9081: 
 9082: sub get_symb_from_alias {
 9083:     my $symb=shift;
 9084:     my ($map,$resid,$url)=&decode_symb($symb);
 9085: # Already is a symb
 9086:     if ($url) { return $symb; }
 9087: # Must be an alias
 9088:     my $aliassymb='';
 9089:     my %bighash;
 9090:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9091:                             &GDBM_READER(),0640)) {
 9092:         my $rid=$bighash{'mapalias_'.$symb};
 9093: 	if ($rid) {
 9094: 	    my ($mapid,$resid)=split(/\./,$rid);
 9095: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9096: 				    $resid,$bighash{'src_'.$rid});
 9097: 	}
 9098:         untie %bighash;
 9099:     }
 9100:     return $aliassymb;
 9101: }
 9102: 
 9103: # ----------------------------------------------------------------- Define Role
 9104: 
 9105: sub definerole {
 9106:   if (allowed('mcr','/')) {
 9107:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9108:     foreach my $role (split(':',$sysrole)) {
 9109: 	my ($crole,$cqual)=split(/\&/,$role);
 9110:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9111:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9112: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9113:                return "refused:s:$crole&$cqual"; 
 9114:             }
 9115:         }
 9116:     }
 9117:     foreach my $role (split(':',$domrole)) {
 9118: 	my ($crole,$cqual)=split(/\&/,$role);
 9119:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9120:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9121: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9122:                return "refused:d:$crole&$cqual"; 
 9123:             }
 9124:         }
 9125:     }
 9126:     foreach my $role (split(':',$courole)) {
 9127: 	my ($crole,$cqual)=split(/\&/,$role);
 9128:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9129:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9130: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9131:                return "refused:c:$crole&$cqual"; 
 9132:             }
 9133:         }
 9134:     }
 9135:     my $uhome;
 9136:     if (($uname ne '') && ($udom ne '')) {
 9137:         $uhome = &homeserver($uname,$udom);
 9138:         return $uhome if ($uhome eq 'no_host');
 9139:     } else {
 9140:         $uname = $env{'user.name'};
 9141:         $udom = $env{'user.domain'};
 9142:         $uhome = $env{'user.home'};
 9143:     }
 9144:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9145:                 "$udom:$uname:rolesdef_$rolename=".
 9146:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9147:     return reply($command,$uhome);
 9148:   } else {
 9149:     return 'refused';
 9150:   }
 9151: }
 9152: 
 9153: # ---------------- Make a metadata query against the network of library servers
 9154: 
 9155: sub metadata_query {
 9156:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9157:     my %rhash;
 9158:     my %libserv = &all_library();
 9159:     my @server_list = (defined($server_array) ? @$server_array
 9160:                                               : keys(%libserv) );
 9161:     for my $server (@server_list) {
 9162:         my $domains = ''; 
 9163:         if (ref($domains_hash) eq 'HASH') {
 9164:             $domains = $domains_hash->{$server}; 
 9165:         }
 9166: 	unless ($custom or $customshow) {
 9167: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9168: 	    $rhash{$server}=$reply;
 9169: 	}
 9170: 	else {
 9171: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9172: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9173: 			     $server);
 9174: 	    $rhash{$server}=$reply;
 9175: 	}
 9176:     }
 9177:     return \%rhash;
 9178: }
 9179: 
 9180: # ----------------------------------------- Send log queries and wait for reply
 9181: 
 9182: sub log_query {
 9183:     my ($uname,$udom,$query,%filters)=@_;
 9184:     my $uhome=&homeserver($uname,$udom);
 9185:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9186:     my $uhost=&hostname($uhome);
 9187:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9188:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9189:                        $uhome);
 9190:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9191:     return get_query_reply($queryid);
 9192: }
 9193: 
 9194: # -------------------------- Update MySQL table for portfolio file
 9195: 
 9196: sub update_portfolio_table {
 9197:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9198:     if ($group ne '') {
 9199:         $file_name =~s /^\Q$group\E//;
 9200:     }
 9201:     my $homeserver = &homeserver($uname,$udom);
 9202:     my $queryid=
 9203:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9204:                ':'.&escape($file_name).':'.$action,$homeserver);
 9205:     my $reply = &get_query_reply($queryid);
 9206:     return $reply;
 9207: }
 9208: 
 9209: # -------------------------- Update MySQL allusers table
 9210: 
 9211: sub update_allusers_table {
 9212:     my ($uname,$udom,$names) = @_;
 9213:     my $homeserver = &homeserver($uname,$udom);
 9214:     my $queryid=
 9215:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9216:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9217:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9218:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9219:                'generation='.&escape($names->{'generation'}).'%%'.
 9220:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9221:                'id='.&escape($names->{'id'}),$homeserver);
 9222:     return;
 9223: }
 9224: 
 9225: # ------- Request retrieval of institutional classlists for course(s)
 9226: 
 9227: sub fetch_enrollment_query {
 9228:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9229:     my ($homeserver,$sleep,$loopmax);
 9230:     my $maxtries = 1;
 9231:     if ($context eq 'automated') {
 9232:         $homeserver = $perlvar{'lonHostID'};
 9233:         $sleep = 2;
 9234:         $loopmax = 100;
 9235:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9236:     } else {
 9237:         $homeserver = &homeserver($cnum,$dom);
 9238:     }
 9239:     my $host=&hostname($homeserver);
 9240:     my $cmd = '';
 9241:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9242:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9243:     }
 9244:     $cmd =~ s/%%$//;
 9245:     $cmd = &escape($cmd);
 9246:     my $query = 'fetchenrollment';
 9247:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9248:     unless ($queryid=~/^\Q$host\E\_/) { 
 9249:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9250:         return 'error: '.$queryid;
 9251:     }
 9252:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9253:     my $tries = 1;
 9254:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9255:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9256:         $tries ++;
 9257:     }
 9258:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9259:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9260:     } else {
 9261:         my @responses = split(/:/,$reply);
 9262:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9263:             foreach my $line (@responses) {
 9264:                 my ($key,$value) = split(/=/,$line,2);
 9265:                 $$replyref{$key} = $value;
 9266:             }
 9267:         } else {
 9268:             my $pathname = LONCAPA::tempdir();
 9269:             foreach my $line (@responses) {
 9270:                 my ($key,$value) = split(/=/,$line);
 9271:                 $$replyref{$key} = $value;
 9272:                 if ($value > 0) {
 9273:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9274:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9275:                         my $destname = $pathname.'/'.$filename;
 9276:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9277:                         if ($xml_classlist =~ /^error/) {
 9278:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9279:                         } else {
 9280:                             if ( open(FILE,">",$destname) ) {
 9281:                                 print FILE &unescape($xml_classlist);
 9282:                                 close(FILE);
 9283:                             } else {
 9284:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9285:                             }
 9286:                         }
 9287:                     }
 9288:                 }
 9289:             }
 9290:         }
 9291:         return 'ok';
 9292:     }
 9293:     return 'error';
 9294: }
 9295: 
 9296: sub get_query_reply {
 9297:     my ($queryid,$sleep,$loopmax) = @_;;
 9298:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9299:         $sleep = 0.2;
 9300:     }
 9301:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9302:         $loopmax = 100;
 9303:     }
 9304:     my $replyfile=LONCAPA::tempdir().$queryid;
 9305:     my $reply='';
 9306:     for (1..$loopmax) {
 9307: 	sleep($sleep);
 9308:         if (-e $replyfile.'.end') {
 9309: 	    if (open(my $fh,"<",$replyfile)) {
 9310: 		$reply = join('',<$fh>);
 9311: 		close($fh);
 9312: 	   } else { return 'error: reply_file_error'; }
 9313:            return &unescape($reply);
 9314: 	}
 9315:     }
 9316:     return 'timeout:'.$queryid;
 9317: }
 9318: 
 9319: sub courselog_query {
 9320: #
 9321: # possible filters:
 9322: # url: url or symb
 9323: # username
 9324: # domain
 9325: # action: view, submit, grade
 9326: # start: timestamp
 9327: # end: timestamp
 9328: #
 9329:     my (%filters)=@_;
 9330:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9331:     if ($filters{'url'}) {
 9332: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9333:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9334:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9335:     }
 9336:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9337:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9338:     return &log_query($cname,$cdom,'courselog',%filters);
 9339: }
 9340: 
 9341: sub userlog_query {
 9342: #
 9343: # possible filters:
 9344: # action: log check role
 9345: # start: timestamp
 9346: # end: timestamp
 9347: #
 9348:     my ($uname,$udom,%filters)=@_;
 9349:     return &log_query($uname,$udom,'userlog',%filters);
 9350: }
 9351: 
 9352: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9353: 
 9354: sub auto_run {
 9355:     my ($cnum,$cdom) = @_;
 9356:     my $response = 0;
 9357:     my $settings;
 9358:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9359:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9360:         $settings = $domconfig{'autoenroll'};
 9361:         if ($settings->{'run'} eq '1') {
 9362:             $response = 1;
 9363:         }
 9364:     } else {
 9365:         my $homeserver;
 9366:         if (&is_course($cdom,$cnum)) {
 9367:             $homeserver = &homeserver($cnum,$cdom);
 9368:         } else {
 9369:             $homeserver = &domain($cdom,'primary');
 9370:         }
 9371:         if ($homeserver ne 'no_host') {
 9372:             $response = &reply('autorun:'.$cdom,$homeserver);
 9373:         }
 9374:     }
 9375:     return $response;
 9376: }
 9377: 
 9378: sub auto_get_sections {
 9379:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9380:     my $homeserver;
 9381:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9382:         $homeserver = &homeserver($cnum,$cdom);
 9383:     }
 9384:     if (!defined($homeserver)) { 
 9385:         if ($cdom =~ /^$match_domain$/) {
 9386:             $homeserver = &domain($cdom,'primary');
 9387:         }
 9388:     }
 9389:     my @secs;
 9390:     if (defined($homeserver)) {
 9391:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9392:         unless ($response eq 'refused') {
 9393:             @secs = split(/:/,$response);
 9394:         }
 9395:     }
 9396:     return @secs;
 9397: }
 9398: 
 9399: sub auto_new_course {
 9400:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9401:     my $homeserver = &homeserver($cnum,$cdom);
 9402:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9403:     return $response;
 9404: }
 9405: 
 9406: sub auto_validate_courseID {
 9407:     my ($cnum,$cdom,$inst_course_id) = @_;
 9408:     my $homeserver = &homeserver($cnum,$cdom);
 9409:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9410:     return $response;
 9411: }
 9412: 
 9413: sub auto_validate_instcode {
 9414:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9415:     my ($homeserver,$response);
 9416:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9417:         $homeserver = &homeserver($cnum,$cdom);
 9418:     }
 9419:     if (!defined($homeserver)) {
 9420:         if ($cdom =~ /^$match_domain$/) {
 9421:             $homeserver = &domain($cdom,'primary');
 9422:         }
 9423:     }
 9424:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9425:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9426:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9427:     return ($outcome,$description,$defaultcredits);
 9428: }
 9429: 
 9430: sub auto_validate_inst_crosslist {
 9431:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9432:     my ($homeserver,$response);
 9433:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9434:         $homeserver = &homeserver($cnum,$cdom);
 9435:     }
 9436:     if (!defined($homeserver)) {
 9437:         if ($cdom =~ /^$match_domain$/) {
 9438:             $homeserver = &domain($cdom,'primary');
 9439:         }
 9440:     }
 9441:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9442:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9443:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9444:                          &escape($coowner),$homeserver);
 9445:     }
 9446:     return $response;
 9447: }
 9448: 
 9449: sub auto_create_password {
 9450:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9451:     my ($homeserver,$response);
 9452:     my $create_passwd = 0;
 9453:     my $authchk = '';
 9454:     if ($udom =~ /^$match_domain$/) {
 9455:         $homeserver = &domain($udom,'primary');
 9456:     }
 9457:     if ($homeserver eq '') {
 9458:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9459:             $homeserver = &homeserver($cnum,$cdom);
 9460:         }
 9461:     }
 9462:     if ($homeserver eq '') {
 9463:         $authchk = 'nodomain';
 9464:     } else {
 9465:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9466:         if ($response eq 'refused') {
 9467:             $authchk = 'refused';
 9468:         } else {
 9469:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9470:         }
 9471:     }
 9472:     return ($authparam,$create_passwd,$authchk);
 9473: }
 9474: 
 9475: sub auto_photo_permission {
 9476:     my ($cnum,$cdom,$students) = @_;
 9477:     my $homeserver = &homeserver($cnum,$cdom);
 9478:     my ($outcome,$perm_reqd,$conditions) = 
 9479: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9480:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9481: 	return (undef,undef);
 9482:     }
 9483:     return ($outcome,$perm_reqd,$conditions);
 9484: }
 9485: 
 9486: sub auto_checkphotos {
 9487:     my ($uname,$udom,$pid) = @_;
 9488:     my $homeserver = &homeserver($uname,$udom);
 9489:     my ($result,$resulttype);
 9490:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9491: 				   &escape($uname).':'.&escape($pid),
 9492: 				   $homeserver));
 9493:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9494: 	return (undef,undef);
 9495:     }
 9496:     if ($outcome) {
 9497:         ($result,$resulttype) = split(/:/,$outcome);
 9498:     } 
 9499:     return ($result,$resulttype);
 9500: }
 9501: 
 9502: sub auto_photochoice {
 9503:     my ($cnum,$cdom) = @_;
 9504:     my $homeserver = &homeserver($cnum,$cdom);
 9505:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9506: 						       &escape($cdom),
 9507: 						       $homeserver)));
 9508:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9509: 	return (undef,undef);
 9510:     }
 9511:     return ($update,$comment);
 9512: }
 9513: 
 9514: sub auto_photoupdate {
 9515:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9516:     my $homeserver = &homeserver($cnum,$dom);
 9517:     my $host=&hostname($homeserver);
 9518:     my $cmd = '';
 9519:     my $maxtries = 1;
 9520:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9521:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9522:     }
 9523:     $cmd =~ s/%%$//;
 9524:     $cmd = &escape($cmd);
 9525:     my $query = 'institutionalphotos';
 9526:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9527:     unless ($queryid=~/^\Q$host\E\_/) {
 9528:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9529:         return 'error: '.$queryid;
 9530:     }
 9531:     my $reply = &get_query_reply($queryid);
 9532:     my $tries = 1;
 9533:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9534:         $reply = &get_query_reply($queryid);
 9535:         $tries ++;
 9536:     }
 9537:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9538:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9539:     } else {
 9540:         my @responses = split(/:/,$reply);
 9541:         my $outcome = shift(@responses); 
 9542:         foreach my $item (@responses) {
 9543:             my ($key,$value) = split(/=/,$item);
 9544:             $$photo{$key} = $value;
 9545:         }
 9546:         return $outcome;
 9547:     }
 9548:     return 'error';
 9549: }
 9550: 
 9551: sub auto_instcode_format {
 9552:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9553: 	$cat_order) = @_;
 9554:     my $courses = '';
 9555:     my @homeservers;
 9556:     if ($caller eq 'global') {
 9557: 	my %servers = &get_servers($codedom,'library');
 9558: 	foreach my $tryserver (keys(%servers)) {
 9559: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9560: 		push(@homeservers,$tryserver);
 9561: 	    }
 9562:         }
 9563:     } elsif ($caller eq 'requests') {
 9564:         if ($codedom =~ /^$match_domain$/) {
 9565:             my $chome = &domain($codedom,'primary');
 9566:             unless ($chome eq 'no_host') {
 9567:                 push(@homeservers,$chome);
 9568:             }
 9569:         }
 9570:     } else {
 9571:         push(@homeservers,&homeserver($caller,$codedom));
 9572:     }
 9573:     foreach my $code (keys(%{$instcodes})) {
 9574:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9575:     }
 9576:     chop($courses);
 9577:     my $ok_response = 0;
 9578:     my $response;
 9579:     while (@homeservers > 0 && $ok_response == 0) {
 9580:         my $server = shift(@homeservers); 
 9581:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9582:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9583:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9584: 		split(/:/,$response);
 9585:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9586:             push(@{$codetitles},&str2array($codetitles_str));
 9587:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9588:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9589:             $ok_response = 1;
 9590:         }
 9591:     }
 9592:     if ($ok_response) {
 9593:         return 'ok';
 9594:     } else {
 9595:         return $response;
 9596:     }
 9597: }
 9598: 
 9599: sub auto_instcode_defaults {
 9600:     my ($domain,$returnhash,$code_order) = @_;
 9601:     my @homeservers;
 9602: 
 9603:     my %servers = &get_servers($domain,'library');
 9604:     foreach my $tryserver (keys(%servers)) {
 9605: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9606: 	    push(@homeservers,$tryserver);
 9607: 	}
 9608:     }
 9609: 
 9610:     my $response;
 9611:     foreach my $server (@homeservers) {
 9612:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9613:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9614: 	
 9615: 	foreach my $pair (split(/\&/,$response)) {
 9616: 	    my ($name,$value)=split(/\=/,$pair);
 9617: 	    if ($name eq 'code_order') {
 9618: 		@{$code_order} = split(/\&/,&unescape($value));
 9619: 	    } else {
 9620: 		$returnhash->{&unescape($name)}=&unescape($value);
 9621: 	    }
 9622: 	}
 9623: 	return 'ok';
 9624:     }
 9625: 
 9626:     return $response;
 9627: }
 9628: 
 9629: sub auto_possible_instcodes {
 9630:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9631:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9632:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9633:         return;
 9634:     }
 9635:     my (@homeservers,$uhome);
 9636:     if (defined(&domain($domain,'primary'))) {
 9637:         $uhome=&domain($domain,'primary');
 9638:         push(@homeservers,&domain($domain,'primary'));
 9639:     } else {
 9640:         my %servers = &get_servers($domain,'library');
 9641:         foreach my $tryserver (keys(%servers)) {
 9642:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9643:                 push(@homeservers,$tryserver);
 9644:             }
 9645:         }
 9646:     }
 9647:     my $response;
 9648:     foreach my $server (@homeservers) {
 9649:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9650:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9651:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9652:             split(':',$response);
 9653:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9654:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9655:         foreach my $item (split('&',$cat_title)) {   
 9656:             my ($name,$value)=split('=',$item);
 9657:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9658:         }
 9659:         foreach my $item (split('&',$cat_order)) {
 9660:             my ($name,$value)=split('=',$item);
 9661:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9662:         }
 9663:         return 'ok';
 9664:     }
 9665:     return $response;
 9666: }
 9667: 
 9668: sub auto_courserequest_checks {
 9669:     my ($dom) = @_;
 9670:     my ($homeserver,%validations);
 9671:     if ($dom =~ /^$match_domain$/) {
 9672:         $homeserver = &domain($dom,'primary');
 9673:     }
 9674:     unless ($homeserver eq 'no_host') {
 9675:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9676:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9677:             my @items = split(/&/,$response);
 9678:             foreach my $item (@items) {
 9679:                 my ($key,$value) = split('=',$item);
 9680:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9681:             }
 9682:         }
 9683:     }
 9684:     return %validations; 
 9685: }
 9686: 
 9687: sub auto_courserequest_validation {
 9688:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9689:     my ($homeserver,$response);
 9690:     if ($dom =~ /^$match_domain$/) {
 9691:         $homeserver = &domain($dom,'primary');
 9692:     }
 9693:     unless ($homeserver eq 'no_host') {
 9694:         my $customdata;
 9695:         if (ref($custominfo) eq 'HASH') {
 9696:             $customdata = &freeze_escape($custominfo);
 9697:         }
 9698:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9699:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9700:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9701:                                     $customdata,$homeserver));
 9702:     }
 9703:     return $response;
 9704: }
 9705: 
 9706: sub auto_validate_class_sec {
 9707:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9708:     my $homeserver = &homeserver($cnum,$cdom);
 9709:     my $ownerlist;
 9710:     if (ref($owners) eq 'ARRAY') {
 9711:         $ownerlist = join(',',@{$owners});
 9712:     } else {
 9713:         $ownerlist = $owners;
 9714:     }
 9715:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9716:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9717:     return $response;
 9718: }
 9719: 
 9720: sub auto_validate_instclasses {
 9721:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9722:     my ($homeserver,%validations);
 9723:     $homeserver = &homeserver($cnum,$cdom);
 9724:     unless ($homeserver eq 'no_host') {
 9725:         my $ownerlist;
 9726:         if (ref($owners) eq 'ARRAY') {
 9727:             $ownerlist = join(',',@{$owners});
 9728:         } else {
 9729:             $ownerlist = $owners;
 9730:         }
 9731:         if (ref($classesref) eq 'HASH') {
 9732:             my $classes = &freeze_escape($classesref);
 9733:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9734:                                 ':'.$cdom.':'.$classes,$homeserver);
 9735:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9736:                 my @items = split(/&/,$response);
 9737:                 foreach my $item (@items) {
 9738:                     my ($key,$value) = split('=',$item);
 9739:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9740:                 }
 9741:             }
 9742:         }
 9743:     }
 9744:     return %validations;
 9745: }
 9746: 
 9747: sub auto_crsreq_update {
 9748:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9749:         $code,$accessstart,$accessend,$inbound) = @_;
 9750:     my ($homeserver,%crsreqresponse);
 9751:     if ($cdom =~ /^$match_domain$/) {
 9752:         $homeserver = &domain($cdom,'primary');
 9753:     }
 9754:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9755:         my $info;
 9756:         if (ref($inbound) eq 'HASH') {
 9757:             $info = &freeze_escape($inbound);
 9758:         }
 9759:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9760:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9761:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9762:                             &escape($title).':'.&escape($code).':'.
 9763:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9764:                             $homeserver);
 9765:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9766:             my @items = split(/&/,$response);
 9767:             foreach my $item (@items) {
 9768:                 my ($key,$value) = split('=',$item);
 9769:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9770:             }
 9771:         }
 9772:     }
 9773:     return \%crsreqresponse;
 9774: }
 9775: 
 9776: sub auto_export_grades {
 9777:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9778:     my ($homeserver,%exportresponse);
 9779:     if ($cdom =~ /^$match_domain$/) {
 9780:         $homeserver = &domain($cdom,'primary');
 9781:     }
 9782:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9783:         my $info;
 9784:         if (ref($inforef) eq 'HASH') {
 9785:             $info = &freeze_escape($inforef);
 9786:         }
 9787:         if (ref($gradesref) eq 'HASH') {
 9788:             my $grades = &freeze_escape($gradesref);
 9789:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9790:                                 $info.':'.$grades,$homeserver);
 9791:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9792:                 my @items = split(/&/,$response);
 9793:                 foreach my $item (@items) {
 9794:                     my ($key,$value) = split('=',$item);
 9795:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9796:                 }
 9797:             }
 9798:         }
 9799:     }
 9800:     return \%exportresponse;
 9801: }
 9802: 
 9803: sub check_instcode_cloning {
 9804:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9805:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9806:         return;
 9807:     }
 9808:     my $canclone;
 9809:     if (@{$code_order} > 0) {
 9810:         my $instcoderegexp ='^';
 9811:         my @clonecodes = split(/\&/,$cloner);
 9812:         foreach my $item (@{$code_order}) {
 9813:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9814:                 foreach my $pair (@clonecodes) {
 9815:                     my ($key,$val) = split(/\=/,$pair,2);
 9816:                     $val = &unescape($val);
 9817:                     if ($key eq $item) {
 9818:                         $instcoderegexp .= '('.$val.')';
 9819:                         last;
 9820:                     }
 9821:                 }
 9822:             } else {
 9823:                 $instcoderegexp .= $codedefaults->{$item};
 9824:             }
 9825:         }
 9826:         $instcoderegexp .= '$';
 9827:         my (@from,@to);
 9828:         eval {
 9829:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9830:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9831:         };
 9832:         if ((@from > 0) && (@to > 0)) {
 9833:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9834:             if (!@diffs) {
 9835:                 $canclone = 1;
 9836:             }
 9837:         }
 9838:     }
 9839:     return $canclone;
 9840: }
 9841: 
 9842: sub default_instcode_cloning {
 9843:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9844:     my (%codedefaults,@code_order,$canclone);
 9845:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9846:         %codedefaults = %{$codedefaultsref};
 9847:         @code_order = @{$codeorderref};
 9848:     } elsif ($clonedom) {
 9849:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9850:     }
 9851:     if (($domdefclone) && (@code_order)) {
 9852:         my @clonecodes = split(/\+/,$domdefclone);
 9853:         my $instcoderegexp ='^';
 9854:         foreach my $item (@code_order) {
 9855:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9856:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9857:             } else {
 9858:                 $instcoderegexp .= $codedefaults{$item};
 9859:             }
 9860:         }
 9861:         $instcoderegexp .= '$';
 9862:         my (@from,@to);
 9863:         eval {
 9864:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9865:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9866:         };
 9867:         if ((@from > 0) && (@to > 0)) {
 9868:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9869:             if (!@diffs) {
 9870:                 $canclone = 1;
 9871:             }
 9872:         }
 9873:     }
 9874:     return $canclone;
 9875: }
 9876: 
 9877: # ------------------------------------------------------- Course Group routines
 9878: 
 9879: sub get_coursegroups {
 9880:     my ($cdom,$cnum,$group,$namespace) = @_;
 9881:     return(&dump($namespace,$cdom,$cnum,$group));
 9882: }
 9883: 
 9884: sub modify_coursegroup {
 9885:     my ($cdom,$cnum,$groupsettings) = @_;
 9886:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9887: }
 9888: 
 9889: sub toggle_coursegroup_status {
 9890:     my ($cdom,$cnum,$group,$action) = @_;
 9891:     my ($from_namespace,$to_namespace);
 9892:     if ($action eq 'delete') {
 9893:         $from_namespace = 'coursegroups';
 9894:         $to_namespace = 'deleted_groups';
 9895:     } else {
 9896:         $from_namespace = 'deleted_groups';
 9897:         $to_namespace = 'coursegroups';
 9898:     }
 9899:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9900:     if (my $tmp = &error(%curr_group)) {
 9901:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9902:         return ('read error',$tmp);
 9903:     } else {
 9904:         my %savedsettings = %curr_group; 
 9905:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9906:         my $deloutcome;
 9907:         if ($result eq 'ok') {
 9908:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9909:         } else {
 9910:             return ('write error',$result);
 9911:         }
 9912:         if ($deloutcome eq 'ok') {
 9913:             return 'ok';
 9914:         } else {
 9915:             return ('delete error',$deloutcome);
 9916:         }
 9917:     }
 9918: }
 9919: 
 9920: sub modify_group_roles {
 9921:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9922:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9923:     my $role = 'gr/'.&escape($userprivs);
 9924:     my ($uname,$udom) = split(/:/,$user);
 9925:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9926:     if ($result eq 'ok') {
 9927:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9928:     }
 9929:     return $result;
 9930: }
 9931: 
 9932: sub modify_coursegroup_membership {
 9933:     my ($cdom,$cnum,$membership) = @_;
 9934:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9935:     return $result;
 9936: }
 9937: 
 9938: sub get_active_groups {
 9939:     my ($udom,$uname,$cdom,$cnum) = @_;
 9940:     my $now = time;
 9941:     my %groups = ();
 9942:     foreach my $key (keys(%env)) {
 9943:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9944:             my ($start,$end) = split(/\./,$env{$key});
 9945:             if (($end!=0) && ($end<$now)) { next; }
 9946:             if (($start!=0) && ($start>$now)) { next; }
 9947:             if ($1 eq $cdom && $2 eq $cnum) {
 9948:                 $groups{$3} = $env{$key} ;
 9949:             }
 9950:         }
 9951:     }
 9952:     return %groups;
 9953: }
 9954: 
 9955: sub get_group_membership {
 9956:     my ($cdom,$cnum,$group) = @_;
 9957:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9958: }
 9959: 
 9960: sub get_users_groups {
 9961:     my ($udom,$uname,$courseid) = @_;
 9962:     my @usersgroups;
 9963:     my $cachetime=1800;
 9964: 
 9965:     my $hashid="$udom:$uname:$courseid";
 9966:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9967:     if (defined($cached)) {
 9968:         @usersgroups = split(/:/,$grouplist);
 9969:     } else {  
 9970:         $grouplist = '';
 9971:         my $courseurl = &courseid_to_courseurl($courseid);
 9972:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9973:         my $access_end = $env{'course.'.$courseid.
 9974:                               '.default_enrollment_end_date'};
 9975:         my $now = time;
 9976:         foreach my $key (keys(%roleshash)) {
 9977:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9978:                 my $group = $1;
 9979:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9980:                     my $start = $2;
 9981:                     my $end = $1;
 9982:                     if ($start == -1) { next; } # deleted from group
 9983:                     if (($start!=0) && ($start>$now)) { next; }
 9984:                     if (($end!=0) && ($end<$now)) {
 9985:                         if ($access_end && $access_end < $now) {
 9986:                             if ($access_end - $end < 86400) {
 9987:                                 push(@usersgroups,$group);
 9988:                             }
 9989:                         }
 9990:                         next;
 9991:                     }
 9992:                     push(@usersgroups,$group);
 9993:                 }
 9994:             }
 9995:         }
 9996:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9997:         $grouplist = join(':',@usersgroups);
 9998:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9999:     }
10000:     return @usersgroups;
10001: }
10002: 
10003: sub devalidate_getgroups_cache {
10004:     my ($udom,$uname,$cdom,$cnum)=@_;
10005:     my $courseid = $cdom.'_'.$cnum;
10006: 
10007:     my $hashid="$udom:$uname:$courseid";
10008:     &devalidate_cache_new('getgroups',$hashid);
10009: }
10010: 
10011: # ------------------------------------------------------------------ Plain Text
10012: 
10013: sub plaintext {
10014:     my ($short,$type,$cid,$forcedefault) = @_;
10015:     if ($short =~ m{^cr/}) {
10016: 	return (split('/',$short))[-1];
10017:     }
10018:     if (!defined($cid)) {
10019:         $cid = $env{'request.course.id'};
10020:     }
10021:     my %rolenames = (
10022:                       Course    => 'std',
10023:                       Community => 'alt1',
10024:                       Placement => 'std',
10025:                     );
10026:     if ($cid ne '') {
10027:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10028:             unless ($forcedefault) {
10029:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10030:                 &Apache::lonlocal::mt_escape(\$roletext);
10031:                 return &Apache::lonlocal::mt($roletext);
10032:             }
10033:         }
10034:     }
10035:     if ((defined($type)) && (defined($rolenames{$type})) &&
10036:         (defined($rolenames{$type})) && 
10037:         (defined($prp{$short}{$rolenames{$type}}))) {
10038:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10039:     } elsif ($cid ne '') {
10040:         my $crstype = $env{'course.'.$cid.'.type'};
10041:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10042:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10043:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10044:         }
10045:     }
10046:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10047: }
10048: 
10049: # ----------------------------------------------------------------- Assign Role
10050: 
10051: sub assignrole {
10052:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10053:         $context)=@_;
10054:     my $mrole;
10055:     if ($role =~ /^cr\//) {
10056:         my $cwosec=$url;
10057:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10058: 	unless (&allowed('ccr',$cwosec)) {
10059:            my $refused = 1;
10060:            if ($context eq 'requestcourses') {
10061:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10062:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10063:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10064:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10065:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10066:                            if ($crsenv{'internal.courseowner'} eq
10067:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10068:                                $refused = '';
10069:                            }
10070:                        }
10071:                    }
10072:                }
10073:            }
10074:            if ($refused) {
10075:                &logthis('Refused custom assignrole: '.
10076:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10077:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10078:                return 'refused';
10079:            }
10080:         }
10081:         $mrole='cr';
10082:     } elsif ($role =~ /^gr\//) {
10083:         my $cwogrp=$url;
10084:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10085:         unless (&allowed('mdg',$cwogrp)) {
10086:             &logthis('Refused group assignrole: '.
10087:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10088:                     $env{'user.name'}.' at '.$env{'user.domain'});
10089:             return 'refused';
10090:         }
10091:         $mrole='gr';
10092:     } else {
10093:         my $cwosec=$url;
10094:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10095:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10096:             my $refused;
10097:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10098:                 if (!(&allowed('c'.$role,$url))) {
10099:                     $refused = 1;
10100:                 }
10101:             } else {
10102:                 $refused = 1;
10103:             }
10104:             if ($refused) {
10105:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10106:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10107:                     my %crsenv;
10108:                     if ($role eq 'cc' || $role eq 'co') {
10109:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10110:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10111:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10112:                                 if ($crsenv{'internal.courseowner'} eq 
10113:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10114:                                     $refused = '';
10115:                                 }
10116:                             }
10117:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10118:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10119:                                 if ($crsenv{'internal.courseowner'} eq 
10120:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10121:                                     $refused = '';
10122:                                 }
10123:                             }
10124:                         }
10125:                     }
10126:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10127:                     if ($role eq 'st') {
10128:                         $refused = '';
10129:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10130:                         $refused = '';
10131:                     }
10132:                 } elsif ($context eq 'requestcourses') {
10133:                     my @possroles = ('st','ta','ep','in','cc','co');
10134:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10135:                         my $wrongcc;
10136:                         if ($cnum =~ /^$match_community$/) {
10137:                             $wrongcc = 1 if ($role eq 'cc');
10138:                         } else {
10139:                             $wrongcc = 1 if ($role eq 'co');
10140:                         }
10141:                         unless ($wrongcc) {
10142:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10143:                             if ($crsenv{'internal.courseowner'} eq 
10144:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10145:                                 $refused = '';
10146:                             }
10147:                         }
10148:                     }
10149:                 } elsif ($context eq 'requestauthor') {
10150:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10151:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10152:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10153:                             $refused = '';
10154:                         } else {
10155:                             my %domdefaults = &get_domain_defaults($udom);
10156:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10157:                                 my $checkbystatus;
10158:                                 if ($env{'user.adv'}) { 
10159:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10160:                                     if ($disposition eq 'automatic') {
10161:                                         $refused = '';
10162:                                     } elsif ($disposition eq '') {
10163:                                         $checkbystatus = 1;
10164:                                     } 
10165:                                 } else {
10166:                                     $checkbystatus = 1;
10167:                                 }
10168:                                 if ($checkbystatus) {
10169:                                     if ($env{'environment.inststatus'}) {
10170:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10171:                                         foreach my $type (@inststatuses) {
10172:                                             if (($type ne '') &&
10173:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10174:                                                 $refused = '';
10175:                                             }
10176:                                         }
10177:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10178:                                         $refused = '';
10179:                                     }
10180:                                 }
10181:                             }
10182:                         }
10183:                     }
10184:                 }
10185:                 if ($refused) {
10186:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10187:                              ' '.$role.' '.$end.' '.$start.' by '.
10188: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10189:                     return 'refused';
10190:                 }
10191:             }
10192:         } elsif ($role eq 'au') {
10193:             if ($url ne '/'.$udom.'/') {
10194:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10195:                          ' to assign author role for '.$uname.':'.$udom.
10196:                          ' in domain: '.$url.' refused (wrong domain).');
10197:                 return 'refused';
10198:             }
10199:         }
10200:         $mrole=$role;
10201:     }
10202:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10203:                 "$udom:$uname:$url".'_'."$mrole=$role";
10204:     if ($end) { $command.='_'.$end; }
10205:     if ($start) {
10206: 	if ($end) { 
10207:            $command.='_'.$start; 
10208:         } else {
10209:            $command.='_0_'.$start;
10210:         }
10211:     }
10212:     my $origstart = $start;
10213:     my $origend = $end;
10214:     my $delflag;
10215: # actually delete
10216:     if ($deleteflag) {
10217: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10218: # modify command to delete the role
10219:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10220:                 "$udom:$uname:$url".'_'."$mrole";
10221: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10222: # set start and finish to negative values for userrolelog
10223:            $start=-1;
10224:            $end=-1;
10225:            $delflag = 1;
10226:         }
10227:     }
10228: # send command
10229:     my $answer=&reply($command,&homeserver($uname,$udom));
10230: # log new user role if status is ok
10231:     if ($answer eq 'ok') {
10232: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10233:         if (($role eq 'cc') || ($role eq 'in') ||
10234:             ($role eq 'ep') || ($role eq 'ad') ||
10235:             ($role eq 'ta') || ($role eq 'st') ||
10236:             ($role=~/^cr/) || ($role eq 'gr') ||
10237:             ($role eq 'co')) {
10238: # for course roles, perform group memberships changes triggered by role change.
10239:             unless ($role =~ /^gr/) {
10240:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10241:                                                  $origstart,$selfenroll,$context);
10242:             }
10243:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10244:                            $selfenroll,$context);
10245:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10246:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10247:                  ($role eq 'da')) {
10248:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10249:                            $context);
10250:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10251:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10252:                              $context); 
10253:         }
10254:         if ($role eq 'cc') {
10255:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10256:         }
10257:     }
10258:     return $answer;
10259: }
10260: 
10261: sub autoupdate_coowners {
10262:     my ($url,$end,$start,$uname,$udom) = @_;
10263:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10264:     if (($cdom ne '') && ($cnum ne '')) {
10265:         my $now = time;
10266:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10267:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10268:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10269:             my $instcode = $coursehash{'internal.coursecode'};
10270:             my $xlists = $coursehash{'internal.crosslistings'};
10271:             if ($instcode ne '') {
10272:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10273:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10274:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10275:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10276:                         unless ($result eq 'valid') {
10277:                             if ($xlists ne '') {
10278:                                 foreach my $xlist (split(',',$xlists)) {
10279:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10280:                                     $result =
10281:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10282:                                                                       $inst_crosslist,$uname.':'.$udom);
10283:                                     last if ($result eq 'valid');
10284:                                 }
10285:                             }
10286:                         }
10287:                         if ($result eq 'valid') {
10288:                             if ($coursehash{'internal.co-owners'}) {
10289:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10290:                                     push(@newcoowners,$coowner);
10291:                                 }
10292:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10293:                                     push(@newcoowners,$uname.':'.$udom);
10294:                                 }
10295:                                 @newcoowners = sort(@newcoowners);
10296:                             } else {
10297:                                 push(@newcoowners,$uname.':'.$udom);
10298:                             }
10299:                         } elsif ($coursehash{'internal.co-owners'}) {
10300:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10301:                                 unless ($coowner eq $uname.':'.$udom) {
10302:                                     push(@newcoowners,$coowner);
10303:                                 }
10304:                             }
10305:                             unless (@newcoowners > 0) {
10306:                                 $delcoowners = 1;
10307:                                 $coowners = '';
10308:                             }
10309:                         }
10310:                         if (@newcoowners || $delcoowners) {
10311:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10312:                                             $delcoowners,@newcoowners);
10313:                         }
10314:                     }
10315:                 }
10316:             }
10317:         }
10318:     }
10319: }
10320: 
10321: sub store_coowners {
10322:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10323:     my $cid = $cdom.'_'.$cnum;
10324:     my ($coowners,$delresult,$putresult);
10325:     if (@newcoowners) {
10326:         $coowners = join(',',@newcoowners);
10327:         my %coownershash = (
10328:                             'internal.co-owners' => $coowners,
10329:                            );
10330:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10331:         if ($putresult eq 'ok') {
10332:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10333:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10334:             }
10335:         }
10336:     }
10337:     if ($delcoowners) {
10338:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10339:         if ($delresult eq 'ok') {
10340:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10341:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10342:             }
10343:         }
10344:     }
10345:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10346:         my %crsinfo =
10347:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10348:         if (ref($crsinfo{$cid}) eq 'HASH') {
10349:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10350:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10351:         }
10352:     }
10353: }
10354: 
10355: # -------------------------------------------------- Modify user authentication
10356: # Overrides without validation
10357: 
10358: sub modifyuserauth {
10359:     my ($udom,$uname,$umode,$upass)=@_;
10360:     my $uhome=&homeserver($uname,$udom);
10361:     my $allowed;
10362:     if (&allowed('mau',$udom)) {
10363:         $allowed = 1;
10364:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10365:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10366:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10367:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10368:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10369:         if (($cdom ne '') && ($cnum ne '')) {
10370:             my $is_owner = &is_course_owner($cdom,$cnum);
10371:             if ($is_owner) {
10372:                 $allowed = 1;
10373:             }
10374:         }
10375:     }
10376:     unless ($allowed) { return 'refused'; }
10377:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10378:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10379:              ' in domain '.$env{'request.role.domain'});  
10380:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10381: 		     &escape($upass),$uhome);
10382:     my $ip = &get_requestor_ip();
10383:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10384:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10385:          '(Remote '.$ip.'): '.$reply);
10386:     &log($udom,,$uname,$uhome,
10387:         'Authentication changed by '.$env{'user.domain'}.', '.
10388:                                      $env{'user.name'}.', '.$umode.
10389:          '(Remote '.$ip.'): '.$reply);
10390:     unless ($reply eq 'ok') {
10391:         &logthis('Authentication mode error: '.$reply);
10392: 	return 'error: '.$reply;
10393:     }   
10394:     return 'ok';
10395: }
10396: 
10397: # --------------------------------------------------------------- Modify a user
10398: 
10399: sub modifyuser {
10400:     my ($udom,    $uname, $uid,
10401:         $umode,   $upass, $first,
10402:         $middle,  $last,  $gene,
10403:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10404:     $udom= &LONCAPA::clean_domain($udom);
10405:     $uname=&LONCAPA::clean_username($uname);
10406:     my $showcandelete = 'none';
10407:     if (ref($candelete) eq 'ARRAY') {
10408:         if (@{$candelete} > 0) {
10409:             $showcandelete = join(', ',@{$candelete});
10410:         }
10411:     }
10412:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10413:              $umode.', '.$first.', '.$middle.', '.
10414: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10415:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10416:                                      ' desiredhome not specified'). 
10417:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10418:              ' in domain '.$env{'request.role.domain'});
10419:     my $uhome=&homeserver($uname,$udom,'true');
10420:     my $newuser;
10421:     if ($uhome eq 'no_host') {
10422:         $newuser = 1;
10423:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10424:                 ($umode eq 'lti')) {
10425:             return 'error: more information needed to create new user';
10426:         }
10427:     }
10428: # ----------------------------------------------------------------- Create User
10429:     if (($uhome eq 'no_host') && 
10430: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10431:         my $unhome='';
10432:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10433:             $unhome = $desiredhome;
10434: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10435: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10436:         } else { # load balancing routine for determining $unhome
10437:             my $loadm=10000000;
10438: 	    my %servers = &get_servers($udom,'library');
10439: 	    foreach my $tryserver (keys(%servers)) {
10440: 		my $answer=reply('load',$tryserver);
10441: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10442: 		    $loadm=$answer;
10443: 		    $unhome=$tryserver;
10444: 		}
10445: 	    }
10446:         }
10447:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10448: 	    return 'error: unable to find a home server for '.$uname.
10449:                    ' in domain '.$udom;
10450:         }
10451:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10452:                          &escape($upass),$unhome);
10453: 	unless ($reply eq 'ok') {
10454:             return 'error: '.$reply;
10455:         }   
10456:         $uhome=&homeserver($uname,$udom,'true');
10457:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10458: 	    return 'error: unable verify users home machine.';
10459:         }
10460:     }   # End of creation of new user
10461: # ---------------------------------------------------------------------- Add ID
10462:     if ($uid) {
10463:        $uid=~tr/A-Z/a-z/;
10464:        my %uidhash=&idrget($udom,$uname);
10465:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10466:          && (!$forceid)) {
10467: 	  unless ($uid eq $uidhash{$uname}) {
10468: 	      return 'error: user id "'.$uid.'" does not match '.
10469:                   'current user id "'.$uidhash{$uname}.'".';
10470:           }
10471:        } else {
10472: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10473:        }
10474:     }
10475: # -------------------------------------------------------------- Add names, etc
10476:     my @tmp=&get('environment',
10477: 		   ['firstname','middlename','lastname','generation','id',
10478:                     'permanentemail','inststatus'],
10479: 		   $udom,$uname);
10480:     my (%names,%oldnames);
10481:     if ($tmp[0] =~ m/^error:.*/) { 
10482:         %names=(); 
10483:     } else {
10484:         %names = @tmp;
10485:         %oldnames = %names;
10486:     }
10487: #
10488: # If name, email and/or uid are blank (e.g., because an uploaded file
10489: # of users did not contain them), do not overwrite existing values
10490: # unless field is in $candelete array ref.  
10491: #
10492: 
10493:     my @fields = ('firstname','middlename','lastname','generation',
10494:                   'permanentemail','id');
10495:     my %newvalues;
10496:     if (ref($candelete) eq 'ARRAY') {
10497:         foreach my $field (@fields) {
10498:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10499:                 if ($field eq 'firstname') {
10500:                     $names{$field} = $first;
10501:                 } elsif ($field eq 'middlename') {
10502:                     $names{$field} = $middle;
10503:                 } elsif ($field eq 'lastname') {
10504:                     $names{$field} = $last;
10505:                 } elsif ($field eq 'generation') { 
10506:                     $names{$field} = $gene;
10507:                 } elsif ($field eq 'permanentemail') {
10508:                     $names{$field} = $email;
10509:                 } elsif ($field eq 'id') {
10510:                     $names{$field}  = $uid;
10511:                 }
10512:             }
10513:         }
10514:     }
10515:     if ($first)  { $names{'firstname'}  = $first; }
10516:     if (defined($middle)) { $names{'middlename'} = $middle; }
10517:     if ($last)   { $names{'lastname'}   = $last; }
10518:     if (defined($gene))   { $names{'generation'} = $gene; }
10519:     if ($email) {
10520:        $email=~s/[^\w\@\.\-\,]//gs;
10521:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10522:     }
10523:     if ($uid) { $names{'id'}  = $uid; }
10524:     if (defined($inststatus)) {
10525:         $names{'inststatus'} = '';
10526:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10527:         if (ref($usertypes) eq 'HASH') {
10528:             my @okstatuses; 
10529:             foreach my $item (split(/:/,$inststatus)) {
10530:                 if (defined($usertypes->{$item})) {
10531:                     push(@okstatuses,$item);  
10532:                 }
10533:             }
10534:             if (@okstatuses) {
10535:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10536:             }
10537:         }
10538:     }
10539:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10540:                  $umode.', '.$first.', '.$middle.', '.
10541:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10542:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10543:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10544:     } else {
10545:         $logmsg .= ' during self creation';
10546:     }
10547:     my $changed;
10548:     if ($newuser) {
10549:         $changed = 1;
10550:     } else {
10551:         foreach my $field (@fields) {
10552:             if ($names{$field} ne $oldnames{$field}) {
10553:                 $changed = 1;
10554:                 last;
10555:             }
10556:         }
10557:     }
10558:     unless ($changed) {
10559:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10560:         &logthis($logmsg);
10561:         return 'ok';
10562:     }
10563:     my $reply = &put('environment', \%names, $udom,$uname);
10564:     if ($reply ne 'ok') { 
10565:         return 'error: '.$reply;
10566:     }
10567:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10568:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10569:     }
10570:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10571:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10572:     $logmsg = 'Success modifying user '.$logmsg;
10573:     &logthis($logmsg);
10574:     return 'ok';
10575: }
10576: 
10577: # -------------------------------------------------------------- Modify student
10578: 
10579: sub modifystudent {
10580:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10581:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10582:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10583:     if (!$cid) {
10584: 	unless ($cid=$env{'request.course.id'}) {
10585: 	    return 'not_in_class';
10586: 	}
10587:     }
10588: # --------------------------------------------------------------- Make the user
10589:     my $reply=&modifyuser
10590: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10591:          $desiredhome,$email,$inststatus);
10592:     unless ($reply eq 'ok') { return $reply; }
10593:     # This will cause &modify_student_enrollment to get the uid from the
10594:     # student's environment
10595:     $uid = undef if (!$forceid);
10596:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10597:                                         $gene,$usec,$end,$start,$type,$locktype,
10598:                                         $cid,$selfenroll,$context,$credits,$instsec);
10599:     return $reply;
10600: }
10601: 
10602: sub modify_student_enrollment {
10603:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10604:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10605:     my ($cdom,$cnum,$chome);
10606:     if (!$cid) {
10607: 	unless ($cid=$env{'request.course.id'}) {
10608: 	    return 'not_in_class';
10609: 	}
10610: 	$cdom=$env{'course.'.$cid.'.domain'};
10611: 	$cnum=$env{'course.'.$cid.'.num'};
10612:     } else {
10613: 	($cdom,$cnum)=split(/_/,$cid);
10614:     }
10615:     $chome=$env{'course.'.$cid.'.home'};
10616:     if (!$chome) {
10617: 	$chome=&homeserver($cnum,$cdom);
10618:     }
10619:     if (!$chome) { return 'unknown_course'; }
10620:     # Make sure the user exists
10621:     my $uhome=&homeserver($uname,$udom);
10622:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10623: 	return 'error: no such user';
10624:     }
10625:     # Get student data if we were not given enough information
10626:     if (!defined($first)  || $first  eq '' || 
10627:         !defined($last)   || $last   eq '' || 
10628:         !defined($uid)    || $uid    eq '' || 
10629:         !defined($middle) || $middle eq '' || 
10630:         !defined($gene)   || $gene   eq '') {
10631:         # They did not supply us with enough data to enroll the student, so
10632:         # we need to pick up more information.
10633:         my %tmp = &get('environment',
10634:                        ['firstname','middlename','lastname', 'generation','id']
10635:                        ,$udom,$uname);
10636: 
10637:         #foreach my $key (keys(%tmp)) {
10638:         #    &logthis("key $key = ".$tmp{$key});
10639:         #}
10640:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10641:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10642:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10643:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10644:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10645:     }
10646:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10647:     my $user = "$uname:$udom";
10648:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10649:     my $reply=cput('classlist',
10650: 		   {$user => 
10651: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10652: 		   $cdom,$cnum);
10653:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10654:         &devalidate_getsection_cache($udom,$uname,$cid);
10655:     } else { 
10656: 	return 'error: '.$reply;
10657:     }
10658:     # Add student role to user
10659:     my $uurl='/'.$cid;
10660:     $uurl=~s/\_/\//g;
10661:     if ($usec) {
10662: 	$uurl.='/'.$usec;
10663:     }
10664:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10665:                              $selfenroll,$context);
10666:     if ($result ne 'ok') {
10667:         if ($old_entry{$user} ne '') {
10668:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10669:         } else {
10670:             $reply = &del('classlist',[$user],$cdom,$cnum);
10671:         }
10672:     }
10673:     return $result; 
10674: }
10675: 
10676: sub format_name {
10677:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10678:     my $name;
10679:     if ($first ne 'lastname') {
10680: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10681:     } else {
10682: 	if ($lastname=~/\S/) {
10683: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10684: 	    $name=~s/\s+,/,/;
10685: 	} else {
10686: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10687: 	}
10688:     }
10689:     $name=~s/^\s+//;
10690:     $name=~s/\s+$//;
10691:     $name=~s/\s+/ /g;
10692:     return $name;
10693: }
10694: 
10695: # ------------------------------------------------- Write to course preferences
10696: 
10697: sub writecoursepref {
10698:     my ($courseid,%prefs)=@_;
10699:     $courseid=~s/^\///;
10700:     $courseid=~s/\_/\//g;
10701:     my ($cdomain,$cnum)=split(/\//,$courseid);
10702:     my $chome=homeserver($cnum,$cdomain);
10703:     if (($chome eq '') || ($chome eq 'no_host')) { 
10704: 	return 'error: no such course';
10705:     }
10706:     my $cstring='';
10707:     foreach my $pref (keys(%prefs)) {
10708: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10709:     }
10710:     $cstring=~s/\&$//;
10711:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10712: }
10713: 
10714: # ---------------------------------------------------------- Make/modify course
10715: 
10716: sub createcourse {
10717:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10718:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10719:     $url=&declutter($url);
10720:     my $cid='';
10721:     if ($context eq 'requestcourses') {
10722:         my $can_create = 0;
10723:         my ($ownername,$ownerdom) = split(':',$course_owner);
10724:         if ($udom eq $ownerdom) {
10725:             my $reload;
10726:             if (($callercontext eq 'auto') &&
10727:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10728:                 $reload = 'reload';
10729:             }
10730:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10731:                                   $context)) {
10732:                 $can_create = 1;
10733:             }
10734:         } else {
10735:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10736:                                            $category);
10737:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10738:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10739:                 if (@curr > 0) {
10740:                     my @options = qw(approval validate autolimit);
10741:                     my $optregex = join('|',@options);
10742:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10743:                         $can_create = 1;
10744:                     }
10745:                 }
10746:             }
10747:         }
10748:         if ($can_create) {
10749:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10750:                 unless (&allowed('ccc',$udom)) {
10751:                     return 'refused'; 
10752:                 }
10753:             }
10754:         } else {
10755:             return 'refused';
10756:         }
10757:     } elsif (!&allowed('ccc',$udom)) {
10758:         return 'refused';
10759:     }
10760: # --------------------------------------------------------------- Get Unique ID
10761:     my $uname;
10762:     if ($cnum =~ /^$match_courseid$/) {
10763:         my $chome=&homeserver($cnum,$udom,'true');
10764:         if (($chome eq '') || ($chome eq 'no_host')) {
10765:             $uname = $cnum;
10766:         } else {
10767:             $uname = &generate_coursenum($udom,$crstype);
10768:         }
10769:     } else {
10770:         $uname = &generate_coursenum($udom,$crstype);
10771:     }
10772:     return $uname if ($uname =~ /^error/);
10773: # -------------------------------------------------- Check supplied server name
10774:     if (!defined($course_server)) {
10775:         if (defined(&domain($udom,'primary'))) {
10776:             $course_server = &domain($udom,'primary');
10777:         } else {
10778:             $course_server = $env{'user.home'}; 
10779:         }
10780:     }
10781:     my %host_servers =
10782:         &Apache::lonnet::get_servers($udom,'library');
10783:     unless ($host_servers{$course_server}) {
10784:         return 'error: invalid home server for course: '.$course_server;
10785:     }
10786: # ------------------------------------------------------------- Make the course
10787:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10788:                       $course_server);
10789:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10790:     my $uhome=&homeserver($uname,$udom,'true');
10791:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10792: 	return 'error: no such course';
10793:     }
10794: # ----------------------------------------------------------------- Course made
10795: # log existence
10796:     my $now = time;
10797:     my $newcourse = {
10798:                     $udom.'_'.$uname => {
10799:                                      description => $description,
10800:                                      inst_code   => $inst_code,
10801:                                      owner       => $course_owner,
10802:                                      type        => $crstype,
10803:                                      creator     => $env{'user.name'}.':'.
10804:                                                     $env{'user.domain'},
10805:                                      created     => $now,
10806:                                      context     => $context,
10807:                                                 },
10808:                     };
10809:     &courseidput($udom,$newcourse,$uhome,'notime');
10810: # set toplevel url
10811:     my $topurl=$url;
10812:     unless ($nonstandard) {
10813: # ------------------------------------------ For standard courses, make top url
10814:         my $mapurl=&clutter($url);
10815:         if ($mapurl eq '/res/') { $mapurl=''; }
10816:         $env{'form.initmap'}=(<<ENDINITMAP);
10817: <map>
10818: <resource id="1" type="start"></resource>
10819: <resource id="2" src="$mapurl"></resource>
10820: <resource id="3" type="finish"></resource>
10821: <link index="1" from="1" to="2"></link>
10822: <link index="2" from="2" to="3"></link>
10823: </map>
10824: ENDINITMAP
10825:         $topurl=&declutter(
10826:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10827:                           );
10828:     }
10829: # ----------------------------------------------------------- Write preferences
10830:     &writecoursepref($udom.'_'.$uname,
10831:                      ('description'              => $description,
10832:                       'url'                      => $topurl,
10833:                       'internal.creator'         => $env{'user.name'}.':'.
10834:                                                     $env{'user.domain'},
10835:                       'internal.created'         => $now,
10836:                       'internal.creationcontext' => $context)
10837:                     );
10838:     return '/'.$udom.'/'.$uname;
10839: }
10840: 
10841: # ------------------------------------------------------------------- Create ID
10842: sub generate_coursenum {
10843:     my ($udom,$crstype) = @_;
10844:     my $domdesc = &domain($udom);
10845:     return 'error: invalid domain' if ($domdesc eq '');
10846:     my $first;
10847:     if ($crstype eq 'Community') {
10848:         $first = '0';
10849:     } else {
10850:         $first = int(1+rand(9)); 
10851:     } 
10852:     my $uname=$first.
10853:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10854:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10855:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10856: # ----------------------------------------------- Make sure that does not exist
10857:     my $uhome=&homeserver($uname,$udom,'true');
10858:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10859:         if ($crstype eq 'Community') {
10860:             $first = '0';
10861:         } else {
10862:             $first = int(1+rand(9));
10863:         }
10864:         $uname=$first.
10865:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10866:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10867:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10868:         $uhome=&homeserver($uname,$udom,'true');
10869:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10870:             return 'error: unable to generate unique course-ID';
10871:         }
10872:     }
10873:     return $uname;
10874: }
10875: 
10876: sub is_course {
10877:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10878:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10879: 
10880:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10881:     my $uhome=&homeserver($cnum,$cdom);
10882:     my $iscourse;
10883:     if (grep { $_ eq $uhome } current_machine_ids()) {
10884:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10885:     } else {
10886:         my $hashid = $cdom.':'.$cnum;
10887:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10888:         unless (defined($cached)) {
10889:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10890:                                         $cnum,undef,undef,'.');
10891:             $iscourse = 0;
10892:             if (exists($courses{$cdom.'_'.$cnum})) {
10893:                 $iscourse = 1;
10894:             }
10895:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10896:         }
10897:     }
10898:     return unless ($iscourse);
10899:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10900: }
10901: 
10902: sub store_userdata {
10903:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10904:     my $result;
10905:     if ($datakey ne '') {
10906:         if (ref($storehash) eq 'HASH') {
10907:             if ($udom eq '' || $uname eq '') {
10908:                 $udom = $env{'user.domain'};
10909:                 $uname = $env{'user.name'};
10910:             }
10911:             my $uhome=&homeserver($uname,$udom);
10912:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10913:                 $result = 'error: no_host';
10914:             } else {
10915:                 $storehash->{'ip'} = &get_requestor_ip();
10916:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10917: 
10918:                 my $namevalue='';
10919:                 foreach my $key (keys(%{$storehash})) {
10920:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10921:                 }
10922:                 $namevalue=~s/\&$//;
10923:                 unless ($namespace eq 'courserequests') {
10924:                     $datakey = &escape($datakey);
10925:                 }
10926:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10927:                                   $namevalue,$uhome);
10928:             }
10929:         } else {
10930:             $result = 'error: data to store was not a hash reference'; 
10931:         }
10932:     } else {
10933:         $result= 'error: invalid requestkey'; 
10934:     }
10935:     return $result;
10936: }
10937: 
10938: # ---------------------------------------------------------- Assign Custom Role
10939: 
10940: sub assigncustomrole {
10941:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10942:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10943:                        $end,$start,$deleteflag,$selfenroll,$context);
10944: }
10945: 
10946: # ----------------------------------------------------------------- Revoke Role
10947: 
10948: sub revokerole {
10949:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10950:     my $now=time;
10951:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10952: }
10953: 
10954: # ---------------------------------------------------------- Revoke Custom Role
10955: 
10956: sub revokecustomrole {
10957:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10958:     my $now=time;
10959:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10960:            $deleteflag,$selfenroll,$context);
10961: }
10962: 
10963: # ------------------------------------------------------------ Disk usage
10964: sub diskusage {
10965:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10966:     $directorypath =~ s/\/$//;
10967:     my $listing=&reply('du2:'.&escape($directorypath).':'
10968:                        .&escape($getpropath).':'.&escape($uname).':'
10969:                        .&escape($udom),homeserver($uname,$udom));
10970:     if ($listing eq 'unknown_cmd') {
10971:         if ($getpropath) {
10972:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10973:         }
10974:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10975:     }
10976:     return $listing;
10977: }
10978: 
10979: sub is_locked {
10980:     my ($file_name, $domain, $user, $which) = @_;
10981:     my @check;
10982:     my $is_locked;
10983:     push (@check,$file_name);
10984:     my %locked = &get('file_permissions',\@check,
10985: 		      $env{'user.domain'},$env{'user.name'});
10986:     my ($tmp)=keys(%locked);
10987:     if ($tmp=~/^error:/) { undef(%locked); }
10988:     
10989:     if (ref($locked{$file_name}) eq 'ARRAY') {
10990:         $is_locked = 'false';
10991:         foreach my $entry (@{$locked{$file_name}}) {
10992:            if (ref($entry) eq 'ARRAY') {
10993:                $is_locked = 'true';
10994:                if (ref($which) eq 'ARRAY') {
10995:                    push(@{$which},$entry);
10996:                } else {
10997:                    last;
10998:                }
10999:            }
11000:        }
11001:     } else {
11002:         $is_locked = 'false';
11003:     }
11004:     return $is_locked;
11005: }
11006: 
11007: sub declutter_portfile {
11008:     my ($file) = @_;
11009:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11010:     return $file;
11011: }
11012: 
11013: # ------------------------------------------------------------- Mark as Read Only
11014: 
11015: sub mark_as_readonly {
11016:     my ($domain,$user,$files,$what) = @_;
11017:     my %current_permissions = &dump('file_permissions',$domain,$user);
11018:     my ($tmp)=keys(%current_permissions);
11019:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11020:     foreach my $file (@{$files}) {
11021: 	$file = &declutter_portfile($file);
11022:         push(@{$current_permissions{$file}},$what);
11023:     }
11024:     &put('file_permissions',\%current_permissions,$domain,$user);
11025:     return;
11026: }
11027: 
11028: # ------------------------------------------------------------Save Selected Files
11029: 
11030: sub save_selected_files {
11031:     my ($user, $path, @files) = @_;
11032:     my $filename = $user."savedfiles";
11033:     my @other_files = &files_not_in_path($user, $path);
11034:     open (OUT,'>',LONCAPA::tempdir().$filename);
11035:     foreach my $file (@files) {
11036:         print (OUT $env{'form.currentpath'}.$file."\n");
11037:     }
11038:     foreach my $file (@other_files) {
11039:         print (OUT $file."\n");
11040:     }
11041:     close (OUT);
11042:     return 'ok';
11043: }
11044: 
11045: sub clear_selected_files {
11046:     my ($user) = @_;
11047:     my $filename = $user."savedfiles";
11048:     open (OUT,'>',LONCAPA::tempdir().$filename);
11049:     print (OUT undef);
11050:     close (OUT);
11051:     return ("ok");    
11052: }
11053: 
11054: sub files_in_path {
11055:     my ($user, $path) = @_;
11056:     my $filename = $user."savedfiles";
11057:     my %return_files;
11058:     open (IN,'<',LONCAPA::tempdir().$filename);
11059:     while (my $line_in = <IN>) {
11060:         chomp ($line_in);
11061:         my @paths_and_file = split (m!/!, $line_in);
11062:         my $file_part = pop (@paths_and_file);
11063:         my $path_part = join ('/', @paths_and_file);
11064:         $path_part.='/';
11065:         my $path_and_file = $path_part.$file_part;
11066:         if ($path_part eq $path) {
11067:             $return_files{$file_part}= 'selected';
11068:         }
11069:     }
11070:     close (IN);
11071:     return (\%return_files);
11072: }
11073: 
11074: # called in portfolio select mode, to show files selected NOT in current directory
11075: sub files_not_in_path {
11076:     my ($user, $path) = @_;
11077:     my $filename = $user."savedfiles";
11078:     my @return_files;
11079:     my $path_part;
11080:     open(IN, '<',LONCAPA::tempdir().$filename);
11081:     while (my $line = <IN>) {
11082:         #ok, I know it's clunky, but I want it to work
11083:         my @paths_and_file = split(m|/|, $line);
11084:         my $file_part = pop(@paths_and_file);
11085:         chomp($file_part);
11086:         my $path_part = join('/', @paths_and_file);
11087:         $path_part .= '/';
11088:         my $path_and_file = $path_part.$file_part;
11089:         if ($path_part ne $path) {
11090:             push(@return_files, ($path_and_file));
11091:         }
11092:     }
11093:     close(OUT);
11094:     return (@return_files);
11095: }
11096: 
11097: #------------------------------Submitted/Handedback Portfolio Files Versioning
11098:  
11099: sub portfiles_versioning {
11100:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11101:     my $portfolio_root = '/userfiles/portfolio';
11102:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11103:     foreach my $file (@{$portfiles}) {
11104:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11105:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11106:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11107:         my $getpropath = 1;
11108:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11109:                                              $stu_name,$getpropath);
11110:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11111:         my $new_answer = 
11112:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11113:         if ($new_answer ne 'problem getting file') {
11114:             push(@{$versioned_portfiles}, $directory.$new_answer);
11115:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11116:                               [$symb,$env{'request.course.id'},'graded']);
11117:         }
11118:     }
11119: }
11120: 
11121: sub get_next_version {
11122:     my ($answer_name, $answer_ext, $dir_list) = @_;
11123:     my $version;
11124:     if (ref($dir_list) eq 'ARRAY') {
11125:         foreach my $row (@{$dir_list}) {
11126:             my ($file) = split(/\&/,$row,2);
11127:             my ($file_name,$file_version,$file_ext) =
11128:                 &file_name_version_ext($file);
11129:             if (($file_name eq $answer_name) &&
11130:                 ($file_ext eq $answer_ext)) {
11131:                      # gets here if filename and extension match,
11132:                      # regardless of version
11133:                 if ($file_version ne '') {
11134:                     # a versioned file is found  so save it for later
11135:                     if ($file_version > $version) {
11136:                         $version = $file_version;
11137:                     }
11138:                 }
11139:             }
11140:         }
11141:     }
11142:     $version ++;
11143:     return($version);
11144: }
11145: 
11146: sub version_selected_portfile {
11147:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11148:     my ($answer_name,$answer_ver,$answer_ext) =
11149:         &file_name_version_ext($file_name);
11150:     my $new_answer;
11151:     $env{'form.copy'} =
11152:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11153:     if($env{'form.copy'} eq '-1') {
11154:         $new_answer = 'problem getting file';
11155:     } else {
11156:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11157:         my $copy_result = 
11158:             &finishuserfileupload($stu_name,$domain,'copy',
11159:                                   '/portfolio'.$directory.$new_answer);
11160:     }
11161:     undef($env{'form.copy'});
11162:     return ($new_answer);
11163: }
11164: 
11165: sub file_name_version_ext {
11166:     my ($file)=@_;
11167:     my @file_parts = split(/\./, $file);
11168:     my ($name,$version,$ext);
11169:     if (@file_parts > 1) {
11170:         $ext=pop(@file_parts);
11171:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11172:             $version=pop(@file_parts);
11173:         }
11174:         $name=join('.',@file_parts);
11175:     } else {
11176:         $name=join('.',@file_parts);
11177:     }
11178:     return($name,$version,$ext);
11179: }
11180: 
11181: #----------------------------------------------Get portfolio file permissions
11182: 
11183: sub get_portfile_permissions {
11184:     my ($domain,$user) = @_;
11185:     my %current_permissions = &dump('file_permissions',$domain,$user);
11186:     my ($tmp)=keys(%current_permissions);
11187:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11188:     return \%current_permissions;
11189: }
11190: 
11191: #---------------------------------------------Get portfolio file access controls
11192: 
11193: sub get_access_controls {
11194:     my ($current_permissions,$group,$file) = @_;
11195:     my %access;
11196:     my $real_file = $file;
11197:     $file =~ s/\.meta$//;
11198:     if (defined($file)) {
11199:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11200:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11201:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11202:             }
11203:         }
11204:     } else {
11205:         foreach my $key (keys(%{$current_permissions})) {
11206:             if ($key =~ /\0accesscontrol$/) {
11207:                 if (defined($group)) {
11208:                     if ($key !~ m-^\Q$group\E/-) {
11209:                         next;
11210:                     }
11211:                 }
11212:                 my ($fullpath) = split(/\0/,$key);
11213:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11214:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11215:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11216:                     }
11217:                 }
11218:             }
11219:         }
11220:     }
11221:     return %access;
11222: }
11223: 
11224: sub modify_access_controls {
11225:     my ($file_name,$changes,$domain,$user)=@_;
11226:     my ($outcome,$deloutcome);
11227:     my %store_permissions;
11228:     my %new_values;
11229:     my %new_control;
11230:     my %translation;
11231:     my @deletions = ();
11232:     my $now = time;
11233:     if (exists($$changes{'activate'})) {
11234:         if (ref($$changes{'activate'}) eq 'HASH') {
11235:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11236:             my $numnew = scalar(@newitems);
11237:             for (my $i=0; $i<$numnew; $i++) {
11238:                 my $newkey = $newitems[$i];
11239:                 my $newid = &Apache::loncommon::get_cgi_id();
11240:                 if ($newkey =~ /^\d+:/) { 
11241:                     $newkey =~ s/^(\d+)/$newid/;
11242:                     $translation{$1} = $newid;
11243:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11244:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11245:                     $translation{$1} = $newid;
11246:                 }
11247:                 $new_values{$file_name."\0".$newkey} = 
11248:                                           $$changes{'activate'}{$newitems[$i]};
11249:                 $new_control{$newkey} = $now;
11250:             }
11251:         }
11252:     }
11253:     my %todelete;
11254:     my %changed_items;
11255:     foreach my $action ('delete','update') {
11256:         if (exists($$changes{$action})) {
11257:             if (ref($$changes{$action}) eq 'HASH') {
11258:                 foreach my $key (keys(%{$$changes{$action}})) {
11259:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11260:                     if ($action eq 'delete') { 
11261:                         $todelete{$itemnum} = 1;
11262:                     } else {
11263:                         $changed_items{$itemnum} = $key;
11264:                     }
11265:                 }
11266:             }
11267:         }
11268:     }
11269:     # get lock on access controls for file.
11270:     my $lockhash = {
11271:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11272:                                                        ':'.$env{'user.domain'},
11273:                    }; 
11274:     my $tries = 0;
11275:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11276:    
11277:     while (($gotlock ne 'ok') && $tries < 10) {
11278:         $tries ++;
11279:         sleep(0.1);
11280:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11281:     }
11282:     if ($gotlock eq 'ok') {
11283:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11284:         my ($tmp)=keys(%curr_permissions);
11285:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11286:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11287:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11288:             if (ref($curr_controls) eq 'HASH') {
11289:                 foreach my $control_item (keys(%{$curr_controls})) {
11290:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11291:                     if (defined($todelete{$itemnum})) {
11292:                         push(@deletions,$file_name."\0".$control_item);
11293:                     } else {
11294:                         if (defined($changed_items{$itemnum})) {
11295:                             $new_control{$changed_items{$itemnum}} = $now;
11296:                             push(@deletions,$file_name."\0".$control_item);
11297:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11298:                         } else {
11299:                             $new_control{$control_item} = $$curr_controls{$control_item};
11300:                         }
11301:                     }
11302:                 }
11303:             }
11304:         }
11305:         my ($group);
11306:         if (&is_course($domain,$user)) {
11307:             ($group,my $file) = split(/\//,$file_name,2);
11308:         }
11309:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11310:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11311:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11312:         #  remove lock
11313:         my @del_lock = ($file_name."\0".'locked_access_records');
11314:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11315:         my $sqlresult =
11316:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11317:                                     $group);
11318:     } else {
11319:         $outcome = "error: could not obtain lockfile\n";  
11320:     }
11321:     return ($outcome,$deloutcome,\%new_values,\%translation);
11322: }
11323: 
11324: sub make_public_indefinitely {
11325:     my (@requrl) = @_;
11326:     return &automated_portfile_access('public',\@requrl);
11327: }
11328: 
11329: sub automated_portfile_access {
11330:     my ($accesstype,$addsref,$delsref,$info) = @_;
11331:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11332:         return 'invalid';
11333:     }
11334:     my %urls;
11335:     if (ref($addsref) eq 'ARRAY') {
11336:         foreach my $requrl (@{$addsref}) {
11337:             if (&is_portfolio_url($requrl)) {
11338:                 unless (exists($urls{$requrl})) {
11339:                     $urls{$requrl} = 'add';
11340:                 }
11341:             }
11342:         }
11343:     }
11344:     if (ref($delsref) eq 'ARRAY') {
11345:         foreach my $requrl (@{$delsref}) { 
11346:             if (&is_portfolio_url($requrl)) {
11347:                 unless (exists($urls{$requrl})) {
11348:                     $urls{$requrl} = 'delete'; 
11349:                 }
11350:             }
11351:         }
11352:     }
11353:     unless (keys(%urls)) {
11354:         return 'invalid';
11355:     }
11356:     my $ip;
11357:     if ($accesstype eq 'ip') {
11358:         if (ref($info) eq 'HASH') {
11359:             if ($info->{'ip'} ne '') {
11360:                 $ip = $info->{'ip'};
11361:             }
11362:         }
11363:         if ($ip eq '') {
11364:             return 'invalid';
11365:         }
11366:     }
11367:     my $errors;
11368:     my $now = time;
11369:     my %current_perms;
11370:     foreach my $requrl (sort(keys(%urls))) {
11371:         my $action;
11372:         if ($urls{$requrl} eq 'add') {
11373:             $action = 'activate';
11374:         } else {
11375:             $action = 'none';
11376:         }
11377:         my $aclnum = 0;
11378:         my (undef,$udom,$unum,$file_name,$group) =
11379:             &parse_portfolio_url($requrl);
11380:         unless (exists($current_perms{$unum.':'.$udom})) {
11381:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11382:         }
11383:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11384:                                                    $group,$file_name);
11385:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11386:             my ($num,$scope,$end,$start) = 
11387:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11388:             if ($scope eq $accesstype) {
11389:                 if (($start <= $now) && ($end == 0)) {
11390:                     if ($accesstype eq 'ip') {
11391:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11392:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11393:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11394:                                     if ($urls{$requrl} eq 'add') {
11395:                                         $action = 'none';
11396:                                         last;
11397:                                     } else {
11398:                                         $action = 'delete';
11399:                                         $aclnum = $num;
11400:                                         last;
11401:                                     }
11402:                                 }
11403:                             }
11404:                         }
11405:                     } elsif ($accesstype eq 'public') {
11406:                         if ($urls{$requrl} eq 'add') {
11407:                             $action = 'none';
11408:                             last;
11409:                         } else {
11410:                             $action = 'delete';
11411:                             $aclnum = $num;
11412:                             last;
11413:                         }
11414:                     }
11415:                 } elsif ($accesstype eq 'public') {
11416:                     $action = 'update';
11417:                     $aclnum = $num;
11418:                     last;
11419:                 }
11420:             }
11421:         }
11422:         if ($action eq 'none') {
11423:             next;
11424:         } else {
11425:             my %changes;
11426:             my $newend = 0;
11427:             my $newstart = $now;
11428:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11429:             $changes{$action}{$newkey} = {
11430:                 type => $accesstype,
11431:                 time => {
11432:                     start => $newstart,
11433:                     end   => $newend,
11434:                 },
11435:             };
11436:             if ($accesstype eq 'ip') {
11437:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11438:             }
11439:             my ($outcome,$deloutcome,$new_values,$translation) =
11440:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11441:             unless ($outcome eq 'ok') {
11442:                 $errors .= $outcome.' ';
11443:             }
11444:         }
11445:     }
11446:     if ($errors) {
11447:         $errors =~ s/\s$//;
11448:         return $errors;
11449:     } else {
11450:         return 'ok';
11451:     }
11452: }
11453: 
11454: #------------------------------------------------------Get Marked as Read Only
11455: 
11456: sub get_marked_as_readonly {
11457:     my ($domain,$user,$what,$group) = @_;
11458:     my $current_permissions = &get_portfile_permissions($domain,$user);
11459:     my @readonly_files;
11460:     my $cmp1=$what;
11461:     if (ref($what)) { $cmp1=join('',@{$what}) };
11462:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11463:         if (defined($group)) {
11464:             if ($file_name !~ m-^\Q$group\E/-) {
11465:                 next;
11466:             }
11467:         }
11468:         if (ref($value) eq "ARRAY"){
11469:             foreach my $stored_what (@{$value}) {
11470:                 my $cmp2=$stored_what;
11471:                 if (ref($stored_what) eq 'ARRAY') {
11472:                     $cmp2=join('',@{$stored_what});
11473:                 }
11474:                 if ($cmp1 eq $cmp2) {
11475:                     push(@readonly_files, $file_name);
11476:                     last;
11477:                 } elsif (!defined($what)) {
11478:                     push(@readonly_files, $file_name);
11479:                     last;
11480:                 }
11481:             }
11482:         }
11483:     }
11484:     return @readonly_files;
11485: }
11486: #-----------------------------------------------------------Get Marked as Read Only Hash
11487: 
11488: sub get_marked_as_readonly_hash {
11489:     my ($current_permissions,$group,$what) = @_;
11490:     my %readonly_files;
11491:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11492:         if (defined($group)) {
11493:             if ($file_name !~ m-^\Q$group\E/-) {
11494:                 next;
11495:             }
11496:         }
11497:         if (ref($value) eq "ARRAY"){
11498:             foreach my $stored_what (@{$value}) {
11499:                 if (ref($stored_what) eq 'ARRAY') {
11500:                     foreach my $lock_descriptor(@{$stored_what}) {
11501:                         if ($lock_descriptor eq 'graded') {
11502:                             $readonly_files{$file_name} = 'graded';
11503:                         } elsif ($lock_descriptor eq 'handback') {
11504:                             $readonly_files{$file_name} = 'handback';
11505:                         } else {
11506:                             if (!exists($readonly_files{$file_name})) {
11507:                                 $readonly_files{$file_name} = 'locked';
11508:                             }
11509:                         }
11510:                     }
11511:                 } 
11512:             }
11513:         } 
11514:     }
11515:     return %readonly_files;
11516: }
11517: # ------------------------------------------------------------ Unmark as Read Only
11518: 
11519: sub unmark_as_readonly {
11520:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11521:     # for portfolio submissions, $what contains [$symb,$crsid] 
11522:     my ($domain,$user,$what,$file_name,$group) = @_;
11523:     $file_name = &declutter_portfile($file_name);
11524:     my $symb_crs = $what;
11525:     if (ref($what)) { $symb_crs=join('',@$what); }
11526:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11527:     my ($tmp)=keys(%current_permissions);
11528:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11529:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11530:     foreach my $file (@readonly_files) {
11531: 	my $clean_file = &declutter_portfile($file);
11532: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11533: 	my $current_locks = $current_permissions{$file};
11534:         my @new_locks;
11535:         my @del_keys;
11536:         if (ref($current_locks) eq "ARRAY"){
11537:             foreach my $locker (@{$current_locks}) {
11538:                 my $compare=$locker;
11539:                 if (ref($locker) eq 'ARRAY') {
11540:                     $compare=join('',@{$locker});
11541:                     if ($compare ne $symb_crs) {
11542:                         push(@new_locks, $locker);
11543:                     }
11544:                 }
11545:             }
11546:             if (scalar(@new_locks) > 0) {
11547:                 $current_permissions{$file} = \@new_locks;
11548:             } else {
11549:                 push(@del_keys, $file);
11550:                 &del('file_permissions',\@del_keys, $domain, $user);
11551:                 delete($current_permissions{$file});
11552:             }
11553:         }
11554:     }
11555:     &put('file_permissions',\%current_permissions,$domain,$user);
11556:     return;
11557: }
11558: 
11559: # ------------------------------------------------------------ Directory lister
11560: 
11561: sub dirlist {
11562:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11563:     $uri=~s/^\///;
11564:     $uri=~s/\/$//;
11565:     my ($udom, $uname);
11566:     if ($getuserdir) {
11567:         $udom = $userdomain;
11568:         $uname = $username;
11569:     } else {
11570:         (undef,$udom,$uname)=split(/\//,$uri);
11571:         if(defined($userdomain)) {
11572:             $udom = $userdomain;
11573:         }
11574:         if(defined($username)) {
11575:             $uname = $username;
11576:         }
11577:     }
11578:     my ($dirRoot,$listing,@listing_results);
11579: 
11580:     $dirRoot = $perlvar{'lonDocRoot'};
11581:     if (defined($getpropath)) {
11582:         $dirRoot = &propath($udom,$uname);
11583:         $dirRoot =~ s/\/$//;
11584:     } elsif (defined($getuserdir)) {
11585:         my $subdir=$uname.'__';
11586:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11587:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11588:                    ."/$udom/$subdir/$uname";
11589:     } elsif (defined($alternateRoot)) {
11590:         $dirRoot = $alternateRoot;
11591:     }
11592: 
11593:     if($udom) {
11594:         if($uname) {
11595:             my $uhome = &homeserver($uname,$udom);
11596:             if ($uhome eq 'no_host') {
11597:                 return ([],'no_host');
11598:             }
11599:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11600:                               .$getuserdir.':'.&escape($dirRoot)
11601:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11602:             if ($listing eq 'unknown_cmd') {
11603:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11604:             } else {
11605:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11606:             }
11607:             if ($listing eq 'unknown_cmd') {
11608:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11609:                 @listing_results = split(/:/,$listing);
11610:             } else {
11611:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11612:             }
11613:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11614:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11615:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11616:                 return ([],$listing);
11617:             } else {
11618:                 return (\@listing_results);
11619:             }
11620:         } elsif(!$alternateRoot) {
11621:             my (%allusers,%listerror);
11622: 	    my %servers = &get_servers($udom,'library');
11623:  	    foreach my $tryserver (keys(%servers)) {
11624:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11625:                                   &escape($udom),$tryserver);
11626:                 if ($listing eq 'unknown_cmd') {
11627: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11628: 				      $udom, $tryserver);
11629:                 } else {
11630:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11631:                 }
11632: 		if ($listing eq 'unknown_cmd') {
11633: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11634: 				      $udom, $tryserver);
11635: 		    @listing_results = split(/:/,$listing);
11636: 		} else {
11637: 		    @listing_results =
11638: 			map { &unescape($_); } split(/:/,$listing);
11639: 		}
11640:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11641:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11642:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11643:                     $listerror{$tryserver} = $listing;
11644:                 } else {
11645: 		    foreach my $line (@listing_results) {
11646: 			my ($entry) = split(/&/,$line,2);
11647: 			$allusers{$entry} = 1;
11648: 		    }
11649: 		}
11650:             }
11651:             my @alluserslist=();
11652:             foreach my $user (sort(keys(%allusers))) {
11653:                 push(@alluserslist,$user.'&user');
11654:             }
11655: 
11656:             if (!%listerror) {
11657:                 # no errors
11658:                 return (\@alluserslist);
11659:             } elsif (scalar(keys(%servers)) == 1) {
11660:                 # one library server, one error 
11661:                 my ($key) = keys(%listerror);
11662:                 return (\@alluserslist, $listerror{$key});
11663:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11664:                 # con_lost indicates that we might miss data from at least one
11665:                 # library server
11666:                 return (\@alluserslist, 'con_lost');
11667:             } else {
11668:                 # multiple library servers and no con_lost -> data should be
11669:                 # complete. 
11670:                 return (\@alluserslist);
11671:             }
11672: 
11673:         } else {
11674:             return ([],'missing username');
11675:         }
11676:     } elsif(!defined($getpropath)) {
11677:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11678:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11679:         return (\@all_domains);
11680:     } else {
11681:         return ([],'missing domain');
11682:     }
11683: }
11684: 
11685: # --------------------------------------------- GetFileTimestamp
11686: # This function utilizes dirlist and returns the date stamp for
11687: # when it was last modified.  It will also return an error of -1
11688: # if an error occurs
11689: 
11690: sub GetFileTimestamp {
11691:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11692:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11693:     $studentName   = &LONCAPA::clean_username($studentName);
11694:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11695:                                     undef,$getuserdir);
11696:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11697:         return -1;
11698:     }
11699:     if (ref($fileref) eq 'ARRAY') {
11700:         my @stats = split('&',$fileref->[0]);
11701:         # @stats contains first the filename, then the stat output
11702:         return $stats[10]; # so this is 10 instead of 9.
11703:     } else {
11704:         return -1;
11705:     }
11706: }
11707: 
11708: sub stat_file {
11709:     my ($uri) = @_;
11710:     $uri = &clutter_with_no_wrapper($uri);
11711: 
11712:     my ($udom,$uname,$file);
11713:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11714: 	($udom,$uname,$file) =
11715: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11716: 	$file = 'userfiles/'.$file;
11717:     }
11718:     if ($uri =~ m-^/res/-) {
11719: 	($udom,$uname) = 
11720: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11721: 	$file = $uri;
11722:     }
11723: 
11724:     if (!$udom || !$uname || !$file) {
11725: 	# unable to handle the uri
11726: 	return ();
11727:     }
11728:     my $getpropath;
11729:     if ($file =~ /^userfiles\//) {
11730:         $getpropath = 1;
11731:     }
11732:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11733:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11734:         return ();
11735:     } else {
11736:         if (ref($listref) eq 'ARRAY') {
11737:             my @stats = split('&',$listref->[0]);
11738: 	    shift(@stats); #filename is first
11739: 	    return @stats;
11740:         }
11741:     }
11742:     return ();
11743: }
11744: 
11745: # --------------------------------------------------------- recursedirs
11746: # Recursive function to traverse either a specific user's Authoring Space
11747: # or corresponding Published Resource Space, and populate the hash ref:
11748: # $dirhashref with URLs of all directories, and if $filehashref hash
11749: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11750: # or .rights files in resource space, and .meta, .save, .log, and .bak
11751: # files in Authoring Space.
11752: #
11753: # Inputs:
11754: #
11755: # $is_home - true if current server is home server for user's space
11756: # $context - either: priv, or res respectively for Authoring or Resource Space.
11757: # $docroot - Document root (i.e., /home/httpd/html
11758: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11759: # $relpath - Current path (relative to top level).
11760: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11761: # $filehashref - reference to hash to populate with URLs of files (Optional)
11762: #
11763: # Returns: nothing
11764: #
11765: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11766: #
11767: # Currently used by interface/londocs.pm to create linked select boxes for
11768: # directory and filename to import a Course "Author" resource into a course, and
11769: # also to create linked select boxes for Authoring Space and Directory to choose
11770: # save location for creation of a new "standard" problem from the Course Editor.
11771: #
11772: 
11773: sub recursedirs {
11774:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11775:     return unless (ref($dirhashref) eq 'HASH');
11776:     my $currpath = $docroot.$toppath;
11777:     if ($relpath) {
11778:         $currpath .= "/$relpath";
11779:     }
11780:     my $savefile;
11781:     if (ref($filehashref)) {
11782:         $savefile = 1;
11783:     }
11784:     if ($is_home) {
11785:         if (opendir(my $dirh,$currpath)) {
11786:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11787:                 next if ($item eq '');
11788:                 if (-d "$currpath/$item") {
11789:                     my $newpath;
11790:                     if ($relpath) {
11791:                         $newpath = "$relpath/$item";
11792:                     } else {
11793:                         $newpath = $item;
11794:                     }
11795:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11796:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11797:                 } elsif ($savefile) {
11798:                     if ($context eq 'priv') {
11799:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11800:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11801:                         }
11802:                     } else {
11803:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11804:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11805:                         }
11806:                     }
11807:                 }
11808:             }
11809:             closedir($dirh);
11810:         }
11811:     } else {
11812:         my ($dirlistref,$listerror) =
11813:             &dirlist($toppath.$relpath);
11814:         my @dir_lines;
11815:         my $dirptr=16384;
11816:         if (ref($dirlistref) eq 'ARRAY') {
11817:             foreach my $dir_line (sort
11818:                               {
11819:                                   my ($afile)=split('&',$a,2);
11820:                                   my ($bfile)=split('&',$b,2);
11821:                                   return (lc($afile) cmp lc($bfile));
11822:                               } (@{$dirlistref})) {
11823:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11824:                     split(/\&/,$dir_line,16);
11825:                 $item =~ s/\s+$//;
11826:                 next if (($item =~ /^\.\.?$/) || ($obs));
11827:                 if ($dirptr&$testdir) {
11828:                     my $newpath;
11829:                     if ($relpath) {
11830:                         $newpath = "$relpath/$item";
11831:                     } else {
11832:                         $relpath = '/';
11833:                         $newpath = $item;
11834:                     }
11835:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11836:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11837:                 } elsif ($savefile) {
11838:                     if ($context eq 'priv') {
11839:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11840:                             $filehashref->{$relpath}{$item} = 1;
11841:                         }
11842:                     } else {
11843:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11844:                             $filehashref->{$relpath}{$item} = 1;
11845:                         }
11846:                     }
11847:                 }
11848:             }
11849:         }
11850:     }
11851:     return;
11852: }
11853: 
11854: # -------------------------------------------------------- Value of a Condition
11855: 
11856: # gets the value of a specific preevaluated condition
11857: #    stored in the string  $env{user.state.<cid>}
11858: # or looks up a condition reference in the bighash and if if hasn't
11859: # already been evaluated recurses into docondval to get the value of
11860: # the condition, then memoizing it to 
11861: #   $env{user.state.<cid>.<condition>}
11862: sub directcondval {
11863:     my $number=shift;
11864:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11865: 	&Apache::lonuserstate::evalstate();
11866:     }
11867:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11868: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11869:     } elsif ($number =~ /^_/) {
11870: 	my $sub_condition;
11871: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11872: 		&GDBM_READER(),0640)) {
11873: 	    $sub_condition=$bighash{'conditions'.$number};
11874: 	    untie(%bighash);
11875: 	}
11876: 	my $value = &docondval($sub_condition);
11877: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11878: 	return $value;
11879:     }
11880:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11881:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11882:     } else {
11883:        return 2;
11884:     }
11885: }
11886: 
11887: # get the collection of conditions for this resource
11888: sub condval {
11889:     my $condidx=shift;
11890:     my $allpathcond='';
11891:     foreach my $cond (split(/\|/,$condidx)) {
11892: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11893: 	    $allpathcond.=
11894: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11895: 	}
11896:     }
11897:     $allpathcond=~s/\|$//;
11898:     return &docondval($allpathcond);
11899: }
11900: 
11901: #evaluates an expression of conditions
11902: sub docondval {
11903:     my ($allpathcond) = @_;
11904:     my $result=0;
11905:     if ($env{'request.course.id'}
11906: 	&& defined($allpathcond)) {
11907: 	my $operand='|';
11908: 	my @stack;
11909: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11910: 	    if ($chunk eq '(') {
11911: 		push @stack,($operand,$result);
11912: 	    } elsif ($chunk eq ')') {
11913: 		my $before=pop @stack;
11914: 		if (pop @stack eq '&') {
11915: 		    $result=$result>$before?$before:$result;
11916: 		} else {
11917: 		    $result=$result>$before?$result:$before;
11918: 		}
11919: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11920: 		$operand=$chunk;
11921: 	    } else {
11922: 		my $new=directcondval($chunk);
11923: 		if ($operand eq '&') {
11924: 		    $result=$result>$new?$new:$result;
11925: 		} else {
11926: 		    $result=$result>$new?$result:$new;
11927: 		}
11928: 	    }
11929: 	}
11930:     }
11931:     return $result;
11932: }
11933: 
11934: # ---------------------------------------------------- Devalidate courseresdata
11935: 
11936: sub devalidatecourseresdata {
11937:     my ($coursenum,$coursedomain)=@_;
11938:     my $hashid=$coursenum.':'.$coursedomain;
11939:     &devalidate_cache_new('courseres',$hashid);
11940: }
11941: 
11942: 
11943: # --------------------------------------------------- Course Resourcedata Query
11944: #
11945: #  Parameters:
11946: #      $coursenum    - Number of the course.
11947: #      $coursedomain - Domain at which the course was created.
11948: #  Returns:
11949: #     A hash of the course parameters along (I think) with timestamps
11950: #     and version info.
11951: 
11952: sub get_courseresdata {
11953:     my ($coursenum,$coursedomain)=@_;
11954:     my $coursehom=&homeserver($coursenum,$coursedomain);
11955:     my $hashid=$coursenum.':'.$coursedomain;
11956:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11957:     my %dumpreply;
11958:     unless (defined($cached)) {
11959: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11960: 	$result=\%dumpreply;
11961: 	my ($tmp) = keys(%dumpreply);
11962: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11963: 	    &do_cache_new('courseres',$hashid,$result,600);
11964: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11965: 	    return $tmp;
11966: 	} elsif ($tmp =~ /^(error)/) {
11967: 	    $result=undef;
11968: 	    &do_cache_new('courseres',$hashid,$result,600);
11969: 	}
11970:     }
11971:     return $result;
11972: }
11973: 
11974: sub devalidateuserresdata {
11975:     my ($uname,$udom)=@_;
11976:     my $hashid="$udom:$uname";
11977:     &devalidate_cache_new('userres',$hashid);
11978: }
11979: 
11980: sub get_userresdata {
11981:     my ($uname,$udom)=@_;
11982:     #most student don\'t have any data set, check if there is some data
11983:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11984: 
11985:     my $hashid="$udom:$uname";
11986:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11987:     if (!defined($cached)) {
11988: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11989: 	$result=\%resourcedata;
11990: 	&do_cache_new('userres',$hashid,$result,600);
11991:     }
11992:     my ($tmp)=keys(%$result);
11993:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11994: 	return $result;
11995:     }
11996:     #error 2 occurs when the .db doesn't exist
11997:     if ($tmp!~/error: 2 /) {
11998:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11999: 	    &logthis("<font color=\"blue\">WARNING:".
12000: 		     " Trying to get resource data for ".
12001: 		     $uname." at ".$udom.": ".
12002: 		     $tmp."</font>");
12003:         }
12004:     } elsif ($tmp=~/error: 2 /) {
12005: 	#&EXT_cache_set($udom,$uname);
12006: 	&do_cache_new('userres',$hashid,undef,600);
12007: 	undef($tmp); # not really an error so don't send it back
12008:     }
12009:     return $tmp;
12010: }
12011: #----------------------------------------------- resdata - return resource data
12012: #  Purpose:
12013: #    Return resource data for either users or for a course.
12014: #  Parameters:
12015: #     $name      - Course/user name.
12016: #     $domain    - Name of the domain the user/course is registered on.
12017: #     $type      - Type of thing $name is (must be 'course' or 'user')
12018: #     $mapp      - decluttered URL of enclosing map  
12019: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12020: #     $recurseup - Ref to array of map URLs, starting with map containing
12021: #                  $mapp up through hierarchy of nested maps to top level map.  
12022: #     $courseid  - CourseID (first part of param identifier).
12023: #     $modifier  - Middle part of param identifier.
12024: #     $what      - Last part of param identifier.
12025: #     @which     - Array of names of resources desired.
12026: #  Returns:
12027: #     The value of the first reasource in @which that is found in the
12028: #     resource hash.
12029: #  Exceptional Conditions:
12030: #     If the $type passed in is not valid (not the string 'course' or 
12031: #     'user', an undefined  reference is returned.
12032: #     If none of the resources are found, an undef is returned
12033: sub resdata {
12034:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12035:         $modifier,$what,@which)=@_;
12036:     my $result;
12037:     if ($type eq 'course') {
12038: 	$result=&get_courseresdata($name,$domain);
12039:     } elsif ($type eq 'user') {
12040: 	$result=&get_userresdata($name,$domain);
12041:     }
12042:     if (!ref($result)) { return $result; }    
12043:     foreach my $item (@which) {
12044:         if ($item->[1] eq 'course') {
12045:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12046:                 unless ($$recursed) {
12047:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12048:                     $$recursed = 1;
12049:                 }
12050:                 foreach my $item (@${recurseup}) {
12051:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12052:                     last if (defined($result->{$norecursechk}));
12053:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12054:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12055:                 }
12056:             }
12057:         }
12058:         if (defined($result->{$item->[0]})) {
12059: 	    return [$result->{$item->[0]},$item->[1]];
12060: 	}
12061:     }
12062:     return undef;
12063: }
12064: 
12065: sub get_domain_lti {
12066:     my ($cdom,$context) = @_;
12067:     my ($name,%lti);
12068:     if ($context eq 'consumer') {
12069:         $name = 'ltitools';
12070:     } elsif ($context eq 'provider') {
12071:         $name = 'lti';
12072:     } else {
12073:         return %lti;
12074:     }
12075:     my ($result,$cached)=&is_cached_new($name,$cdom);
12076:     if (defined($cached)) {
12077:         if (ref($result) eq 'HASH') {
12078:             %lti = %{$result};
12079:         }
12080:     } else {
12081:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12082:         if (ref($domconfig{$name}) eq 'HASH') {
12083:             %lti = %{$domconfig{$name}};
12084:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
12085:             if (ref($encdomconfig{$name}) eq 'HASH') {
12086:                 foreach my $id (keys(%lti)) {
12087:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12088:                         foreach my $item ('key','secret') {
12089:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12090:                         }
12091:                     }
12092:                 }
12093:             }
12094:         }
12095:         my $cachetime = 24*60*60;
12096:         &do_cache_new($name,$cdom,\%lti,$cachetime);
12097:     }
12098:     return %lti;
12099: }
12100: 
12101: sub get_numsuppfiles {
12102:     my ($cnum,$cdom,$ignorecache)=@_;
12103:     my $hashid=$cnum.':'.$cdom;
12104:     my ($suppcount,$cached);
12105:     unless ($ignorecache) {
12106:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12107:     }
12108:     unless (defined($cached)) {
12109:         my $chome=&homeserver($cnum,$cdom);
12110:         unless ($chome eq 'no_host') {
12111:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12112:             my $suppmap = 'supplemental.sequence';
12113:             ($suppcount,$supptools,$errors) =
12114:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12115:                                                          $supptools,$errors);
12116:         }
12117:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12118:     }
12119:     return $suppcount;
12120: }
12121: 
12122: #
12123: # EXT resource caching routines
12124: #
12125: 
12126: {
12127: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12128: #
12129: # The course for which we cache
12130: my $cachedmapkey='';
12131: # The cached recursive maps for this course
12132: my %cachedmaps=();
12133: # When this was last done
12134: my $cachedmaptime='';
12135: 
12136: sub clear_EXT_cache_status {
12137:     &delenv('cache.EXT.');
12138: }
12139: 
12140: sub EXT_cache_status {
12141:     my ($target_domain,$target_user) = @_;
12142:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12143:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12144:         # We know already the user has no data
12145:         return 1;
12146:     } else {
12147:         return 0;
12148:     }
12149: }
12150: 
12151: sub EXT_cache_set {
12152:     my ($target_domain,$target_user) = @_;
12153:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12154:     #&appenv({$cachename => time});
12155: }
12156: 
12157: # --------------------------------------------------------- Value of a Variable
12158: sub EXT {
12159: 
12160:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
12161:     unless ($varname) { return ''; }
12162:     #get real user name/domain, courseid and symb
12163:     my $courseid;
12164:     my $publicuser;
12165:     if ($symbparm) {
12166: 	$symbparm=&get_symb_from_alias($symbparm);
12167:     }
12168:     if (!($uname && $udom)) {
12169:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12170:       if (!$symbparm) {	$symbparm=$cursymb; }
12171:     } else {
12172: 	$courseid=$env{'request.course.id'};
12173:     }
12174:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12175:     my $rest;
12176:     if (defined($therest[0])) {
12177:        $rest=join('.',@therest);
12178:     } else {
12179:        $rest='';
12180:     }
12181: 
12182:     my $qualifierrest=$qualifier;
12183:     if ($rest) { $qualifierrest.='.'.$rest; }
12184:     my $spacequalifierrest=$space;
12185:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12186:     if ($realm eq 'user') {
12187: # --------------------------------------------------------------- user.resource
12188: 	if ($space eq 'resource') {
12189: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12190: 		  || defined($Apache::lonhomework::parsing_a_task))
12191: 		 &&
12192: 		 ($symbparm eq &symbread()) ) {	
12193: 		# if we are in the middle of processing the resource the
12194: 		# get the value we are planning on committing
12195:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12196:                     return $Apache::lonhomework::results{$qualifierrest};
12197:                 } else {
12198:                     return $Apache::lonhomework::history{$qualifierrest};
12199:                 }
12200: 	    } else {
12201: 		my %restored;
12202: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12203: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12204: 		} else {
12205: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12206: 		}
12207: 		return $restored{$qualifierrest};
12208: 	    }
12209: # ----------------------------------------------------------------- user.access
12210:         } elsif ($space eq 'access') {
12211: 	    # FIXME - not supporting calls for a specific user
12212:             return &allowed($qualifier,$rest);
12213: # ------------------------------------------ user.preferences, user.environment
12214:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12215: 	    if (($uname eq $env{'user.name'}) &&
12216: 		($udom eq $env{'user.domain'})) {
12217: 		return $env{join('.',('environment',$qualifierrest))};
12218: 	    } else {
12219: 		my %returnhash;
12220: 		if (!$publicuser) {
12221: 		    %returnhash=&userenvironment($udom,$uname,
12222: 						 $qualifierrest);
12223: 		}
12224: 		return $returnhash{$qualifierrest};
12225: 	    }
12226: # ----------------------------------------------------------------- user.course
12227:         } elsif ($space eq 'course') {
12228: 	    # FIXME - not supporting calls for a specific user
12229:             return $env{join('.',('request.course',$qualifier))};
12230: # ------------------------------------------------------------------- user.role
12231:         } elsif ($space eq 'role') {
12232: 	    # FIXME - not supporting calls for a specific user
12233:             my ($role,$where)=split(/\./,$env{'request.role'});
12234:             if ($qualifier eq 'value') {
12235: 		return $role;
12236:             } elsif ($qualifier eq 'extent') {
12237:                 return $where;
12238:             }
12239: # ----------------------------------------------------------------- user.domain
12240:         } elsif ($space eq 'domain') {
12241:             return $udom;
12242: # ------------------------------------------------------------------- user.name
12243:         } elsif ($space eq 'name') {
12244:             return $uname;
12245: # ---------------------------------------------------- Any other user namespace
12246:         } else {
12247: 	    my %reply;
12248: 	    if (!$publicuser) {
12249: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12250: 	    }
12251: 	    return $reply{$qualifierrest};
12252:         }
12253:     } elsif ($realm eq 'query') {
12254: # ---------------------------------------------- pull stuff out of query string
12255:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12256: 						[$spacequalifierrest]);
12257: 	return $env{'form.'.$spacequalifierrest}; 
12258:    } elsif ($realm eq 'request') {
12259: # ------------------------------------------------------------- request.browser
12260:         if ($space eq 'browser') {
12261:             return $env{'browser.'.$qualifier};
12262: # ------------------------------------------------------------ request.filename
12263:         } else {
12264:             return $env{'request.'.$spacequalifierrest};
12265:         }
12266:     } elsif ($realm eq 'course') {
12267: # ---------------------------------------------------------- course.description
12268:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12269:     } elsif ($realm eq 'resource') {
12270: 
12271: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12272: 	    if (!$symbparm) { $symbparm=&symbread(); }
12273: 	}
12274: 
12275:         if ($qualifier eq '') {
12276: 	    if ($space eq 'title') {
12277: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12278: 	        return &gettitle($symbparm);
12279: 	    }
12280: 	
12281: 	    if ($space eq 'map') {
12282: 	        my ($map) = &decode_symb($symbparm);
12283: 	        return &symbread($map);
12284: 	    }
12285:             if ($space eq 'maptitle') {
12286:                 my ($map) = &decode_symb($symbparm);
12287:                 return &gettitle($map);
12288:             }
12289: 	    if ($space eq 'filename') {
12290: 	        if ($symbparm) {
12291: 		    return &clutter((&decode_symb($symbparm))[2]);
12292: 	        }
12293: 	        return &hreflocation('',$env{'request.filename'});
12294: 	    }
12295: 
12296:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12297:                 if ($space eq 'visibleparts') {
12298:                     my $navmap = Apache::lonnavmaps::navmap->new();
12299:                     my $item;
12300:                     if (ref($navmap)) {
12301:                         my $res = $navmap->getBySymb($symbparm);
12302:                         my $parts = $res->parts();
12303:                         if (ref($parts) eq 'ARRAY') {
12304:                             $item = join(',',@{$parts});
12305:                         }
12306:                         undef($navmap);
12307:                     }
12308:                     return $item;
12309:                 }
12310:             }
12311:         }
12312: 
12313: 	my ($section, $group, @groups, @recurseup, $recursed);
12314: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12315:         if (($courseid eq '') && ($cid)) {
12316:             $courseid = $cid;
12317:         }
12318: 	if (($symbparm && $courseid) && 
12319: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12320: 
12321: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12322: 
12323: # ----------------------------------------------------- Cascading lookup scheme
12324: 	    my $symbp=$symbparm;
12325: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12326: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12327:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12328: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12329: 	    if (($env{'user.name'} eq $uname) &&
12330: 		($env{'user.domain'} eq $udom)) {
12331: 		$section=$env{'request.course.sec'};
12332:                 @groups = split(/:/,$env{'request.course.groups'});  
12333:                 @groups=&sort_course_groups($courseid,@groups); 
12334: 	    } else {
12335: 		if (! defined($usection)) {
12336: 		    $section=&getsection($udom,$uname,$courseid);
12337: 		} else {
12338: 		    $section = $usection;
12339: 		}
12340:                 @groups = &get_users_groups($udom,$uname,$courseid);
12341: 	    }
12342: 
12343: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12344: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12345:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12346: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12347: 
12348: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12349: 	    my $courselevelr=$courseid.'.'.$symbparm;
12350:             $courseleveli=$courseid.'.'.$recurseparm;
12351: 	    $courselevelm=$courseid.'.'.$mapparm;
12352: 
12353: # ----------------------------------------------------------- first, check user
12354: 
12355: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12356:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12357: 				       ([$courselevelr,'resource'],
12358: 					[$courselevelm,'map'     ],
12359:                                         [$courseleveli,'map'     ],
12360: 					[$courselevel, 'course'  ]));
12361: 	    if (defined($userreply)) { return &get_reply($userreply); }
12362: 
12363: # ------------------------------------------------ second, check some of course
12364:             my $coursereply;
12365:             if (@groups > 0) {
12366:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12367:                                        $recurseparm,$mapparm,$spacequalifierrest,
12368:                                        $mapp,\$recursed,\@recurseup);
12369:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12370:             }
12371: 
12372: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12373: 				  $env{'course.'.$courseid.'.domain'},
12374: 				  'course',$mapp,\$recursed,\@recurseup,
12375:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12376: 				  ([$seclevelr,   'resource'],
12377: 				   [$seclevelm,   'map'     ],
12378:                                    [$secleveli,   'map'     ],
12379: 				   [$seclevel,    'course'  ],
12380: 				   [$courselevelr,'resource']));
12381: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12382: 
12383: # ------------------------------------------------------ third, check map parms
12384: 	    my %parmhash=();
12385: 	    my $thisparm='';
12386: 	    if (tie(%parmhash,'GDBM_File',
12387: 		    $env{'request.course.fn'}.'_parms.db',
12388: 		    &GDBM_READER(),0640)) {
12389: 		$thisparm=$parmhash{$symbparm};
12390: 		untie(%parmhash);
12391: 	    }
12392: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12393: 	}
12394: # ------------------------------------------ fourth, look in resource metadata
12395:  
12396:         my $what = $spacequalifierrest;
12397: 	$what=~s/\./\_/;
12398: 	my $filename;
12399: 	if (!$symbparm) { $symbparm=&symbread(); }
12400: 	if ($symbparm) {
12401: 	    $filename=(&decode_symb($symbparm))[2];
12402: 	} else {
12403: 	    $filename=$env{'request.filename'};
12404: 	}
12405:         my $toolsymb;
12406:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12407:             $toolsymb = $symbparm;
12408:         }
12409: 	my $metadata=&metadata($filename,$what,$toolsymb);
12410: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12411: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12412: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12413: 
12414: # ----------------------------------------------- fifth, look in rest of course
12415: 	if ($symbparm && defined($courseid) && 
12416: 	    $courseid eq $env{'request.course.id'}) {
12417: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12418: 				     $env{'course.'.$courseid.'.domain'},
12419: 				     'course',$mapp,\$recursed,\@recurseup,
12420:                                      $courseid,'.',$spacequalifierrest,
12421: 				     ([$courselevelm,'map'   ],
12422:                                       [$courseleveli,'map'   ],
12423: 				      [$courselevel, 'course']));
12424: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12425: 	}
12426: # ------------------------------------------------------------------ Cascade up
12427: 	unless ($space eq '0') {
12428: 	    my @parts=split(/_/,$space);
12429: 	    my $id=pop(@parts);
12430: 	    my $part=join('_',@parts);
12431: 	    if ($part eq '') { $part='0'; }
12432: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12433: 				 $symbparm,$udom,$uname,$section,1);
12434: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12435: 	}
12436: 	if ($recurse) { return undef; }
12437: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12438: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12439: # ---------------------------------------------------- Any other user namespace
12440:     } elsif ($realm eq 'environment') {
12441: # ----------------------------------------------------------------- environment
12442: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12443: 	    return $env{'environment.'.$spacequalifierrest};
12444: 	} else {
12445: 	    if ($uname eq 'anonymous' && $udom eq '') {
12446: 		return '';
12447: 	    }
12448: 	    my %returnhash=&userenvironment($udom,$uname,
12449: 					    $spacequalifierrest);
12450: 	    return $returnhash{$spacequalifierrest};
12451: 	}
12452:     } elsif ($realm eq 'system') {
12453: # ----------------------------------------------------------------- system.time
12454: 	if ($space eq 'time') {
12455: 	    return time;
12456:         }
12457:     } elsif ($realm eq 'server') {
12458: # ----------------------------------------------------------------- system.time
12459: 	if ($space eq 'name') {
12460: 	    return $ENV{'SERVER_NAME'};
12461:         }
12462:     } elsif ($realm eq 'client') {
12463:         if ($space eq 'remote_addr') {
12464:             return &get_requestor_ip();
12465:         }
12466:     }
12467:     return '';
12468: }
12469: 
12470: sub get_reply {
12471:     my ($reply_value) = @_;
12472:     if (ref($reply_value) eq 'ARRAY') {
12473:         if (wantarray) {
12474: 	    return @$reply_value;
12475:         }
12476:         return $reply_value->[0];
12477:     } else {
12478:         return $reply_value;
12479:     }
12480: }
12481: 
12482: sub check_group_parms {
12483:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12484:         $recursed,$recurseupref) = @_;
12485:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12486:                   [$what,'course']);
12487:     my $coursereply;
12488:     foreach my $group (@{$groups}) {
12489:         my @groupitems = ();
12490:         foreach my $level (@levels) {
12491:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12492:              push(@groupitems,[$item,$level->[1]]);
12493:         }
12494:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12495:                                    $env{'course.'.$courseid.'.domain'},
12496:                                    'course',$mapp,$recursed,$recurseupref,
12497:                                    $courseid,'.['.$group.'].',$what,
12498:                                    @groupitems);
12499:         last if (defined($coursereply));
12500:     }
12501:     return $coursereply;
12502: }
12503: 
12504: sub get_map_hierarchy {
12505:     my ($mapname,$courseid) = @_;
12506:     my @recurseup = ();
12507:     if ($mapname) {
12508:         if (($cachedmapkey eq $courseid) &&
12509:             (abs($cachedmaptime-time)<5)) {
12510:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12511:                 return @{$cachedmaps{$mapname}};
12512:             }
12513:         }
12514:         my $navmap = Apache::lonnavmaps::navmap->new();
12515:         if (ref($navmap)) {
12516:             @recurseup = $navmap->recurseup_maps($mapname);
12517:             undef($navmap);
12518:             $cachedmaps{$mapname} = \@recurseup;
12519:             $cachedmaptime=time;
12520:             $cachedmapkey=$courseid;
12521:         }
12522:     }
12523:     return @recurseup;
12524: }
12525: 
12526: }
12527: 
12528: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12529:     my ($courseid,@groups) = @_;
12530:     @groups = sort(@groups);
12531:     return @groups;
12532: }
12533: 
12534: sub packages_tab_default {
12535:     my ($uri,$varname,$toolsymb)=@_;
12536:     my (undef,$part,$name)=split(/\./,$varname);
12537: 
12538:     my (@extension,@specifics,$do_default);
12539:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12540: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12541: 	if ($pack_type eq 'default') {
12542: 	    $do_default=1;
12543: 	} elsif ($pack_type eq 'extension') {
12544: 	    push(@extension,[$package,$pack_type,$pack_part]);
12545: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12546: 	    # only look at packages defaults for packages that this id is
12547: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12548: 	}
12549:     }
12550:     # first look for a package that matches the requested part id
12551:     foreach my $package (@specifics) {
12552: 	my (undef,$pack_type,$pack_part)=@{$package};
12553: 	next if ($pack_part ne $part);
12554: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12555: 	    return $packagetab{"$pack_type&$name&default"};
12556: 	}
12557:     }
12558:     # look for any possible matching non extension_ package
12559:     foreach my $package (@specifics) {
12560: 	my (undef,$pack_type,$pack_part)=@{$package};
12561: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12562: 	    return $packagetab{"$pack_type&$name&default"};
12563: 	}
12564: 	if ($pack_type eq 'part') { $pack_part='0'; }
12565: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12566: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12567: 	}
12568:     }
12569:     # look for any posible extension_ match
12570:     foreach my $package (@extension) {
12571: 	my ($package,$pack_type)=@{$package};
12572: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12573: 	    return $packagetab{"$pack_type&$name&default"};
12574: 	}
12575: 	if (defined($packagetab{$package."&$name&default"})) {
12576: 	    return $packagetab{$package."&$name&default"};
12577: 	}
12578:     }
12579:     # look for a global default setting
12580:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12581: 	return $packagetab{"default&$name&default"};
12582:     }
12583:     return undef;
12584: }
12585: 
12586: sub add_prefix_and_part {
12587:     my ($prefix,$part)=@_;
12588:     my $keyroot;
12589:     if (defined($prefix) && $prefix !~ /^__/) {
12590: 	# prefix that has a part already
12591: 	$keyroot=$prefix;
12592:     } elsif (defined($prefix)) {
12593: 	# prefix that is missing a part
12594: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12595:     } else {
12596: 	# no prefix at all
12597: 	if (defined($part)) { $keyroot='_'.$part; }
12598:     }
12599:     return $keyroot;
12600: }
12601: 
12602: # ---------------------------------------------------------------- Get metadata
12603: 
12604: my %metaentry;
12605: my %importedpartids;
12606: my %importedrespids;
12607: sub metadata {
12608:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12609:     $uri=&declutter($uri);
12610:     # if it is a non metadata possible uri return quickly
12611:     if (($uri eq '') || 
12612: 	(($uri =~ m|^/*adm/|) && 
12613: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12614:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12615: 	return undef;
12616:     }
12617:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12618: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12619: 	return undef;
12620:     }
12621:     my $filename=$uri;
12622:     $uri=~s/\.meta$//;
12623: #
12624: # Is the metadata already cached?
12625: # Look at timestamp of caching
12626: # Everything is cached by the main uri, libraries are never directly cached
12627: #
12628:     if (!defined($liburi)) {
12629: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12630: 	if (defined($cached)) { return $result->{':'.$what}; }
12631:     }
12632: 
12633: #
12634: # If the uri is for an external tool the file from
12635: # which metadata should be retrieved depends on whether
12636: # the tool had been configured to be gradable (set in the Course
12637: # Editor or Resource Editor).
12638: #
12639: # If a valid symb has been included as the third arg in the call
12640: # to &metadata() that can be used to retrieve the value of
12641: # parameter_0_gradable set for the resource, and included in the
12642: # uploaded map containing the tool. The value is retrieved via
12643: # &EXT(), if a valid symb is available.  Otherwise the value of
12644: # gradable in the exttool_$marker.db file for the tool instance
12645: # is retrieved via &get().
12646: #
12647: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12648: # hiddenresource and encrypturl (during course initialization)
12649: # the map-level parameter for resource.0.gradable included in the 
12650: # uploaded map containing the tool will not yet have been stored
12651: # in the user_course_parms.db file for the user's session, so in 
12652: # this case fall back to retrieving gradable status from the
12653: # exttool_$marker.db file.
12654: #
12655: # In order to avoid an infinite loop, &metadata() will return
12656: # before a call to &EXT(), if the uri is for an external tool
12657: # and the $what for which metadata is being requested is
12658: # parameter_0_gradable or 0_gradable.
12659: #
12660: 
12661:     if ($uri =~ /ext\.tool$/) {
12662:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12663:             return;
12664:         } else {
12665:             my ($checked,$use_passback);
12666:             if ($toolsymb ne '') {
12667:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12668:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12669:                     $checked = 1;
12670:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12671:                         $use_passback = 1;
12672:                     }
12673:                 }
12674:             }
12675:             unless ($checked) {
12676:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12677:                 $marker=~s/\D//g;
12678:                 if ($marker) {
12679:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12680:                     $use_passback = $toolsettings{'gradable'};
12681:                 }
12682:             }
12683:             if ($use_passback) {
12684:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12685:             } else {
12686:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12687:             }
12688:         }
12689:     }
12690: 
12691:     {
12692: # Imported parts would go here
12693:         my @origfiletagids=();
12694:         my $importedparts=0;
12695: 
12696: # Imported responseids would go here
12697:         my $importedresponses=0;
12698: #
12699: # Is this a recursive call for a library?
12700: #
12701: #	if (! exists($metacache{$uri})) {
12702: #	    $metacache{$uri}={};
12703: #	}
12704: 	my $cachetime = 60*60;
12705:         if ($liburi) {
12706: 	    $liburi=&declutter($liburi);
12707:             $filename=$liburi;
12708:         } else {
12709: 	    &devalidate_cache_new('meta',$uri);
12710: 	    undef(%metaentry);
12711: 	}
12712:         my %metathesekeys=();
12713:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12714: 	my $metastring;
12715: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12716: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12717: 	    $metastring = 
12718: 		&Apache::lonnet::ssi_body($which,
12719: 					  ('grade_target' => 'meta'));
12720: 	    $cachetime = 1; # only want this cached in the child not long term
12721: 	} elsif (($uri !~ m -^(editupload)/-) && 
12722:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12723: 	    my $file=&filelocation('',&clutter($filename));
12724: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12725: 	    $metastring=&getfile($file);
12726: 	}
12727:         my $parser=HTML::LCParser->new(\$metastring);
12728:         my $token;
12729:         undef %metathesekeys;
12730:         while ($token=$parser->get_token) {
12731: 	    if ($token->[0] eq 'S') {
12732: 		if (defined($token->[2]->{'package'})) {
12733: #
12734: # This is a package - get package info
12735: #
12736: 		    my $package=$token->[2]->{'package'};
12737: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12738: 		    if (defined($token->[2]->{'id'})) { 
12739: 			$keyroot.='_'.$token->[2]->{'id'}; 
12740: 		    }
12741: 		    if ($metaentry{':packages'}) {
12742: 			$metaentry{':packages'}.=','.$package.$keyroot;
12743: 		    } else {
12744: 			$metaentry{':packages'}=$package.$keyroot;
12745: 		    }
12746: 		    foreach my $pack_entry (keys(%packagetab)) {
12747: 			my $part=$keyroot;
12748: 			$part=~s/^\_//;
12749: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12750: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12751: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12752: 			    # ignore package.tab specified default values
12753:                             # here &package_tab_default() will fetch those
12754: 			    if ($subp eq 'default') { next; }
12755: 			    my $value=$packagetab{$pack_entry};
12756: 			    my $unikey;
12757: 			    if ($pack =~ /_0$/) {
12758: 				$unikey='parameter_0_'.$name;
12759: 				$part=0;
12760: 			    } else {
12761: 				$unikey='parameter'.$keyroot.'_'.$name;
12762: 			    }
12763: 			    if ($subp eq 'display') {
12764: 				$value.=' [Part: '.$part.']';
12765: 			    }
12766: 			    $metaentry{':'.$unikey.'.part'}=$part;
12767: 			    $metathesekeys{$unikey}=1;
12768: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12769: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12770: 			    }
12771: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12772: 				$metaentry{':'.$unikey}=
12773: 				    $metaentry{':'.$unikey.'.default'};
12774: 			    }
12775: 			}
12776: 		    }
12777: 		} else {
12778: #
12779: # This is not a package - some other kind of start tag
12780: #
12781: 		    my $entry=$token->[1];
12782: 		    my $unikey='';
12783: 
12784: 		    if ($entry eq 'import') {
12785: #
12786: # Importing a library here
12787: #
12788:                         my $location=$parser->get_text('/import');
12789:                         my $dir=$filename;
12790:                         $dir=~s|[^/]*$||;
12791:                         $location=&filelocation($dir,$location);
12792: 
12793:                         my $importid=$token->[2]->{'id'};
12794:                         my $importmode=$token->[2]->{'importmode'};
12795: #
12796: # Check metadata for imported file to
12797: # see if it contained response items
12798: #
12799:                         my ($origfile,@libfilekeys);
12800:                         my %currmetaentry = %metaentry;
12801:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12802:                                                            $depthcount+1));
12803:                         if (grep(/^responseorder$/,@libfilekeys)) {
12804:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12805:                                                              undef,$depthcount+1);
12806:                             if ($libresponseorder ne '') {
12807:                                 if ($#origfiletagids<0) {
12808:                                     undef(%importedrespids);
12809:                                     undef(%importedpartids);
12810:                                 }
12811:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12812:                                 if (@respids) {
12813:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12814:                                 }
12815:                                 if ($importedrespids{$importid} ne '') {
12816:                                     $importedresponses = 1;
12817: # We need to get the original file and the imported file to get the response order correct
12818: # Load and inspect original file
12819:                                     if ($#origfiletagids<0) {
12820:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12821:                                         $origfile=&getfile($origfilelocation);
12822:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12823:                                     }
12824:                                 }
12825:                             }
12826:                         }
12827: # Do not overwrite contents of %metaentry hash for resource itself with 
12828: # hash populated for imported library file
12829:                         %metaentry = %currmetaentry;
12830:                         undef(%currmetaentry);
12831:                         if ($importmode eq 'part') {
12832: # Import as part(s)
12833:                            $importedparts=1;
12834: # We need to get the original file and the imported file to get the part order correct
12835: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12836: # Load and inspect original file if we didn't do that already
12837:                            if ($#origfiletagids<0) {
12838:                                undef(%importedrespids);
12839:                                undef(%importedpartids);
12840:                                if ($origfile eq '') {
12841:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12842:                                    $origfile=&getfile($origfilelocation);
12843:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12844:                                }
12845:                            }
12846:                            my @impfilepartids;
12847: # If <partorder> tag is included in metadata for the imported file
12848: # get the parts in the imported file from that.
12849:                            if (grep(/^partorder$/,@libfilekeys)) {
12850:                                %currmetaentry = %metaentry;
12851:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12852:                                                             $depthcount+1);
12853:                                %metaentry = %currmetaentry;
12854:                                undef(%currmetaentry);
12855:                                if ($libpartorder ne '') {
12856:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12857:                                }
12858:                            } else {
12859: # If no <partorder> tag available, load and inspect imported file
12860:                                my $impfile=&getfile($location);
12861:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12862:                            }
12863:                            if ($#impfilepartids>=0) {
12864: # This problem had parts
12865:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12866:                            } else {
12867: # Importing by turning a single problem into a problem part
12868: # It gets the import-tags ID as part-ID
12869:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12870:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12871:                            }
12872:                         } else {
12873: # Import as problem or as normal import
12874:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12875:                             unless ($importmode eq 'problem') {
12876: # Normal import
12877:                                 if (defined($token->[2]->{'id'})) {
12878:                                     $unikey.='_'.$token->[2]->{'id'};
12879:                                 }
12880:                             }
12881: # Check metadata for imported file to
12882: # see if it contained parts
12883:                             if (grep(/^partorder$/,@libfilekeys)) {
12884:                                 %currmetaentry = %metaentry;
12885:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12886:                                                              $depthcount+1);
12887:                                 %metaentry = %currmetaentry;
12888:                                 undef(%currmetaentry);
12889:                                 if ($libpartorder ne '') {
12890:                                     $importedparts = 1;
12891:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12892:                                 }
12893:                             }
12894:                         }
12895: 			if ($depthcount<20) {
12896: 			    my $metadata = 
12897: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12898: 					  $depthcount+1);
12899: 			    foreach my $meta (split(',',$metadata)) {
12900: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12901: 				$metathesekeys{$meta}=1;
12902: 			    }
12903:                         }
12904: 		    } else {
12905: #
12906: # Not importing, some other kind of non-package, non-library start tag
12907: # 
12908:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12909:                         if (defined($token->[2]->{'id'})) {
12910:                             $unikey.='_'.$token->[2]->{'id'};
12911:                         }
12912: 			if (defined($token->[2]->{'name'})) { 
12913: 			    $unikey.='_'.$token->[2]->{'name'}; 
12914: 			}
12915: 			$metathesekeys{$unikey}=1;
12916: 			foreach my $param (@{$token->[3]}) {
12917: 			    $metaentry{':'.$unikey.'.'.$param} =
12918: 				$token->[2]->{$param};
12919: 			}
12920: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12921: 			my $default=$metaentry{':'.$unikey.'.default'};
12922: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12923: 		 # only ws inside the tag, and not in default, so use default
12924: 		 # as value
12925: 			    $metaentry{':'.$unikey}=$default;
12926: 			} elsif ( $internaltext =~ /\S/ ) {
12927: 		  # something interesting inside the tag
12928: 			    $metaentry{':'.$unikey}=$internaltext;
12929: 			} else {
12930: 		  # no interesting values, don't set a default
12931: 			}
12932: # end of not-a-package not-a-library import
12933: 		    }
12934: # end of not-a-package start tag
12935: 		}
12936: # the next is the end of "start tag"
12937: 	    }
12938: 	}
12939: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12940: 	$extension = lc($extension);
12941: 	if ($extension eq 'htm') { $extension='html'; }
12942: 
12943: 	foreach my $key (keys(%packagetab)) {
12944: 	    #no specific packages #how's our extension
12945: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12946: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12947: 					 \%metathesekeys);
12948: 	}
12949: 
12950: 	if (!exists($metaentry{':packages'})
12951: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12952: 	    foreach my $key (keys(%packagetab)) {
12953: 		#no specific packages well let's get default then
12954: 		if ($key!~/^default&/) { next; }
12955: 		&metadata_create_package_def($uri,$key,'default',
12956: 					     \%metathesekeys);
12957: 	    }
12958: 	}
12959: # are there custom rights to evaluate
12960: 	if ($metaentry{':copyright'} eq 'custom') {
12961: 
12962:     #
12963:     # Importing a rights file here
12964:     #
12965: 	    unless ($depthcount) {
12966: 		my $location=$metaentry{':customdistributionfile'};
12967: 		my $dir=$filename;
12968: 		$dir=~s|[^/]*$||;
12969: 		$location=&filelocation($dir,$location);
12970: 		my $rights_metadata =
12971: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12972: 			      $depthcount+1);
12973: 		foreach my $rights (split(',',$rights_metadata)) {
12974: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12975: 		    $metathesekeys{$rights}=1;
12976: 		}
12977: 	    }
12978: 	}
12979: 	# uniqifiy package listing
12980: 	my %seen;
12981: 	my @uniq_packages =
12982: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12983: 	$metaentry{':packages'} = join(',',@uniq_packages);
12984: 
12985:         if (($importedresponses) || ($importedparts)) {
12986:             if ($importedparts) {
12987: # We had imported parts and need to rebuild partorder
12988:                 $metaentry{':partorder'}='';
12989:                 $metathesekeys{'partorder'}=1;
12990:             }
12991:             if ($importedresponses) {
12992: # We had imported responses and need to rebuil responseorder
12993:                 $metaentry{':responseorder'}='';
12994:                 $metathesekeys{'responseorder'}=1;
12995:             }
12996:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12997:                 my $origid = $origfiletagids[$index+1];
12998:                 if ($origfiletagids[$index] eq 'part') {
12999: # Original part, part of the problem
13000:                     if ($importedparts) {
13001:                         $metaentry{':partorder'}.=','.$origid;
13002:                     }
13003:                 } elsif ($origfiletagids[$index] eq 'import') {
13004:                     if ($importedparts) {
13005: # We have imported parts at this position
13006:                         if ($importedpartids{$origid} ne '') {
13007:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13008:                         }
13009:                     }
13010:                     if ($importedresponses) {
13011: # We have imported responses at this position
13012:                         if ($importedrespids{$origid} ne '') {
13013:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13014:                         }
13015:                     }
13016:                 } else {
13017: # Original response item, part of the problem
13018:                     if ($importedresponses) {
13019:                         $metaentry{':responseorder'}.=','.$origid;
13020:                     }
13021:                 }
13022:             }
13023:             if ($importedparts) {
13024:                 $metaentry{':partorder'}=~s/^\,//;
13025:             }
13026:             if ($importedresponses) {
13027:                 $metaentry{':responseorder'}=~s/^\,//;
13028:             }
13029:         }
13030: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13031: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13032: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13033:         unless ($liburi) {
13034: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13035:         }
13036: # this is the end of "was not already recently cached
13037:     }
13038:     return $metaentry{':'.$what};
13039: }
13040: 
13041: sub metadata_create_package_def {
13042:     my ($uri,$key,$package,$metathesekeys)=@_;
13043:     my ($pack,$name,$subp)=split(/\&/,$key);
13044:     if ($subp eq 'default') { next; }
13045:     
13046:     if (defined($metaentry{':packages'})) {
13047: 	$metaentry{':packages'}.=','.$package;
13048:     } else {
13049: 	$metaentry{':packages'}=$package;
13050:     }
13051:     my $value=$packagetab{$key};
13052:     my $unikey;
13053:     $unikey='parameter_0_'.$name;
13054:     $metaentry{':'.$unikey.'.part'}=0;
13055:     $$metathesekeys{$unikey}=1;
13056:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13057: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13058:     }
13059:     if (defined($metaentry{':'.$unikey.'.default'})) {
13060: 	$metaentry{':'.$unikey}=
13061: 	    $metaentry{':'.$unikey.'.default'};
13062:     }
13063: }
13064: 
13065: sub metadata_generate_part0 {
13066:     my ($metadata,$metacache,$uri) = @_;
13067:     my %allnames;
13068:     foreach my $metakey (keys(%$metadata)) {
13069: 	if ($metakey=~/^parameter\_(.*)/) {
13070: 	  my $part=$$metacache{':'.$metakey.'.part'};
13071: 	  my $name=$$metacache{':'.$metakey.'.name'};
13072: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13073: 	    $allnames{$name}=$part;
13074: 	  }
13075: 	}
13076:     }
13077:     foreach my $name (keys(%allnames)) {
13078:       $$metadata{"parameter_0_$name"}=1;
13079:       my $key=":parameter_0_$name";
13080:       $$metacache{"$key.part"}='0';
13081:       $$metacache{"$key.name"}=$name;
13082:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13083: 					   $allnames{$name}.'_'.$name.
13084: 					   '.type'};
13085:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13086: 			     '.display'};
13087:       my $expr='[Part: '.$allnames{$name}.']';
13088:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13089:       $$metacache{"$key.display"}=$olddis;
13090:     }
13091: }
13092: 
13093: # ------------------------------------------------------ Devalidate title cache
13094: 
13095: sub devalidate_title_cache {
13096:     my ($url)=@_;
13097:     if (!$env{'request.course.id'}) { return; }
13098:     my $symb=&symbread($url);
13099:     if (!$symb) { return; }
13100:     my $key=$env{'request.course.id'}."\0".$symb;
13101:     &devalidate_cache_new('title',$key);
13102: }
13103: 
13104: # ------------------------------------------------- Get the title of a course
13105: 
13106: sub current_course_title {
13107:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13108: }
13109: # ------------------------------------------------- Get the title of a resource
13110: 
13111: sub gettitle {
13112:     my $urlsymb=shift;
13113:     my $symb=&symbread($urlsymb);
13114:     if ($symb) {
13115: 	my $key=$env{'request.course.id'}."\0".$symb;
13116: 	my ($result,$cached)=&is_cached_new('title',$key);
13117: 	if (defined($cached)) { 
13118: 	    return $result;
13119: 	}
13120: 	my ($map,$resid,$url)=&decode_symb($symb);
13121: 	my $title='';
13122: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13123: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13124: 	} else {
13125: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13126: 		    &GDBM_READER(),0640)) {
13127: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13128: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13129: 		untie(%bighash);
13130: 	    }
13131: 	}
13132: 	$title=~s/\&colon\;/\:/gs;
13133: 	if ($title) {
13134: # Remember both $symb and $title for dynamic metadata
13135:             $accesshash{$symb.'___crstitle'}=$title;
13136:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13137: # Cache this title and then return it
13138: 	    return &do_cache_new('title',$key,$title,600);
13139: 	}
13140: 	$urlsymb=$url;
13141:     }
13142:     my $title=&metadata($urlsymb,'title');
13143:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13144:     return $title;
13145: }
13146: 
13147: sub get_slot {
13148:     my ($which,$cnum,$cdom)=@_;
13149:     if (!$cnum || !$cdom) {
13150: 	(undef,my $courseid)=&whichuser();
13151: 	$cdom=$env{'course.'.$courseid.'.domain'};
13152: 	$cnum=$env{'course.'.$courseid.'.num'};
13153:     }
13154:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13155:     my %slotinfo;
13156:     if (exists($remembered{$key})) {
13157: 	$slotinfo{$which} = $remembered{$key};
13158:     } else {
13159: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13160: 	&Apache::lonhomework::showhash(%slotinfo);
13161: 	my ($tmp)=keys(%slotinfo);
13162: 	if ($tmp=~/^error:/) { return (); }
13163: 	$remembered{$key} = $slotinfo{$which};
13164:     }
13165:     if (ref($slotinfo{$which}) eq 'HASH') {
13166: 	return %{$slotinfo{$which}};
13167:     }
13168:     return $slotinfo{$which};
13169: }
13170: 
13171: sub get_reservable_slots {
13172:     my ($cnum,$cdom,$uname,$udom) = @_;
13173:     my $now = time;
13174:     my $reservable_info;
13175:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13176:     if (exists($remembered{$key})) {
13177:         $reservable_info = $remembered{$key};
13178:     } else {
13179:         my %resv;
13180:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13181:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13182:         $reservable_info = \%resv;
13183:         $remembered{$key} = $reservable_info;
13184:     }
13185:     return $reservable_info;
13186: }
13187: 
13188: sub get_course_slots {
13189:     my ($cnum,$cdom) = @_;
13190:     my $hashid=$cnum.':'.$cdom;
13191:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13192:     if (defined($cached)) {
13193:         if (ref($result) eq 'HASH') {
13194:             return %{$result};
13195:         }
13196:     } else {
13197:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13198:         my ($tmp) = keys(%slots);
13199:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13200:             &do_cache_new('allslots',$hashid,\%slots,600);
13201:             return %slots;
13202:         }
13203:     }
13204:     return;
13205: }
13206: 
13207: sub devalidate_slots_cache {
13208:     my ($cnum,$cdom)=@_;
13209:     my $hashid=$cnum.':'.$cdom;
13210:     &devalidate_cache_new('allslots',$hashid);
13211: }
13212: 
13213: sub get_coursechange {
13214:     my ($cdom,$cnum) = @_;
13215:     if ($cdom eq '' || $cnum eq '') {
13216:         return unless ($env{'request.course.id'});
13217:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13218:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13219:     }
13220:     my $hashid=$cdom.'_'.$cnum;
13221:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13222:     if ((defined($cached)) && ($change ne '')) {
13223:         return $change;
13224:     } else {
13225:         my %crshash;
13226:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13227:         if ($crshash{'internal.contentchange'} eq '') {
13228:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13229:             if ($change eq '') {
13230:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13231:                 $change = $crshash{'internal.created'};
13232:             }
13233:         } else {
13234:             $change = $crshash{'internal.contentchange'};
13235:         }
13236:         my $cachetime = 600;
13237:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13238:     }
13239:     return $change;
13240: }
13241: 
13242: sub devalidate_coursechange_cache {
13243:     my ($cnum,$cdom)=@_;
13244:     my $hashid=$cnum.':'.$cdom;
13245:     &devalidate_cache_new('crschange',$hashid);
13246: }
13247: 
13248: # ------------------------------------------------- Update symbolic store links
13249: 
13250: sub symblist {
13251:     my ($mapname,%newhash)=@_;
13252:     $mapname=&deversion(&declutter($mapname));
13253:     my %hash;
13254:     if (($env{'request.course.fn'}) && (%newhash)) {
13255:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13256:                       &GDBM_WRCREAT(),0640)) {
13257: 	    foreach my $url (keys(%newhash)) {
13258: 		next if ($url eq 'last_known'
13259: 			 && $env{'form.no_update_last_known'});
13260: 		$hash{declutter($url)}=&encode_symb($mapname,
13261: 						    $newhash{$url}->[1],
13262: 						    $newhash{$url}->[0]);
13263:             }
13264:             if (untie(%hash)) {
13265: 		return 'ok';
13266:             }
13267:         }
13268:     }
13269:     return 'error';
13270: }
13271: 
13272: # --------------------------------------------------------------- Verify a symb
13273: 
13274: sub symbverify {
13275:     my ($symb,$thisurl,$encstate)=@_;
13276:     my $thisfn=$thisurl;
13277:     $thisfn=&declutter($thisfn);
13278: # direct jump to resource in page or to a sequence - will construct own symbs
13279:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13280: # check URL part
13281:     my ($map,$resid,$url)=&decode_symb($symb);
13282: 
13283:     unless ($url eq $thisfn) { return 0; }
13284: 
13285:     $symb=&symbclean($symb);
13286:     $thisurl=&deversion($thisurl);
13287:     $thisfn=&deversion($thisfn);
13288: 
13289:     my %bighash;
13290:     my $okay=0;
13291: 
13292:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13293:                             &GDBM_READER(),0640)) {
13294:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13295:             $thisurl =~ s/\?.+$//;
13296:             if ($map =~ m{^uploaded/.+\.page$}) {
13297:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13298:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13299:             }
13300:         }
13301:         my $ids;
13302:         if ($map =~ m{^uploaded/.+\.page$}) {
13303:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13304:         } else {
13305:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13306:         }
13307:         unless ($ids) {
13308:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13309:             $ids=$bighash{$idkey};
13310:         }
13311:         if ($ids) {
13312: # ------------------------------------------------------------------- Has ID(s)
13313:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13314:                 $symb =~ s/\?.+$//;
13315:             }
13316: 	    foreach my $id (split(/\,/,$ids)) {
13317: 	       my ($mapid,$resid)=split(/\./,$id);
13318:                if (
13319:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13320:    eq $symb) {
13321:                    if (ref($encstate)) {
13322:                        $$encstate = $bighash{'encrypted_'.$id};
13323:                    }
13324: 		   if (($env{'request.role.adv'}) ||
13325: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13326:                        ($thisurl eq '/adm/navmaps')) {
13327: 		       $okay=1;
13328:                        last;
13329: 		   }
13330: 	       }
13331: 	   }
13332:         }
13333: 	untie(%bighash);
13334:     }
13335:     return $okay;
13336: }
13337: 
13338: # --------------------------------------------------------------- Clean-up symb
13339: 
13340: sub symbclean {
13341:     my $symb=shift;
13342:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13343: # remove version from map
13344:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13345: 
13346: # remove version from URL
13347:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13348: 
13349: # remove wrapper
13350: 
13351:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13352:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13353:     return $symb;
13354: }
13355: 
13356: # ---------------------------------------------- Split symb to find map and url
13357: 
13358: sub encode_symb {
13359:     my ($map,$resid,$url)=@_;
13360:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13361: }
13362: 
13363: sub decode_symb {
13364:     my $symb=shift;
13365:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13366:     my ($map,$resid,$url)=split(/___/,$symb);
13367:     return (&fixversion($map),$resid,&fixversion($url));
13368: }
13369: 
13370: sub fixversion {
13371:     my $fn=shift;
13372:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13373:     my %bighash;
13374:     my $uri=&clutter($fn);
13375:     my $key=$env{'request.course.id'}.'_'.$uri;
13376: # is this cached?
13377:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13378:     if (defined($cached)) { return $result; }
13379: # unfortunately not cached, or expired
13380:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13381: 	    &GDBM_READER(),0640)) {
13382:  	if ($bighash{'version_'.$uri}) {
13383:  	    my $version=$bighash{'version_'.$uri};
13384:  	    unless (($version eq 'mostrecent') || 
13385: 		    ($version==&getversion($uri))) {
13386:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13387:  	    }
13388:  	}
13389:  	untie %bighash;
13390:     }
13391:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13392: }
13393: 
13394: sub deversion {
13395:     my $url=shift;
13396:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13397:     return $url;
13398: }
13399: 
13400: # ------------------------------------------------------ Return symb list entry
13401: 
13402: sub symbread {
13403:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13404:         $ignoresymbdb,$noenccheck)=@_;
13405:     my $cache_str='request.symbread.cached.'.$thisfn;
13406:     if (defined($env{$cache_str})) {
13407:         unless (ref($possibles) eq 'HASH') {
13408:             if ($ignorecachednull) {
13409:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13410:             } else {
13411:                 return $env{$cache_str};
13412:             }
13413:         }
13414:     }
13415: # no filename provided? try from environment
13416:     unless ($thisfn) {
13417:         if ($env{'request.symb'}) {
13418:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13419: 	}
13420: 	$thisfn=$env{'request.filename'};
13421:     }
13422:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13423: # is that filename actually a symb? Verify, clean, and return
13424:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13425: 	if (&symbverify($thisfn,$1)) {
13426: 	    return $env{$cache_str}=&symbclean($thisfn);
13427: 	}
13428:     }
13429:     $thisfn=declutter($thisfn);
13430:     my %hash;
13431:     my %bighash;
13432:     my $syval='';
13433:     if (($env{'request.course.fn'}) && ($thisfn)) {
13434:         my $targetfn = $thisfn;
13435:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13436:             $targetfn = 'adm/wrapper/'.$thisfn;
13437:         }
13438: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13439: 	    $targetfn=$1;
13440: 	}
13441:         unless ($ignoresymbdb) {
13442:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13443:                           &GDBM_READER(),0640)) {
13444: 	        $syval=$hash{$targetfn};
13445:                 untie(%hash);
13446:             }
13447:             if ($syval && $checkforblock) {
13448:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13449:                 if (@blockers) {
13450:                     $syval='';
13451:                 }
13452:             }
13453:         }
13454: # ---------------------------------------------------------- There was an entry
13455:         if ($syval) {
13456: 	    #unless ($syval=~/\_\d+$/) {
13457: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13458: 		    #&appenv({'request.ambiguous' => $thisfn});
13459: 		    #return $env{$cache_str}='';
13460: 		#}    
13461: 		#$syval.=$1;
13462: 	    #}
13463:         } else {
13464: # ------------------------------------------------------- Was not in symb table
13465:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13466:                             &GDBM_READER(),0640)) {
13467: # ---------------------------------------------- Get ID(s) for current resource
13468:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13469:               unless ($ids) { 
13470:                  $ids=$bighash{'ids_/'.$thisfn};
13471:               }
13472:               unless ($ids) {
13473: # alias?
13474: 		  $ids=$bighash{'mapalias_'.$thisfn};
13475:               }
13476:               if ($ids) {
13477: # ------------------------------------------------------------------- Has ID(s)
13478:                  my @possibilities=split(/\,/,$ids);
13479:                  if ($#possibilities==0) {
13480: # ----------------------------------------------- There is only one possibility
13481: 		     my ($mapid,$resid)=split(/\./,$ids);
13482: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13483: 						    $resid,$thisfn);
13484:                      if (ref($possibles) eq 'HASH') {
13485:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13486:                              $possibles->{$syval} = 1;
13487:                          }
13488:                      }
13489:                      if ($checkforblock) {
13490:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13491:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13492:                              if (@blockers) {
13493:                                  $syval = '';
13494:                                  untie(%bighash);
13495:                                  return $env{$cache_str}='';
13496:                              }
13497:                          }
13498:                      }
13499:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13500: # ------------------------------------------ There is more than one possibility
13501:                      my $realpossible=0;
13502:                      foreach my $id (@possibilities) {
13503: 			 my $file=$bighash{'src_'.$id};
13504:                          my $canaccess;
13505:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13506:                              $canaccess = 1;
13507:                          } else { 
13508:                              $canaccess = &allowed('bre',$file);
13509:                          }
13510:                          if ($canaccess) {
13511:          		     my ($mapid,$resid)=split(/\./,$id);
13512:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13513:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13514: 						             $resid,$thisfn);
13515:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13516:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13517:                                  if ($checkforblock) {
13518:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13519:                                      if (@blockers > 0) {
13520:                                          $syval = '';
13521:                                      } else {
13522:                                          $syval = $poss_syval;
13523:                                          $realpossible++;
13524:                                      }
13525:                                  } else {
13526:                                      $syval = $poss_syval;
13527:                                      $realpossible++;
13528:                                  }
13529:                                  if ($syval) {
13530:                                      if (ref($possibles) eq 'HASH') {
13531:                                          $possibles->{$syval} = 1;
13532:                                      }
13533:                                  }
13534:                              }
13535: 			 }
13536:                      }
13537: 		     if ($realpossible!=1) { $syval=''; }
13538:                  } else {
13539:                      $syval='';
13540:                  }
13541: 	      }
13542:               untie(%bighash);
13543:            }
13544:         }
13545:         if ($syval) {
13546: 	    return $env{$cache_str}=$syval;
13547:         }
13548:     }
13549:     &appenv({'request.ambiguous' => $thisfn});
13550:     return $env{$cache_str}='';
13551: }
13552: 
13553: # ---------------------------------------------------------- Return random seed
13554: 
13555: sub numval {
13556:     my $txt=shift;
13557:     $txt=~tr/A-J/0-9/;
13558:     $txt=~tr/a-j/0-9/;
13559:     $txt=~tr/K-T/0-9/;
13560:     $txt=~tr/k-t/0-9/;
13561:     $txt=~tr/U-Z/0-5/;
13562:     $txt=~tr/u-z/0-5/;
13563:     $txt=~s/\D//g;
13564:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13565:     return int($txt);
13566: }
13567: 
13568: sub numval2 {
13569:     my $txt=shift;
13570:     $txt=~tr/A-J/0-9/;
13571:     $txt=~tr/a-j/0-9/;
13572:     $txt=~tr/K-T/0-9/;
13573:     $txt=~tr/k-t/0-9/;
13574:     $txt=~tr/U-Z/0-5/;
13575:     $txt=~tr/u-z/0-5/;
13576:     $txt=~s/\D//g;
13577:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13578:     my $total;
13579:     foreach my $val (@txts) { $total+=$val; }
13580:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13581:     return int($total);
13582: }
13583: 
13584: sub numval3 {
13585:     use integer;
13586:     my $txt=shift;
13587:     $txt=~tr/A-J/0-9/;
13588:     $txt=~tr/a-j/0-9/;
13589:     $txt=~tr/K-T/0-9/;
13590:     $txt=~tr/k-t/0-9/;
13591:     $txt=~tr/U-Z/0-5/;
13592:     $txt=~tr/u-z/0-5/;
13593:     $txt=~s/\D//g;
13594:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13595:     my $total;
13596:     foreach my $val (@txts) { $total+=$val; }
13597:     if ($_64bit) { $total=(($total<<32)>>32); }
13598:     return $total;
13599: }
13600: 
13601: sub digest {
13602:     my ($data)=@_;
13603:     my $digest=&Digest::MD5::md5($data);
13604:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13605:     my ($e,$f);
13606:     {
13607:         use integer;
13608:         $e=($a+$b);
13609:         $f=($c+$d);
13610:         if ($_64bit) {
13611:             $e=(($e<<32)>>32);
13612:             $f=(($f<<32)>>32);
13613:         }
13614:     }
13615:     if (wantarray) {
13616: 	return ($e,$f);
13617:     } else {
13618: 	my $g;
13619: 	{
13620: 	    use integer;
13621: 	    $g=($e+$f);
13622: 	    if ($_64bit) {
13623: 		$g=(($g<<32)>>32);
13624: 	    }
13625: 	}
13626: 	return $g;
13627:     }
13628: }
13629: 
13630: sub latest_rnd_algorithm_id {
13631:     return '64bit5';
13632: }
13633: 
13634: sub get_rand_alg {
13635:     my ($courseid)=@_;
13636:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13637:     if ($courseid) {
13638: 	return $env{"course.$courseid.rndseed"};
13639:     }
13640:     return &latest_rnd_algorithm_id();
13641: }
13642: 
13643: sub validCODE {
13644:     my ($CODE)=@_;
13645:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13646:     return 0;
13647: }
13648: 
13649: sub getCODE {
13650:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13651:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13652: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13653: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13654: 	return $Apache::lonhomework::history{'resource.CODE'};
13655:     }
13656:     return undef;
13657: }
13658: #
13659: #  Determines the random seed for a specific context:
13660: #
13661: # parameters:
13662: #   symb      - in course context the symb for the seed.
13663: #   course_id - The course id of the form domain_coursenum.
13664: #   domain    - Domain for the user.
13665: #   course    - Course for the user.
13666: #   cenv      - environment of the course.
13667: #
13668: # NOTE:
13669: #   All parameters are picked out of the environment if missing
13670: #   or not defined.
13671: #   If a symb cannot be determined the current time is used instead.
13672: #
13673: #  For a given well defined symb, courside, domain, username,
13674: #  and course environment, the seed is reproducible.
13675: #
13676: sub rndseed {
13677:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13678:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13679:     if (!defined($symb)) {
13680: 	unless ($symb=$wsymb) { return time; }
13681:     }
13682:     if (!defined $courseid) { 
13683: 	$courseid=$wcourseid; 
13684:     }
13685:     if (!defined $domain) { $domain=$wdomain; }
13686:     if (!defined $username) { $username=$wusername }
13687: 
13688:     my $which;
13689:     if (defined($cenv->{'rndseed'})) {
13690: 	$which = $cenv->{'rndseed'};
13691:     } else {
13692: 	$which =&get_rand_alg($courseid);
13693:     }
13694:     if (defined(&getCODE())) {
13695: 
13696: 	if ($which eq '64bit5') {
13697: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13698: 	} elsif ($which eq '64bit4') {
13699: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13700: 	} else {
13701: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13702: 	}
13703:     } elsif ($which eq '64bit5') {
13704: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13705:     } elsif ($which eq '64bit4') {
13706: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13707:     } elsif ($which eq '64bit3') {
13708: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13709:     } elsif ($which eq '64bit2') {
13710: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13711:     } elsif ($which eq '64bit') {
13712: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13713:     }
13714:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13715: }
13716: 
13717: sub rndseed_32bit {
13718:     my ($symb,$courseid,$domain,$username)=@_;
13719:     {
13720: 	use integer;
13721: 	my $symbchck=unpack("%32C*",$symb) << 27;
13722: 	my $symbseed=numval($symb) << 22;
13723: 	my $namechck=unpack("%32C*",$username) << 17;
13724: 	my $nameseed=numval($username) << 12;
13725: 	my $domainseed=unpack("%32C*",$domain) << 7;
13726: 	my $courseseed=unpack("%32C*",$courseid);
13727: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13728: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13729: 	#&logthis("rndseed :$num:$symb");
13730: 	if ($_64bit) { $num=(($num<<32)>>32); }
13731: 	return $num;
13732:     }
13733: }
13734: 
13735: sub rndseed_64bit {
13736:     my ($symb,$courseid,$domain,$username)=@_;
13737:     {
13738: 	use integer;
13739: 	my $symbchck=unpack("%32S*",$symb) << 21;
13740: 	my $symbseed=numval($symb) << 10;
13741: 	my $namechck=unpack("%32S*",$username);
13742: 	
13743: 	my $nameseed=numval($username) << 21;
13744: 	my $domainseed=unpack("%32S*",$domain) << 10;
13745: 	my $courseseed=unpack("%32S*",$courseid);
13746: 	
13747: 	my $num1=$symbchck+$symbseed+$namechck;
13748: 	my $num2=$nameseed+$domainseed+$courseseed;
13749: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13750: 	#&logthis("rndseed :$num:$symb");
13751: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13752: 	return "$num1,$num2";
13753:     }
13754: }
13755: 
13756: sub rndseed_64bit2 {
13757:     my ($symb,$courseid,$domain,$username)=@_;
13758:     {
13759: 	use integer;
13760: 	# strings need to be an even # of cahracters long, it it is odd the
13761:         # last characters gets thrown away
13762: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13763: 	my $symbseed=numval($symb) << 10;
13764: 	my $namechck=unpack("%32S*",$username.' ');
13765: 	
13766: 	my $nameseed=numval($username) << 21;
13767: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13768: 	my $courseseed=unpack("%32S*",$courseid.' ');
13769: 	
13770: 	my $num1=$symbchck+$symbseed+$namechck;
13771: 	my $num2=$nameseed+$domainseed+$courseseed;
13772: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13773: 	#&logthis("rndseed :$num:$symb");
13774: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13775: 	return "$num1,$num2";
13776:     }
13777: }
13778: 
13779: sub rndseed_64bit3 {
13780:     my ($symb,$courseid,$domain,$username)=@_;
13781:     {
13782: 	use integer;
13783: 	# strings need to be an even # of cahracters long, it it is odd the
13784:         # last characters gets thrown away
13785: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13786: 	my $symbseed=numval2($symb) << 10;
13787: 	my $namechck=unpack("%32S*",$username.' ');
13788: 	
13789: 	my $nameseed=numval2($username) << 21;
13790: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13791: 	my $courseseed=unpack("%32S*",$courseid.' ');
13792: 	
13793: 	my $num1=$symbchck+$symbseed+$namechck;
13794: 	my $num2=$nameseed+$domainseed+$courseseed;
13795: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13796: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13797: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13798: 	
13799: 	return "$num1:$num2";
13800:     }
13801: }
13802: 
13803: sub rndseed_64bit4 {
13804:     my ($symb,$courseid,$domain,$username)=@_;
13805:     {
13806: 	use integer;
13807: 	# strings need to be an even # of cahracters long, it it is odd the
13808:         # last characters gets thrown away
13809: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13810: 	my $symbseed=numval3($symb) << 10;
13811: 	my $namechck=unpack("%32S*",$username.' ');
13812: 	
13813: 	my $nameseed=numval3($username) << 21;
13814: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13815: 	my $courseseed=unpack("%32S*",$courseid.' ');
13816: 	
13817: 	my $num1=$symbchck+$symbseed+$namechck;
13818: 	my $num2=$nameseed+$domainseed+$courseseed;
13819: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13820: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13821: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13822: 	
13823: 	return "$num1:$num2";
13824:     }
13825: }
13826: 
13827: sub rndseed_64bit5 {
13828:     my ($symb,$courseid,$domain,$username)=@_;
13829:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13830:     return "$num1:$num2";
13831: }
13832: 
13833: sub rndseed_CODE_64bit {
13834:     my ($symb,$courseid,$domain,$username)=@_;
13835:     {
13836: 	use integer;
13837: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13838: 	my $symbseed=numval2($symb);
13839: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13840: 	my $CODEseed=numval(&getCODE());
13841: 	my $courseseed=unpack("%32S*",$courseid.' ');
13842: 	my $num1=$symbseed+$CODEchck;
13843: 	my $num2=$CODEseed+$courseseed+$symbchck;
13844: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13845: 	#&logthis("rndseed :$num1:$num2:$symb");
13846: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13847: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13848: 	return "$num1:$num2";
13849:     }
13850: }
13851: 
13852: sub rndseed_CODE_64bit4 {
13853:     my ($symb,$courseid,$domain,$username)=@_;
13854:     {
13855: 	use integer;
13856: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13857: 	my $symbseed=numval3($symb);
13858: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13859: 	my $CODEseed=numval3(&getCODE());
13860: 	my $courseseed=unpack("%32S*",$courseid.' ');
13861: 	my $num1=$symbseed+$CODEchck;
13862: 	my $num2=$CODEseed+$courseseed+$symbchck;
13863: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13864: 	#&logthis("rndseed :$num1:$num2:$symb");
13865: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13866: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13867: 	return "$num1:$num2";
13868:     }
13869: }
13870: 
13871: sub rndseed_CODE_64bit5 {
13872:     my ($symb,$courseid,$domain,$username)=@_;
13873:     my $code = &getCODE();
13874:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13875:     return "$num1:$num2";
13876: }
13877: 
13878: sub setup_random_from_rndseed {
13879:     my ($rndseed)=@_;
13880:     if ($rndseed =~/([,:])/) {
13881:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13882:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13883:             &Math::Random::random_set_seed_from_phrase($rndseed);
13884:         } else {
13885:             &Math::Random::random_set_seed($num1,$num2);
13886:         }
13887:     } else {
13888: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13889:     }
13890: }
13891: 
13892: sub latest_receipt_algorithm_id {
13893:     return 'receipt3';
13894: }
13895: 
13896: sub recunique {
13897:     my $fucourseid=shift;
13898:     my $unique;
13899:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13900: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13901: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13902:     } else {
13903: 	$unique=$perlvar{'lonReceipt'};
13904:     }
13905:     return unpack("%32C*",$unique);
13906: }
13907: 
13908: sub recprefix {
13909:     my $fucourseid=shift;
13910:     my $prefix;
13911:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13912: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13913: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13914:     } else {
13915: 	$prefix=$perlvar{'lonHostID'};
13916:     }
13917:     return unpack("%32C*",$prefix);
13918: }
13919: 
13920: sub ireceipt {
13921:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13922: 
13923:     my $return =&recprefix($fucourseid).'-';
13924: 
13925:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13926: 	$env{'request.state'} eq 'construct') {
13927: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13928: 	return $return;
13929:     }
13930: 
13931:     my $cuname=unpack("%32C*",$funame);
13932:     my $cudom=unpack("%32C*",$fudom);
13933:     my $cucourseid=unpack("%32C*",$fucourseid);
13934:     my $cusymb=unpack("%32C*",$fusymb);
13935:     my $cunique=&recunique($fucourseid);
13936:     my $cpart=unpack("%32S*",$part);
13937:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13938: 
13939: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13940: 			       
13941: 	$return.= ($cunique%$cuname+
13942: 		   $cunique%$cudom+
13943: 		   $cusymb%$cuname+
13944: 		   $cusymb%$cudom+
13945: 		   $cucourseid%$cuname+
13946: 		   $cucourseid%$cudom+
13947: 		   $cpart%$cuname+
13948: 		   $cpart%$cudom);
13949:     } else {
13950: 	$return.= ($cunique%$cuname+
13951: 		   $cunique%$cudom+
13952: 		   $cusymb%$cuname+
13953: 		   $cusymb%$cudom+
13954: 		   $cucourseid%$cuname+
13955: 		   $cucourseid%$cudom);
13956:     }
13957:     return $return;
13958: }
13959: 
13960: sub receipt {
13961:     my ($part)=@_;
13962:     my ($symb,$courseid,$domain,$name) = &whichuser();
13963:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13964: }
13965: 
13966: sub whichuser {
13967:     my ($passedsymb)=@_;
13968:     my ($symb,$courseid,$domain,$name,$publicuser);
13969:     if (defined($env{'form.grade_symb'})) {
13970: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13971: 	my $allowed=&allowed('vgr',$tmp_courseid);
13972: 	if (!$allowed &&
13973: 	    exists($env{'request.course.sec'}) &&
13974: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13975: 	    $allowed=&allowed('vgr',$tmp_courseid.
13976: 			      '/'.$env{'request.course.sec'});
13977: 	}
13978: 	if ($allowed) {
13979: 	    ($symb)=&get_env_multiple('form.grade_symb');
13980: 	    $courseid=$tmp_courseid;
13981: 	    ($domain)=&get_env_multiple('form.grade_domain');
13982: 	    ($name)=&get_env_multiple('form.grade_username');
13983: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13984: 	}
13985:     }
13986:     if (!$passedsymb) {
13987: 	$symb=&symbread();
13988:     } else {
13989: 	$symb=$passedsymb;
13990:     }
13991:     $courseid=$env{'request.course.id'};
13992:     $domain=$env{'user.domain'};
13993:     $name=$env{'user.name'};
13994:     if ($name eq 'public' && $domain eq 'public') {
13995: 	if (!defined($env{'form.username'})) {
13996: 	    $env{'form.username'}.=time.rand(10000000);
13997: 	}
13998: 	$name.=$env{'form.username'};
13999:     }
14000:     return ($symb,$courseid,$domain,$name,$publicuser);
14001: 
14002: }
14003: 
14004: # ------------------------------------------------------------ Serves up a file
14005: # returns either the contents of the file or 
14006: # -1 if the file doesn't exist
14007: #
14008: # if the target is a file that was uploaded via DOCS, 
14009: # a check will be made to see if a current copy exists on the local server,
14010: # if it does this will be served, otherwise a copy will be retrieved from
14011: # the home server for the course and stored in /home/httpd/html/userfiles on
14012: # the local server.   
14013: 
14014: sub getfile {
14015:     my ($file) = @_;
14016:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14017:     &repcopy($file);
14018:     return &readfile($file);
14019: }
14020: 
14021: sub repcopy_userfile {
14022:     my ($file)=@_;
14023:     my $londocroot = $perlvar{'lonDocRoot'};
14024:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14025:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14026:     my ($cdom,$cnum,$filename) = 
14027: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14028:     my $uri="/uploaded/$cdom/$cnum/$filename";
14029:     if (-e "$file") {
14030: # we already have a local copy, check it out
14031: 	my @fileinfo = stat($file);
14032: 	my $rtncode;
14033: 	my $info;
14034: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14035: 	if ($lwpresp ne 'ok') {
14036: # there is no such file anymore, even though we had a local copy
14037: 	    if ($rtncode eq '404') {
14038: 		unlink($file);
14039: 	    }
14040: 	    return -1;
14041: 	}
14042: 	if ($info < $fileinfo[9]) {
14043: # nice, the file we have is up-to-date, just say okay
14044: 	    return 'ok';
14045: 	} else {
14046: # the file is outdated, get rid of it
14047: 	    unlink($file);
14048: 	}
14049:     }
14050: # one way or the other, at this point, we don't have the file
14051: # construct the correct path for the file
14052:     my @parts = ($cdom,$cnum); 
14053:     if ($filename =~ m|^(.+)/[^/]+$|) {
14054: 	push @parts, split(/\//,$1);
14055:     }
14056:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14057:     foreach my $part (@parts) {
14058: 	$path .= '/'.$part;
14059: 	if (!-e $path) {
14060: 	    mkdir($path,0770);
14061: 	}
14062:     }
14063: # now the path exists for sure
14064: # get a user agent
14065:     my $transferfile=$file.'.in.transfer';
14066: # FIXME: this should flock
14067:     if (-e $transferfile) { return 'ok'; }
14068:     my $request;
14069:     $uri=~s/^\///;
14070:     my $homeserver = &homeserver($cnum,$cdom);
14071:     my $hostname = &hostname($homeserver);
14072:     my $protocol = $protocol{$homeserver};
14073:     $protocol = 'http' if ($protocol ne 'https');
14074:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14075:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14076: # did it work?
14077:     if ($response->is_error()) {
14078: 	unlink($transferfile);
14079: 	&logthis("Userfile repcopy failed for $uri");
14080: 	return -1;
14081:     }
14082: # worked, rename the transfer file
14083:     rename($transferfile,$file);
14084:     return 'ok';
14085: }
14086: 
14087: sub tokenwrapper {
14088:     my $uri=shift;
14089:     $uri=~s|^https?\://([^/]+)||;
14090:     $uri=~s|^/||;
14091:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14092:     my $token=$1;
14093:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14094:     if ($udom && $uname && $file) {
14095: 	$file=~s|(\?\.*)*$||;
14096:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14097:         my $homeserver = &homeserver($uname,$udom);
14098:         my $hostname = &hostname($homeserver);
14099:         my $protocol = $protocol{$homeserver};
14100:         $protocol = 'http' if ($protocol ne 'https');
14101:         return $protocol.'://'.$hostname.'/'.$uri.
14102:                (($uri=~/\?/)?'&':'?').'token='.$token.
14103:                                '&tokenissued='.$perlvar{'lonHostID'};
14104:     } else {
14105:         return '/adm/notfound.html';
14106:     }
14107: }
14108: 
14109: # call with reqtype HEAD: get last modification time
14110: # call with reqtype GET: get the file contents
14111: # Do not call this with reqtype GET for large files! It loads everything into memory
14112: #
14113: sub getuploaded {
14114:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14115:     $uri=~s/^\///;
14116:     my $homeserver = &homeserver($cnum,$cdom);
14117:     my $hostname = &hostname($homeserver);
14118:     my $protocol = $protocol{$homeserver};
14119:     $protocol = 'http' if ($protocol ne 'https');
14120:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14121:     my $request=new HTTP::Request($reqtype,$uri);
14122:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14123:     $$rtncode = $response->code;
14124:     if (! $response->is_success()) {
14125: 	return 'failed';
14126:     }      
14127:     if ($reqtype eq 'HEAD') {
14128: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14129:     } elsif ($reqtype eq 'GET') {
14130: 	$$info = $response->content;
14131:     }
14132:     return 'ok';
14133: }
14134: 
14135: sub readfile {
14136:     my $file = shift;
14137:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14138:     my $fh;
14139:     open($fh,"<",$file);
14140:     my $a='';
14141:     while (my $line = <$fh>) { $a .= $line; }
14142:     return $a;
14143: }
14144: 
14145: sub filelocation {
14146:     my ($dir,$file) = @_;
14147:     my $location;
14148:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14149: 
14150:     if ($file =~ m-^/adm/-) {
14151: 	$file=~s-^/adm/wrapper/-/-;
14152: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14153:     }
14154: 
14155:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14156:         $location = $file;
14157:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14158:         my ($udom,$uname,$filename)=
14159:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14160:         my $home=&homeserver($uname,$udom);
14161:         my $is_me=0;
14162:         my @ids=&current_machine_ids();
14163:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14164:         if ($is_me) {
14165:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14166:         } else {
14167:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14168:   	      $udom.'/'.$uname.'/'.$filename;
14169:         }
14170:     } elsif ($file =~ m-^/adm/-) {
14171: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14172:     } else {
14173:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14174:         $file=~s:^/(res|priv)/:/:;
14175:         my $space=$1;
14176:         if ( !( $file =~ m:^/:) ) {
14177:             $location = $dir. '/'.$file;
14178:         } else {
14179:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14180:         }
14181:     }
14182:     $location=~s://+:/:g; # remove duplicate /
14183:     while ($location=~m{/\.\./}) {
14184: 	if ($location =~ m{/[^/]+/\.\./}) {
14185: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14186: 	} else {
14187: 	    $location=~ s{/\.\./}{/}g;
14188: 	}
14189:     } #remove dir/..
14190:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14191:     return $location;
14192: }
14193: 
14194: sub hreflocation {
14195:     my ($dir,$file)=@_;
14196:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14197: 	$file=filelocation($dir,$file);
14198:     } elsif ($file=~m-^/adm/-) {
14199: 	$file=~s-^/adm/wrapper/-/-;
14200: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14201:     }
14202:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14203: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14204:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14205: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14206: 	        {/uploaded/$1/$2/}x;
14207:     }
14208:     if ($file=~ m{^/userfiles/}) {
14209: 	$file =~ s{^/userfiles/}{/uploaded/};
14210:     }
14211:     return $file;
14212: }
14213: 
14214: 
14215: 
14216: 
14217: 
14218: sub current_machine_domains {
14219:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14220: }
14221: 
14222: sub machine_domains {
14223:     my ($hostname) = @_;
14224:     my @domains;
14225:     my %hostname = &all_hostnames();
14226:     while( my($id, $name) = each(%hostname)) {
14227: #	&logthis("-$id-$name-$hostname-");
14228: 	if ($hostname eq $name) {
14229: 	    push(@domains,&host_domain($id));
14230: 	}
14231:     }
14232:     return @domains;
14233: }
14234: 
14235: sub current_machine_ids {
14236:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14237: }
14238: 
14239: sub machine_ids {
14240:     my ($hostname) = @_;
14241:     $hostname ||= &hostname($perlvar{'lonHostID'});
14242:     my @ids;
14243:     my %name_to_host = &all_names();
14244:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14245: 	return @{ $name_to_host{$hostname} };
14246:     }
14247:     return;
14248: }
14249: 
14250: sub additional_machine_domains {
14251:     my @domains;
14252:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14253:     while( my $line = <$fh>) {
14254:         $line =~ s/\s//g;
14255:         push(@domains,$line);
14256:     }
14257:     return @domains;
14258: }
14259: 
14260: sub default_login_domain {
14261:     my $domain = $perlvar{'lonDefDomain'};
14262:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14263:     foreach my $posdom (&current_machine_domains(),
14264:                         &additional_machine_domains()) {
14265:         if (lc($posdom) eq lc($testdomain)) {
14266:             $domain=$posdom;
14267:             last;
14268:         }
14269:     }
14270:     return $domain;
14271: }
14272: 
14273: sub shared_institution {
14274:     my ($dom,$lonhost) = @_;
14275:     if ($lonhost eq '') {
14276:         $lonhost = $perlvar{'lonHostID'};
14277:     }
14278:     my $same_intdom;
14279:     my $hostintdom = &internet_dom($lonhost);
14280:     if ($hostintdom ne '') {
14281:         my %iphost = &get_iphost();
14282:         my $primary_id = &domain($dom,'primary');
14283:         my $primary_ip = &get_host_ip($primary_id);
14284:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14285:             foreach my $id (@{$iphost{$primary_ip}}) {
14286:                 my $intdom = &internet_dom($id);
14287:                 if ($intdom eq $hostintdom) {
14288:                     $same_intdom = 1;
14289:                     last;
14290:                 }
14291:             }
14292:         }
14293:     }
14294:     return $same_intdom;
14295: }
14296: 
14297: sub uses_sts {
14298:     my ($ignore_cache) = @_;
14299:     my $lonhost = $perlvar{'lonHostID'};
14300:     my $hostname = &hostname($lonhost);
14301:     my $sts_on;
14302:     if ($protocol{$lonhost} eq 'https') {
14303:         my $cachetime = 12*3600;
14304:         if (!$ignore_cache) {
14305:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14306:             if (defined($cached)) {
14307:                 return $sts_on;
14308:             }
14309:         }
14310:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14311:         my $request=new HTTP::Request('HEAD',$url);
14312:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14313:         if ($response->is_success) {
14314:             my $has_sts = $response->header('Strict-Transport-Security');
14315:             if ($has_sts eq '') {
14316:                 $sts_on = 0;
14317:             } else {
14318:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14319:                     my $maxage = $1;
14320:                     if ($maxage) {
14321:                         $sts_on = 1;
14322:                     } else {
14323:                         $sts_on = 0;
14324:                     }
14325:                 } else {
14326:                     $sts_on = 0;
14327:                 }
14328:             }
14329:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14330:         }
14331:     }
14332:     return;
14333: }
14334: 
14335: sub get_requestor_ip {
14336:     my ($r,$nolookup,$noproxy) = @_;
14337:     my $from_ip;
14338:     if (ref($r)) {
14339:         $from_ip = $r->get_remote_host($nolookup);
14340:     } else {
14341:         $from_ip = $ENV{'REMOTE_ADDR'};
14342:     }
14343:     return $from_ip if ($noproxy); 
14344:     # Who controls proxy settings for server
14345:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14346:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14347:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14348:         if ($proxyinfo->{'vpnint'}) {
14349:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14350:                 return $from_ip;
14351:             }
14352:         }
14353:         if ($proxyinfo->{'trusted'}) {
14354:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14355:                 my $ipheader = $proxyinfo->{'ipheader'};
14356:                 my ($ip,$xfor);
14357:                 if (ref($r)) {
14358:                     if ($ipheader) {
14359:                         $ip = $r->headers_in->{$ipheader};
14360:                     }
14361:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14362:                 } else {
14363:                     if ($ipheader) {
14364:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14365:                     }
14366:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14367:                 }
14368:                 if (($ip eq '') && ($xfor ne '')) {
14369:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14370:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14371:                             $ip = $poss_ip;
14372:                             last;
14373:                         }
14374:                     }
14375:                 }
14376:                 if ($ip ne '') {
14377:                     return $ip;
14378:                 }
14379:             }
14380:         }
14381:     }
14382:     return $from_ip;
14383: }
14384: 
14385: sub get_proxy_settings {
14386:     my ($dom_in_use) = @_;
14387:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14388:     my $proxyinfo = {
14389:                        ipheader => $domdefaults{'waf_ipheader'},
14390:                        trusted  => $domdefaults{'waf_trusted'},
14391:                        vpnint   => $domdefaults{'waf_vpnint'},
14392:                        vpnext   => $domdefaults{'waf_vpnext'},
14393:                     };
14394:     return $proxyinfo;
14395: }
14396: 
14397: sub ip_match {
14398:     my ($ip,$pattern_str) = @_;
14399:     $ip=Net::CIDR::cidrvalidate($ip);
14400:     if ($ip) {
14401:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14402:     }
14403:     return;
14404: }
14405: 
14406: sub get_proxy_alias {
14407:     my $lonhost = $perlvar{'lonHostID'};
14408:     if ($lonhost ne '') {
14409:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonhost);
14410:         if ($cached) {
14411:             return $alias;
14412:         }
14413:         my $dom = &Apache::lonnet::host_domain($lonhost);
14414:         if ($dom ne '') {
14415:             my $cachetime = 60*60*24;
14416:             my %domconfig =
14417:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14418:             my $alias;
14419:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14420:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14421:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonhost};
14422:                 }
14423:             }
14424:             return &do_cache_new('proxyalias',$lonhost,$alias,$cachetime);
14425:         }
14426:     }
14427:     return;
14428: }
14429: 
14430: # ------------------------------------------------------------- Declutters URLs
14431: 
14432: sub declutter {
14433:     my $thisfn=shift;
14434:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14435:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14436:         $thisfn=~s{^/home/httpd/html}{};
14437:     }
14438:     $thisfn=~s/^\///;
14439:     $thisfn=~s|^adm/wrapper/||;
14440:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14441:     $thisfn=~s/^res\///;
14442:     $thisfn=~s/^priv\///;
14443:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14444:         $thisfn=~s/\?.+$//;
14445:     }
14446:     return $thisfn;
14447: }
14448: 
14449: # ------------------------------------------------------------- Clutter up URLs
14450: 
14451: sub clutter {
14452:     my $thisfn='/'.&declutter(shift);
14453:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14454: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14455:        $thisfn='/res'.$thisfn; 
14456:     }
14457:     if ($thisfn !~m|^/adm|) {
14458: 	if ($thisfn =~ m|^/ext/|) {
14459: 	    $thisfn='/adm/wrapper'.$thisfn;
14460: 	} else {
14461: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14462: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14463: 	    if ($embstyle eq 'ssi'
14464: 		|| ($embstyle eq 'hdn')
14465: 		|| ($embstyle eq 'rat')
14466: 		|| ($embstyle eq 'prv')
14467: 		|| ($embstyle eq 'ign')) {
14468: 		#do nothing with these
14469: 	    } elsif (($embstyle eq 'img') 
14470: 		|| ($embstyle eq 'emb')
14471: 		|| ($embstyle eq 'wrp')) {
14472: 		$thisfn='/adm/wrapper'.$thisfn;
14473: 	    } elsif ($embstyle eq 'unk'
14474: 		     && $thisfn!~/\.(sequence|page)$/) {
14475: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14476: 	    } else {
14477: #		&logthis("Got a blank emb style");
14478: 	    }
14479: 	}
14480:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14481:         $thisfn='/adm/wrapper'.$thisfn;
14482:     }
14483:     return $thisfn;
14484: }
14485: 
14486: sub clutter_with_no_wrapper {
14487:     my $uri = &clutter(shift);
14488:     if ($uri =~ m-^/adm/-) {
14489: 	$uri =~ s-^/adm/wrapper/-/-;
14490: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14491:     }
14492:     return $uri;
14493: }
14494: 
14495: sub freeze_escape {
14496:     my ($value)=@_;
14497:     if (ref($value)) {
14498: 	$value=&nfreeze($value);
14499: 	return '__FROZEN__'.&escape($value);
14500:     }
14501:     return &escape($value);
14502: }
14503: 
14504: 
14505: sub thaw_unescape {
14506:     my ($value)=@_;
14507:     if ($value =~ /^__FROZEN__/) {
14508: 	substr($value,0,10,undef);
14509: 	$value=&unescape($value);
14510: 	return &thaw($value);
14511:     }
14512:     return &unescape($value);
14513: }
14514: 
14515: sub correct_line_ends {
14516:     my ($result)=@_;
14517:     $$result =~s/\r\n/\n/mg;
14518:     $$result =~s/\r/\n/mg;
14519: }
14520: # ================================================================ Main Program
14521: 
14522: sub goodbye {
14523:    &logthis("Starting Shut down");
14524: #not converted to using infrastruture and probably shouldn't be
14525:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14526: #converted
14527: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14528:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14529: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14530: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14531: #1.1 only
14532: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14533: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14534: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14535: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14536:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14537:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14538:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14539:    &flushcourselogs();
14540:    &logthis("Shutting down");
14541: }
14542: 
14543: sub get_dns {
14544:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14545:     if (!$ignore_cache) {
14546: 	my ($content,$cached)=
14547: 	    &Apache::lonnet::is_cached_new('dns',$url);
14548: 	if ($cached) {
14549: 	    &$func($content,$hashref);
14550: 	    return;
14551: 	}
14552:     }
14553: 
14554:     my %alldns;
14555:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14556:         foreach my $dns (<$config>) {
14557: 	    next if ($dns !~ /^\^(\S*)/x);
14558:             my $line = $1;
14559:             my ($host,$protocol) = split(/:/,$line);
14560:             if ($protocol ne 'https') {
14561:                 $protocol = 'http';
14562:             }
14563: 	    $alldns{$host} = $protocol;
14564:         }
14565:         close($config);
14566:     }
14567:     while (%alldns) {
14568: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14569: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14570:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14571:         delete($alldns{$dns});
14572: 	next if ($response->is_error());
14573:         if ($url eq '/adm/dns/loncapaCRL') {
14574:             return &$func($response);
14575:         } else {
14576: 	    my @content = split("\n",$response->content);
14577: 	    unless ($nocache) {
14578: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14579: 	    }
14580: 	    &$func(\@content,$hashref);
14581:             return;
14582:         }
14583:     }
14584:     my $which = (split('/',$url,4))[3];
14585:     if ($which eq 'loncapaCRL') {
14586:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14587:         if (-e $diskfile) {
14588:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14589:         } else {
14590:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14591:         }
14592:     } else {
14593:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14594:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14595:             my @content = <$config>;
14596:             close($config);
14597:             &$func(\@content,$hashref);
14598:         }
14599:     }
14600:     return;
14601: }
14602: 
14603: # ------------------------------------------------------Get DNS checksums file
14604: sub parse_dns_checksums_tab {
14605:     my ($lines,$hashref) = @_;
14606:     my $lonhost = $perlvar{'lonHostID'};
14607:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14608:     my $loncaparev = &get_server_loncaparev($machine_dom);
14609:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14610:     my $webconfdir = '/etc/httpd/conf';
14611:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14612:         $webconfdir = '/etc/apache2';
14613:     } elsif ($distro =~ /^sles(\d+)$/) {
14614:         if ($1 >= 10) {
14615:             $webconfdir = '/etc/apache2';
14616:         }
14617:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14618:         if ($1 >= 10.0) {
14619:             $webconfdir = '/etc/apache2';
14620:         }
14621:     }
14622:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14623:     my (%chksum,%revnum);
14624:     if (ref($lines) eq 'ARRAY') {
14625:         chomp(@{$lines});
14626:         my $version = shift(@{$lines});
14627:         if ($version eq $release) {  
14628:             foreach my $line (@{$lines}) {
14629:                 my ($file,$version,$shasum) = split(/,/,$line);
14630:                 if ($file =~ m{^/etc/httpd/conf}) {
14631:                     if ($webconfdir eq '/etc/apache2') {
14632:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14633:                     }
14634:                 }
14635:                 $chksum{$file} = $shasum;
14636:                 $revnum{$file} = $version;
14637:             }
14638:             if (ref($hashref) eq 'HASH') {
14639:                 %{$hashref} = (
14640:                                 sums     => \%chksum,
14641:                                 versions => \%revnum,
14642:                               );
14643:             }
14644:         }
14645:     }
14646:     return;
14647: }
14648: 
14649: sub fetch_dns_checksums {
14650:     my %checksums;
14651:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14652:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14653:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14654:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14655:              \%checksums);
14656:     return \%checksums;
14657: }
14658: 
14659: sub fetch_crl_pemfile {
14660:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14661: }
14662: 
14663: sub save_crl_pem {
14664:     my ($response) = @_;
14665:     my ($msg,$hadchanges);
14666:     if (ref($response)) {
14667:         my $now = time;
14668:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14669:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14670:         if (open(my $fh,'>',"$tmpcrl")) {
14671:             print $fh $response->content;
14672:             close($fh);
14673:             if (-e $lonca) {
14674:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14675:                     my $check = <PIPE>;
14676:                     close(PIPE);
14677:                     chomp($check);
14678:                     if ($check eq 'verify OK') {
14679:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14680:                         my $backup;
14681:                         if (-e $dest) {
14682:                             if (&File::Copy::move($dest,"$dest.bak")) {
14683:                                 $backup = 'ok';
14684:                             }
14685:                         }
14686:                         if (&File::Copy::move($tmpcrl,$dest)) {
14687:                             $msg = 'ok';
14688:                             if ($backup) {
14689:                                 my (%oldnums,%newnums);
14690:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14691:                                     while (<PIPE>) {
14692:                                         $oldnums{(split(/:/))[1]} = 1;
14693:                                     }
14694:                                     close(PIPE);
14695:                                 }
14696:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14697:                                     while(<PIPE>) {
14698:                                         $newnums{(split(/:/))[1]} = 1;
14699:                                     }
14700:                                     close(PIPE);
14701:                                 }
14702:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14703:                                     unless (exists($oldnums{$key})) {
14704:                                         $hadchanges = 1;
14705:                                         last;
14706:                                     }
14707:                                 }
14708:                                 unless ($hadchanges) {
14709:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14710:                                         unless (exists($newnums{$key})) {
14711:                                             $hadchanges = 1;
14712:                                             last;
14713:                                         }
14714:                                     }
14715:                                 }
14716:                             }
14717:                         }
14718:                     } else {
14719:                         unlink($tmpcrl);
14720:                     }
14721:                 } else {
14722:                     unlink($tmpcrl);
14723:                 }
14724:             } else {
14725:                 unlink($tmpcrl);
14726:             }
14727:         }
14728:     }
14729:     return ($msg,$hadchanges);
14730: }
14731: 
14732: # ------------------------------------------------------------ Read domain file
14733: {
14734:     my $loaded;
14735:     my %domain;
14736: 
14737:     sub parse_domain_tab {
14738: 	my ($lines) = @_;
14739: 	foreach my $line (@$lines) {
14740: 	    next if ($line =~ /^(\#|\s*$ )/x);
14741: 
14742: 	    chomp($line);
14743: 	    my ($name,@elements) = split(/:/,$line,9);
14744: 	    my %this_domain;
14745: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14746: 			       'lang_def', 'city', 'longi', 'lati',
14747: 			       'primary') {
14748: 		$this_domain{$field} = shift(@elements);
14749: 	    }
14750: 	    $domain{$name} = \%this_domain;
14751: 	}
14752:     }
14753: 
14754:     sub reset_domain_info {
14755: 	undef($loaded);
14756: 	undef(%domain);
14757:     }
14758: 
14759:     sub load_domain_tab {
14760: 	my ($ignore_cache,$nocache) = @_;
14761: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14762: 	my $fh;
14763: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14764: 	    my @lines = <$fh>;
14765: 	    &parse_domain_tab(\@lines);
14766: 	}
14767: 	close($fh);
14768: 	$loaded = 1;
14769:     }
14770: 
14771:     sub domain {
14772: 	&load_domain_tab() if (!$loaded);
14773: 
14774: 	my ($name,$what) = @_;
14775: 	return if ( !exists($domain{$name}) );
14776: 
14777: 	if (!$what) {
14778: 	    return $domain{$name}{'description'};
14779: 	}
14780: 	return $domain{$name}{$what};
14781:     }
14782: 
14783:     sub domain_info {
14784:         &load_domain_tab() if (!$loaded);
14785:         return %domain;
14786:     }
14787: 
14788: }
14789: 
14790: 
14791: # ------------------------------------------------------------- Read hosts file
14792: {
14793:     my %hostname;
14794:     my %hostdom;
14795:     my %libserv;
14796:     my $loaded;
14797:     my %name_to_host;
14798:     my %internetdom;
14799:     my %LC_dns_serv;
14800: 
14801:     sub parse_hosts_tab {
14802: 	my ($file) = @_;
14803: 	foreach my $configline (@$file) {
14804: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14805:             chomp($configline);
14806: 	    if ($configline =~ /^\^/) {
14807:                 if ($configline =~ /^\^([\w.\-]+)/) {
14808:                     $LC_dns_serv{$1} = 1;
14809:                 }
14810:                 next;
14811:             }
14812: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14813: 	    $name=~s/\s//g;
14814: 	    if ($id && $domain && $role && $name) {
14815:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14816:                     my $curr = $hostname{$id};
14817:                     my $skip;
14818:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14819:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14820:                             $skip = 1;
14821:                         } else {
14822:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14823:                         }
14824:                     }
14825:                     unless ($skip) {
14826:                         push(@{$name_to_host{$name}},$id);
14827:                     }
14828:                 } else {
14829:                     push(@{$name_to_host{$name}},$id);
14830:                 }
14831: 		$hostname{$id}=$name;
14832: 		$hostdom{$id}=$domain;
14833: 		if ($role eq 'library') { $libserv{$id}=$name; }
14834:                 if (defined($protocol)) {
14835:                     if ($protocol eq 'https') {
14836:                         $protocol{$id} = $protocol;
14837:                     } else {
14838:                         $protocol{$id} = 'http'; 
14839:                     }
14840:                 } else {
14841:                     $protocol{$id} = 'http';
14842:                 }
14843:                 if (defined($intdom)) {
14844:                     $internetdom{$id} = $intdom;
14845:                 }
14846: 	    }
14847: 	}
14848:     }
14849:     
14850:     sub reset_hosts_info {
14851: 	&purge_remembered();
14852: 	&reset_domain_info();
14853: 	&reset_hosts_ip_info();
14854:         undef(%internetdom);
14855: 	undef(%name_to_host);
14856: 	undef(%hostname);
14857: 	undef(%hostdom);
14858: 	undef(%libserv);
14859: 	undef($loaded);
14860:     }
14861: 
14862:     sub load_hosts_tab {
14863: 	my ($ignore_cache,$nocache) = @_;
14864: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14865: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14866: 	my @config = <$config>;
14867: 	&parse_hosts_tab(\@config);
14868: 	close($config);
14869: 	$loaded=1;
14870:     }
14871: 
14872:     sub hostname {
14873: 	&load_hosts_tab() if (!$loaded);
14874: 
14875: 	my ($lonid) = @_;
14876: 	return $hostname{$lonid};
14877:     }
14878: 
14879:     sub all_hostnames {
14880: 	&load_hosts_tab() if (!$loaded);
14881: 
14882: 	return %hostname;
14883:     }
14884: 
14885:     sub all_names {
14886:         my ($ignore_cache,$nocache) = @_;
14887: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14888: 
14889: 	return %name_to_host;
14890:     }
14891: 
14892:     sub all_host_domain {
14893:         &load_hosts_tab() if (!$loaded);
14894:         return %hostdom;
14895:     }
14896: 
14897:     sub all_host_intdom {
14898:         &load_hosts_tab() if (!$loaded);
14899:         return %internetdom;
14900:     }
14901: 
14902:     sub is_library {
14903: 	&load_hosts_tab() if (!$loaded);
14904: 
14905: 	return exists($libserv{$_[0]});
14906:     }
14907: 
14908:     sub all_library {
14909: 	&load_hosts_tab() if (!$loaded);
14910: 
14911: 	return %libserv;
14912:     }
14913: 
14914:     sub unique_library {
14915: 	#2x reverse removes all hostnames that appear more than once
14916:         my %unique = reverse &all_library();
14917:         return reverse %unique;
14918:     }
14919: 
14920:     sub get_servers {
14921: 	&load_hosts_tab() if (!$loaded);
14922: 
14923: 	my ($domain,$type) = @_;
14924: 	my %possible_hosts = ($type eq 'library') ? %libserv
14925: 	                                          : %hostname;
14926: 	my %result;
14927: 	if (ref($domain) eq 'ARRAY') {
14928: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14929: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14930: 		    $result{$host} = $hostname;
14931: 		}
14932: 	    }
14933: 	} else {
14934: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14935: 		if ($hostdom{$host} eq $domain) {
14936: 		    $result{$host} = $hostname;
14937: 		}
14938: 	    }
14939: 	}
14940: 	return %result;
14941:     }
14942: 
14943:     sub get_unique_servers {
14944:         my %unique = reverse &get_servers(@_);
14945: 	return reverse %unique;
14946:     }
14947: 
14948:     sub host_domain {
14949: 	&load_hosts_tab() if (!$loaded);
14950: 
14951: 	my ($lonid) = @_;
14952: 	return $hostdom{$lonid};
14953:     }
14954: 
14955:     sub all_domains {
14956: 	&load_hosts_tab() if (!$loaded);
14957: 
14958: 	my %seen;
14959: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14960: 	return @uniq;
14961:     }
14962: 
14963:     sub internet_dom {
14964:         &load_hosts_tab() if (!$loaded);
14965: 
14966:         my ($lonid) = @_;
14967:         return $internetdom{$lonid};
14968:     }
14969: 
14970:     sub is_LC_dns {
14971:         &load_hosts_tab() if (!$loaded);
14972: 
14973:         my ($hostname) = @_;
14974:         return exists($LC_dns_serv{$hostname});
14975:     }
14976: 
14977: }
14978: 
14979: { 
14980:     my %iphost;
14981:     my %name_to_ip;
14982:     my %lonid_to_ip;
14983: 
14984:     sub get_hosts_from_ip {
14985: 	my ($ip) = @_;
14986: 	my %iphosts = &get_iphost();
14987: 	if (ref($iphosts{$ip})) {
14988: 	    return @{$iphosts{$ip}};
14989: 	}
14990: 	return;
14991:     }
14992:     
14993:     sub reset_hosts_ip_info {
14994: 	undef(%iphost);
14995: 	undef(%name_to_ip);
14996: 	undef(%lonid_to_ip);
14997:     }
14998: 
14999:     sub get_host_ip {
15000: 	my ($lonid) = @_;
15001: 	if (exists($lonid_to_ip{$lonid})) {
15002: 	    return $lonid_to_ip{$lonid};
15003: 	}
15004: 	my $name=&hostname($lonid);
15005:    	my $ip = gethostbyname($name);
15006: 	return if (!$ip || length($ip) ne 4);
15007: 	$ip=inet_ntoa($ip);
15008: 	$name_to_ip{$name}   = $ip;
15009: 	$lonid_to_ip{$lonid} = $ip;
15010: 	return $ip;
15011:     }
15012:     
15013:     sub get_iphost {
15014: 	my ($ignore_cache,$nocache) = @_;
15015: 
15016: 	if (!$ignore_cache) {
15017: 	    if (%iphost) {
15018: 		return %iphost;
15019: 	    }
15020: 	    my ($ip_info,$cached)=
15021: 		&Apache::lonnet::is_cached_new('iphost','iphost');
15022: 	    if ($cached) {
15023: 		%iphost      = %{$ip_info->[0]};
15024: 		%name_to_ip  = %{$ip_info->[1]};
15025: 		%lonid_to_ip = %{$ip_info->[2]};
15026: 		return %iphost;
15027: 	    }
15028: 	}
15029: 
15030: 	# get yesterday's info for fallback
15031: 	my %old_name_to_ip;
15032: 	my ($ip_info,$cached)=
15033: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
15034: 	if ($cached) {
15035: 	    %old_name_to_ip = %{$ip_info->[1]};
15036: 	}
15037: 
15038: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15039: 	foreach my $name (keys(%name_to_host)) {
15040: 	    my $ip;
15041: 	    if (!exists($name_to_ip{$name})) {
15042: 		$ip = gethostbyname($name);
15043: 		if (!$ip || length($ip) ne 4) {
15044: 		    if (defined($old_name_to_ip{$name})) {
15045: 			$ip = $old_name_to_ip{$name};
15046: 			&logthis("Can't find $name defaulting to old $ip");
15047: 		    } else {
15048: 			&logthis("Name $name no IP found");
15049: 			next;
15050: 		    }
15051: 		} else {
15052: 		    $ip=inet_ntoa($ip);
15053: 		}
15054: 		$name_to_ip{$name} = $ip;
15055: 	    } else {
15056: 		$ip = $name_to_ip{$name};
15057: 	    }
15058: 	    foreach my $id (@{ $name_to_host{$name} }) {
15059: 		$lonid_to_ip{$id} = $ip;
15060: 	    }
15061: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15062: 	}
15063:         unless ($nocache) {
15064: 	    &do_cache_new('iphost','iphost',
15065: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15066: 		          48*60*60);
15067:         }
15068: 
15069: 	return %iphost;
15070:     }
15071: 
15072:     #
15073:     #  Given a DNS returns the loncapa host name for that DNS 
15074:     # 
15075:     sub host_from_dns {
15076:         my ($dns) = @_;
15077:         my @hosts;
15078:         my $ip;
15079: 
15080:         if (exists($name_to_ip{$dns})) {
15081:             $ip = $name_to_ip{$dns};
15082:         }
15083:         if (!$ip) {
15084:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15085:             if (length($ip) == 4) { 
15086: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15087:             }
15088:         }
15089:         if ($ip) {
15090: 	    @hosts = get_hosts_from_ip($ip);
15091: 	    return $hosts[0];
15092:         }
15093:         return undef;
15094:     }
15095: 
15096:     sub get_internet_names {
15097:         my ($lonid) = @_;
15098:         return if ($lonid eq '');
15099:         my ($idnref,$cached)=
15100:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15101:         if ($cached) {
15102:             return $idnref;
15103:         }
15104:         my $ip = &get_host_ip($lonid);
15105:         my @hosts = &get_hosts_from_ip($ip);
15106:         my %iphost = &get_iphost();
15107:         my (@idns,%seen);
15108:         foreach my $id (@hosts) {
15109:             my $dom = &host_domain($id);
15110:             my $prim_id = &domain($dom,'primary');
15111:             my $prim_ip = &get_host_ip($prim_id);
15112:             next if ($seen{$prim_ip});
15113:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15114:                 foreach my $id (@{$iphost{$prim_ip}}) {
15115:                     my $intdom = &internet_dom($id);
15116:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15117:                         push(@idns,$intdom);
15118:                     }
15119:                 }
15120:             }
15121:             $seen{$prim_ip} = 1;
15122:         }
15123:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15124:     }
15125: 
15126: }
15127: 
15128: sub all_loncaparevs {
15129:     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);
15130: }
15131: 
15132: # ---------------------------------------------------------- Read loncaparev table
15133: {
15134:     sub load_loncaparevs { 
15135:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15136:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15137:                 while (my $configline=<$config>) {
15138:                     chomp($configline);
15139:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15140:                     $loncaparevs{$hostid}=$loncaparev;
15141:                 }
15142:                 close($config);
15143:             }
15144:         }
15145:     }
15146: }
15147: 
15148: # ---------------------------------------------------------- Read serverhostID table
15149: {
15150:     sub load_serverhomeIDs {
15151:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15152:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15153:                 while (my $configline=<$config>) {
15154:                     chomp($configline);
15155:                     my ($name,$id)=split(/:/,$configline);
15156:                     $serverhomeIDs{$name}=$id;
15157:                 }
15158:                 close($config);
15159:             }
15160:         }
15161:     }
15162: }
15163: 
15164: 
15165: BEGIN {
15166: 
15167: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15168:     unless ($readit) {
15169: {
15170:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15171:     %perlvar = (%perlvar,%{$configvars});
15172: }
15173: 
15174: 
15175: # ------------------------------------------------------ Read spare server file
15176: {
15177:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15178: 
15179:     while (my $configline=<$config>) {
15180:        chomp($configline);
15181:        if ($configline) {
15182: 	   my ($host,$type) = split(':',$configline,2);
15183: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15184: 	   push(@{ $spareid{$type} }, $host);
15185:        }
15186:     }
15187:     close($config);
15188: }
15189: # ------------------------------------------------------------ Read permissions
15190: {
15191:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15192: 
15193:     while (my $configline=<$config>) {
15194: 	chomp($configline);
15195: 	if ($configline) {
15196: 	    my ($role,$perm)=split(/ /,$configline);
15197: 	    if ($perm ne '') { $pr{$role}=$perm; }
15198: 	}
15199:     }
15200:     close($config);
15201: }
15202: 
15203: # -------------------------------------------- Read plain texts for permissions
15204: {
15205:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15206: 
15207:     while (my $configline=<$config>) {
15208: 	chomp($configline);
15209: 	if ($configline) {
15210: 	    my ($short,@plain)=split(/:/,$configline);
15211:             %{$prp{$short}} = ();
15212: 	    if (@plain > 0) {
15213:                 $prp{$short}{'std'} = $plain[0];
15214:                 for (my $i=1; $i<@plain; $i++) {
15215:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15216:                 }
15217:             }
15218: 	}
15219:     }
15220:     close($config);
15221: }
15222: 
15223: # ---------------------------------------------------------- Read package table
15224: {
15225:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15226: 
15227:     while (my $configline=<$config>) {
15228: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15229: 	chomp($configline);
15230: 	my ($short,$plain)=split(/:/,$configline);
15231: 	my ($pack,$name)=split(/\&/,$short);
15232: 	if ($plain ne '') {
15233: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15234: 	    $packagetab{$short}=$plain; 
15235: 	}
15236:     }
15237:     close($config);
15238: }
15239: 
15240: # ---------------------------------------------------------- Read loncaparev table
15241: 
15242: &load_loncaparevs();
15243: 
15244: # ---------------------------------------------------------- Read serverhostID table
15245: 
15246: &load_serverhomeIDs();
15247: 
15248: # ---------------------------------------------------------- Read releaseslist XML
15249: {
15250:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15251:     if (-e $file) {
15252:         my $parser = HTML::LCParser->new($file);
15253:         while (my $token = $parser->get_token()) {
15254:             if ($token->[0] eq 'S') {
15255:                 my $item = $token->[1];
15256:                 my $name = $token->[2]{'name'};
15257:                 my $value = $token->[2]{'value'};
15258:                 my $valuematch = $token->[2]{'valuematch'};
15259:                 my $namematch = $token->[2]{'namematch'};
15260:                 if ($item eq 'parameter') {
15261:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15262:                         my $release = $parser->get_text();
15263:                         $release =~ s/(^\s*|\s*$ )//gx;
15264:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15265:                     }
15266:                 } elsif ($item ne '' && $name ne '') {
15267:                     my $release = $parser->get_text();
15268:                     $release =~ s/(^\s*|\s*$ )//gx;
15269:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15270:                 }
15271:             }
15272:         }
15273:     }
15274: }
15275: 
15276: # ---------------------------------------------------------- Read managers table
15277: {
15278:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15279:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15280:             while (my $configline=<$config>) {
15281:                 chomp($configline);
15282:                 next if ($configline =~ /^\#/);
15283:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15284:                     $managerstab{$configline} = 1;
15285:                 }
15286:             }
15287:             close($config);
15288:         }
15289:     }
15290: }
15291: 
15292: # ------------- set up temporary directory
15293: {
15294:     $tmpdir = LONCAPA::tempdir();
15295: 
15296: }
15297: 
15298: # ------------- set default texengine (domain default overrides this)
15299: {
15300:     $deftex = LONCAPA::texengine();
15301: }
15302: 
15303: # ------------- set default minimum length for passwords for internal auth users
15304: {
15305:     $passwdmin = LONCAPA::passwd_min();
15306: }
15307: 
15308: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15309: 				'compress_threshold'=> 20_000,
15310:  			        });
15311: 
15312: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15313: $dumpcount=0;
15314: $locknum=0;
15315: 
15316: &logtouch();
15317: &logthis('<font color="yellow">INFO: Read configuration</font>');
15318: $readit=1;
15319:     {
15320: 	use integer;
15321: 	my $test=(2**32)+1;
15322: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15323: 	&logthis(" Detected 64bit platform ($_64bit)");
15324:     }
15325: }
15326: }
15327: 
15328: 1;
15329: __END__
15330: 
15331: =pod
15332: 
15333: =head1 NAME
15334: 
15335: Apache::lonnet - Subroutines to ask questions about things in the network.
15336: 
15337: =head1 SYNOPSIS
15338: 
15339: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15340: 
15341:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15342: 
15343: Common parameters:
15344: 
15345: =over 4
15346: 
15347: =item *
15348: 
15349: $uname : an internal username (if $cname expecting a course Id specifically)
15350: 
15351: =item *
15352: 
15353: $udom : a domain (if $cdom expecting a course's domain specifically)
15354: 
15355: =item *
15356: 
15357: $symb : a resource instance identifier
15358: 
15359: =item *
15360: 
15361: $namespace : the name of a .db file that contains the data needed or
15362: being set.
15363: 
15364: =back
15365: 
15366: =head1 OVERVIEW
15367: 
15368: lonnet provides subroutines which interact with the
15369: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15370: about classes, users, and resources.
15371: 
15372: For many of these objects you can also use this to store data about
15373: them or modify them in various ways.
15374: 
15375: =head2 Symbs
15376: 
15377: To identify a specific instance of a resource, LON-CAPA uses symbols
15378: or "symbs"X<symb>. These identifiers are built from the URL of the
15379: map, the resource number of the resource in the map, and the URL of
15380: the resource itself. The latter is somewhat redundant, but might help
15381: if maps change.
15382: 
15383: An example is
15384: 
15385:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15386: 
15387: The respective map entry is
15388: 
15389:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15390:   title="Problem 2">
15391:  </resource>
15392: 
15393: Symbs are used by the random number generator, as well as to store and
15394: restore data specific to a certain instance of for example a problem.
15395: 
15396: =head2 Storing And Retrieving Data
15397: 
15398: X<store()>X<cstore()>X<restore()>Three of the most important functions
15399: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15400: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15401: is is the non-critical message twin of cstore. These functions are for
15402: handlers to store a perl hash to a user's permanent data space in an
15403: easy manner, and to retrieve it again on another call. It is expected
15404: that a handler would use this once at the beginning to retrieve data,
15405: and then again once at the end to send only the new data back.
15406: 
15407: The data is stored in the user's data directory on the user's
15408: homeserver under the ID of the course.
15409: 
15410: The hash that is returned by restore will have all of the previous
15411: value for all of the elements of the hash.
15412: 
15413: Example:
15414: 
15415:  #creating a hash
15416:  my %hash;
15417:  $hash{'foo'}='bar';
15418: 
15419:  #storing it
15420:  &Apache::lonnet::cstore(\%hash);
15421: 
15422:  #changing a value
15423:  $hash{'foo'}='notbar';
15424: 
15425:  #adding a new value
15426:  $hash{'bar'}='foo';
15427:  &Apache::lonnet::cstore(\%hash);
15428: 
15429:  #retrieving the hash
15430:  my %history=&Apache::lonnet::restore();
15431: 
15432:  #print the hash
15433:  foreach my $key (sort(keys(%history))) {
15434:    print("\%history{$key} = $history{$key}");
15435:  }
15436: 
15437: Will print out:
15438: 
15439:  %history{1:foo} = bar
15440:  %history{1:keys} = foo:timestamp
15441:  %history{1:timestamp} = 990455579
15442:  %history{2:bar} = foo
15443:  %history{2:foo} = notbar
15444:  %history{2:keys} = foo:bar:timestamp
15445:  %history{2:timestamp} = 990455580
15446:  %history{bar} = foo
15447:  %history{foo} = notbar
15448:  %history{timestamp} = 990455580
15449:  %history{version} = 2
15450: 
15451: Note that the special hash entries C<keys>, C<version> and
15452: C<timestamp> were added to the hash. C<version> will be equal to the
15453: total number of versions of the data that have been stored. The
15454: C<timestamp> attribute will be the UNIX time the hash was
15455: stored. C<keys> is available in every historical section to list which
15456: keys were added or changed at a specific historical revision of a
15457: hash.
15458: 
15459: B<Warning>: do not store the hash that restore returns directly. This
15460: will cause a mess since it will restore the historical keys as if the
15461: were new keys. I.E. 1:foo will become 1:1:foo etc.
15462: 
15463: Calling convention:
15464: 
15465:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15466:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15467: 
15468: For more detailed information, see lonnet specific documentation.
15469: 
15470: =head1 RETURN MESSAGES
15471: 
15472: =over 4
15473: 
15474: =item * B<con_lost>: unable to contact remote host
15475: 
15476: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15477: when the connection is brought back up
15478: 
15479: =item * B<con_failed>: unable to contact remote host and unable to save message
15480: for later delivery
15481: 
15482: =item * B<error:>: an error a occurred, a description of the error follows the :
15483: 
15484: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15485: that was requested
15486: 
15487: =back
15488: 
15489: =head1 PUBLIC SUBROUTINES
15490: 
15491: =head2 Session Environment Functions
15492: 
15493: =over 4
15494: 
15495: =item * 
15496: X<appenv()>
15497: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15498: the user envirnoment file, and will be restored for each access this
15499: user makes during this session, also modifies the %env for the current
15500: process. Optional rolesarrayref - if defined contains a reference to an array
15501: of roles which are exempt from the restriction on modifying user.role entries 
15502: in the user's environment.db and in %env.    
15503: 
15504: =item *
15505: X<delenv()>
15506: B<delenv($delthis,$regexp)>: removes all items from the session
15507: environment file that begin with $delthis. If the 
15508: optional second arg - $regexp - is true, $delthis is treated as a 
15509: regular expression, otherwise \Q$delthis\E is used. 
15510: The values are also deleted from the current processes %env.
15511: 
15512: =item * get_env_multiple($name) 
15513: 
15514: gets $name from the %env hash, it seemlessly handles the cases where multiple
15515: values may be defined and end up as an array ref.
15516: 
15517: returns an array of values
15518: 
15519: =back
15520: 
15521: =head2 User Information
15522: 
15523: =over 4
15524: 
15525: =item *
15526: X<queryauthenticate()>
15527: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15528: authentication scheme
15529: 
15530: =item *
15531: X<authenticate()>
15532: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15533: authenticate user from domain's lib servers (first use the current
15534: one). C<$upass> should be the users password.
15535: $checkdefauth is optional (value is 1 if a check should be made to
15536:    authenticate user using default authentication method, and allow
15537:    account creation if username does not have account in the domain).
15538: $clientcancheckhost is optional (value is 1 if checking whether the
15539:    server can host will occur on the client side in lonauth.pm).   
15540: 
15541: =item *
15542: X<homeserver()>
15543: B<homeserver($uname,$udom)>: find the server which has
15544: the user's directory and files (there must be only one), this caches
15545: the answer, and also caches if there is a borken connection.
15546: 
15547: =item *
15548: X<idget()>
15549: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15550: a list of student/employee IDs or clicker IDs
15551: (student/employee IDs are a unique resource in a domain, there must be 
15552: only 1 ID per username, and only 1 username per ID in a specific domain).
15553: clickerIDs are not necessarily unique, as students might share clickers.
15554: (returns hash: id=>name,id=>name)
15555: 
15556: =item *
15557: X<idrget()>
15558: B<idrget($udom,@unames)>: find the IDs behind a list of
15559: usernames (returns hash: name=>id,name=>id)
15560: 
15561: =item *
15562: X<idput()>
15563: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15564: names and associated student/employee IDs or clicker IDs.
15565: 
15566: =item *
15567: X<iddel()>
15568: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15569: student/employee ID or clicker ID username look-ups from domain.
15570: The homeserver ($uhome) and namespace ($namespace) are optional.
15571: If no $uhome is provided, it will be determined usig &homeserver()
15572: for each user.  If no $namespace is provided, the default is ids.
15573: 
15574: =item *
15575: X<updateclickers()>
15576: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15577: clicker ID-to-username look-ups in clickers.db on library server.
15578: Permitted actions are add or del (i.e., add or delete). The 
15579: clickers.db contains clickerID as keys (escaped), and each corresponding
15580: value is an escaped comma-separated list of usernames (for whom the
15581: library server is the homeserver), who registered that particular ID.
15582: If $critical is true, the update will be sent via &critical, otherwise
15583: &reply() will be used.
15584: 
15585: =item *
15586: X<rolesinit()>
15587: B<rolesinit($udom,$username)>: get user privileges.
15588: returns user role, first access and timer interval hashes
15589: 
15590: =item *
15591: X<privileged()>
15592: B<privileged($username,$domain)>: returns a true if user has a
15593: privileged and active role (i.e. su or dc), false otherwise.
15594: 
15595: =item *
15596: X<getsection()>
15597: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15598: course $cname, return section name/number or '' for "not in course"
15599: and '-1' for "no section"
15600: 
15601: =item *
15602: X<userenvironment()>
15603: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15604: passed in @what from the requested user's environment, returns a hash
15605: 
15606: =item * 
15607: X<userlog_query()>
15608: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15609: activity.log file. %filters defines filters applied when parsing the
15610: log file. These can be start or end timestamps, or the type of action
15611: - log to look for Login or Logout events, check for Checkin or
15612: Checkout, role for role selection. The response is in the form
15613: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15614: escaped strings of the action recorded in the activity.log file.
15615: 
15616: =back
15617: 
15618: =head2 User Roles
15619: 
15620: =over 4
15621: 
15622: =item *
15623: 
15624: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15625: returns codes for allowed actions.
15626: 
15627: The first argument is required, all others are optional.
15628: 
15629: $priv is the privilege being checked.
15630: $uri contains additional information about what is being checked for access (e.g.,
15631: URL, course ID etc.). 
15632: $symb is the unique resource instance identifier in a course; if needed,
15633: but not provided, it will be retrieved via a call to &symbread(). 
15634: $role is the role for which a priv is being checked (only used if priv is evb). 
15635: $clientip is the user's IP address (only used when checking for access to portfolio 
15636: files).
15637: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15638: prevents recursive calls to &allowed.
15639: 
15640:  F: full access
15641:  U,I,K: authentication modes (cxx only)
15642:  '': forbidden
15643:  1: user needs to choose course
15644:  2: browse allowed
15645:  A: passphrase authentication needed
15646:  B: access temporarily blocked because of a blocking event in a course.
15647:  D: access blocked because access is required via session initiated via deep-link 
15648: 
15649: =item *
15650: 
15651: constructaccess($url,$setpriv) : check for access to construction space URL
15652: 
15653: See if the owner domain and name in the URL match those in the
15654: expected environment.  If so, return three element list
15655: ($ownername,$ownerdomain,$ownerhome).
15656: 
15657: Otherwise return the null string.
15658: 
15659: If second argument 'setpriv' is true, it assigns the privileges,
15660: and returns the same three element list, unless the owner has
15661: blocked "ad hoc" Domain Coordinator access to the Author Space,
15662: in which case the null string is returned.
15663: 
15664: =item *
15665: 
15666: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15667: define a custom role rolename set privileges in format of lonTabs/roles.tab
15668: for system, domain, and course level. $uname and $udom are optional (current
15669: user's username and domain will be used when either of $uname or $udom are absent.
15670: 
15671: =item *
15672: 
15673: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15674: (rolesplain.tab); plain text explanation of a user role term.
15675: $type is Course (default) or Community.
15676: If $forcedefault evaluates to true, text returned will be default 
15677: text for $type. Otherwise, if this is a course, the text returned 
15678: will be a custom name for the role (if defined in the course's 
15679: environment).  If no custom name is defined the default is returned.
15680:    
15681: =item *
15682: 
15683: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15684: All arguments are optional. Returns a hash of a roles, either for
15685: co-author/assistant author roles for a user's Construction Space
15686: (default), or if $context is 'userroles', roles for the user himself,
15687: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15688: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15689: For each key, value is set to colon-separated start and end times for
15690: the role.  If no username and domain are specified, will default to
15691: current user/domain. Types, roles, and roledoms are references to arrays
15692: of role statuses (active, future or previous), roles 
15693: (e.g., cc,in, st etc.) and domains of the roles which can be used
15694: to restrict the list of roles reported. If no array ref is 
15695: provided for types, will default to return only active roles.
15696: 
15697: =item *
15698: 
15699: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15700: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15701: 
15702: Additional optional arguments are: $type (if role checking is to be restricted 
15703: to certain user status types -- previous (expired roles), active (currently
15704: available roles) or future (roles available in the future), and
15705: $hideprivileged -- if true will not report course roles for users who
15706: have active Domain Coordinator role in course's domain or in additional
15707: domains (specified in 'Domains to check for privileged users' in course
15708: environment -- set via:  Course Settings -> Classlists and staff listing).
15709: 
15710: =item *
15711: 
15712: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15713: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15714: $possdomains and $possroles are optional array refs -- to domains to check and
15715: roles to check.  If $possdomains is not specified, a dump will be done of the
15716: users' roles.db to check for a dc or su role in any domain. This can be
15717: time consuming if &privileged is called repeatedly (e.g., when displaying a
15718: classlist), so in such cases, supplying a $possdomains array is preferred, as
15719: this then allows &privileged_by_domain() to be used, which caches the identity
15720: of privileged users, eliminating the need for repeated calls to &dump().
15721: 
15722: =item *
15723: 
15724: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15725: where the outer hash keys are domains specified in the $possdomains array ref,
15726: next inner hash keys are privileged roles specified in the $roles array ref,
15727: and the innermost hash contains key = value pairs for username:domain = end:start
15728: for active or future "privileged" users with that role in that domain. To avoid
15729: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15730: innerhash are cached using priv_$role and $dom as the identifiers.
15731: 
15732: =back
15733: 
15734: =head2 User Modification
15735: 
15736: =over 4
15737: 
15738: =item *
15739: 
15740: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15741: user for the level given by URL.  Optional start and end dates (leave empty
15742: string or zero for "no date")
15743: 
15744: =item *
15745: 
15746: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15747: change a users, password, possible return values are: ok,
15748: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15749: refused
15750: 
15751: =item *
15752: 
15753: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15754: 
15755: =item *
15756: 
15757: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15758:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15759: 
15760: will update user information (firstname,middlename,lastname,generation,
15761: permanentemail), and if forceid is true, student/employee ID also.
15762: A user's institutional affiliation(s) can also be updated.
15763: User information fields will not be overwritten with empty entries 
15764: unless the field is included in the $candelete array reference.
15765: This array is included when a single user is modified via "Manage Users",
15766: or when Autoupdate.pl is run by cron in a domain.
15767: 
15768: =item *
15769: 
15770: modifystudent
15771: 
15772: modify a student's enrollment and identification information.
15773: The course id is resolved based on the current user's environment.  
15774: This means the invoking user must be a course coordinator or otherwise
15775: associated with a course.
15776: 
15777: This call is essentially a wrapper for lonnet::modifyuser and
15778: lonnet::modify_student_enrollment
15779: 
15780: Inputs: 
15781: 
15782: =over 4
15783: 
15784: =item B<$udom> Student's loncapa domain
15785: 
15786: =item B<$uname> Student's loncapa login name
15787: 
15788: =item B<$uid> Student/Employee ID
15789: 
15790: =item B<$umode> Student's authentication mode
15791: 
15792: =item B<$upass> Student's password
15793: 
15794: =item B<$first> Student's first name
15795: 
15796: =item B<$middle> Student's middle name
15797: 
15798: =item B<$last> Student's last name
15799: 
15800: =item B<$gene> Student's generation
15801: 
15802: =item B<$usec> Student's section in course
15803: 
15804: =item B<$end> Unix time of the roles expiration
15805: 
15806: =item B<$start> Unix time of the roles start date
15807: 
15808: =item B<$forceid> If defined, allow $uid to be changed
15809: 
15810: =item B<$desiredhome> server to use as home server for student
15811: 
15812: =item B<$email> Student's permanent e-mail address
15813: 
15814: =item B<$type> Type of enrollment (auto or manual)
15815: 
15816: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15817: 
15818: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15819: 
15820: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15821: 
15822: =item B<$context> role change context (shown in User Management Logs display in a course)
15823: 
15824: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15825: 
15826: =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.
15827: 
15828: =back
15829: 
15830: =item *
15831: 
15832: modify_student_enrollment
15833: 
15834: Change a student's enrollment status in a class.  The environment variable
15835: 'role.request.course' must be defined for this function to proceed.
15836: 
15837: Inputs:
15838: 
15839: =over 4
15840: 
15841: =item $udom, student's domain
15842: 
15843: =item $uname, student's name
15844: 
15845: =item $uid, student's user id
15846: 
15847: =item $first, student's first name
15848: 
15849: =item $middle
15850: 
15851: =item $last
15852: 
15853: =item $gene
15854: 
15855: =item $usec
15856: 
15857: =item $end
15858: 
15859: =item $start
15860: 
15861: =item $type
15862: 
15863: =item $locktype
15864: 
15865: =item $cid
15866: 
15867: =item $selfenroll
15868: 
15869: =item $context
15870: 
15871: =item $credits, number of credits student will earn from this class
15872: 
15873: =item $instsec, institutional course section code for student
15874: 
15875: =back
15876: 
15877: 
15878: =item *
15879: 
15880: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15881: custom role; give a custom role to a user for the level given by URL.  Specify
15882: name and domain of role author, and role name
15883: 
15884: =item *
15885: 
15886: revokerole($udom,$uname,$url,$role) : revoke a role for url
15887: 
15888: =item *
15889: 
15890: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15891: 
15892: =back
15893: 
15894: =head2 Course Infomation
15895: 
15896: =over 4
15897: 
15898: =item *
15899: 
15900: coursedescription($courseid,$options) : returns a hash of information about the
15901: specified course id, including all environment settings for the
15902: course, the description of the course will be in the hash under the
15903: key 'description'
15904: 
15905: $options is an optional parameter that if supplied is a hash reference that controls
15906: what how this function works.  It has the following key/values:
15907: 
15908: =over 4
15909: 
15910: =item freshen_cache
15911: 
15912: If defined, and the environment cache for the course is valid, it is 
15913: returned in the returned hash.
15914: 
15915: =item one_time
15916: 
15917: If defined, the last cache time is set to _now_
15918: 
15919: =item user
15920: 
15921: If defined, the supplied username is used instead of the current user.
15922: 
15923: 
15924: =back
15925: 
15926: =item *
15927: 
15928: resdata($name,$domain,$type,@which) : request for current parameter
15929: setting for a specific $type, where $type is either 'course' or 'user',
15930: @what should be a list of parameters to ask about. This routine caches
15931: answers for 10 minutes.
15932: 
15933: =item *
15934: 
15935: get_courseresdata($courseid, $domain) : dump the entire course resource
15936: data base, returning a hash that is keyed by the resource name and has
15937: values that are the resource value.  I believe that the timestamps and
15938: versions are also returned.
15939: 
15940: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15941: supplemental content area. This routine caches the number of files for 
15942: 10 minutes.
15943: 
15944: =back
15945: 
15946: =head2 Course Modification
15947: 
15948: =over 4
15949: 
15950: =item *
15951: 
15952: writecoursepref($courseid,%prefs) : write preferences (environment
15953: database) for a course
15954: 
15955: =item *
15956: 
15957: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15958: 
15959: =item *
15960: 
15961: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15962: 
15963: =item *
15964: 
15965: is_course($courseid), is_course($cdom, $cnum)
15966: 
15967: Accepts either a combined $courseid (in the form of domain_courseid) or the
15968: two component version $cdom, $cnum. It checks if the specified course exists.
15969: 
15970: Returns:
15971:     undef if the course doesn't exist, otherwise
15972:     in scalar context the combined courseid.
15973:     in list context the two components of the course identifier, domain and 
15974:     courseid.    
15975: 
15976: =back
15977: 
15978: =head2 Bubblesheet Configuration
15979: 
15980: =over 4
15981: 
15982: =item *
15983: 
15984: get_scantron_config($which)
15985: 
15986: $which - the name of the configuration to parse from the file.
15987: 
15988: Parses and returns the bubblesheet configuration line selected as a
15989: hash of configuration file fields.
15990: 
15991: 
15992: Returns:
15993:     If the named configuration is not in the file, an empty
15994:     hash is returned.
15995: 
15996:     a hash with the fields
15997:       name         - internal name for the this configuration setup
15998:       description  - text to display to operator that describes this config
15999:       CODElocation - if 0 or the string 'none'
16000:                           - no CODE exists for this config
16001:                      if -1 || the string 'letter'
16002:                           - a CODE exists for this config and is
16003:                             a string of letters
16004:                      Unsupported value (but planned for future support)
16005:                           if a positive integer
16006:                                - The CODE exists as the first n items from
16007:                                  the question section of the form
16008:                           if the string 'number'
16009:                                - The CODE exists for this config and is
16010:                                  a string of numbers
16011:       CODEstart   - (only matter if a CODE exists) column in the line where
16012:                      the CODE starts
16013:       CODElength  - length of the CODE
16014:       IDstart     - column where the student/employee ID starts
16015:       IDlength    - length of the student/employee ID info
16016:       Qstart      - column where the information from the bubbled
16017:                     'questions' start
16018:       Qlength     - number of columns comprising a single bubble line from
16019:                     the sheet. (usually either 1 or 10)
16020:       Qon         - either a single character representing the character used
16021:                     to signal a bubble was chosen in the positional setup, or
16022:                     the string 'letter' if the letter of the chosen bubble is
16023:                     in the final, or 'number' if a number representing the
16024:                     chosen bubble is in the file (1->A 0->J)
16025:       Qoff        - the character used to represent that a bubble was
16026:                     left blank
16027:       PaperID     - if the scanning process generates a unique number for each
16028:                     sheet scanned the column that this ID number starts in
16029:       PaperIDlength - number of columns that comprise the unique ID number
16030:                       for the sheet of paper
16031:       FirstName   - column that the first name starts in
16032:       FirstNameLength - number of columns that the first name spans
16033:       LastName    - column that the last name starts in
16034:       LastNameLength - number of columns that the last name spans
16035:       BubblesPerRow - number of bubbles available in each row used to
16036:                       bubble an answer. (If not specified, 10 assumed).
16037: 
16038: 
16039: =item *
16040: 
16041: get_scantronformat_file($cdom)
16042: 
16043: $cdom - the course's domain (optional); if not supplied, uses
16044: domain for current $env{'request.course.id'}.
16045: 
16046: Returns an array containing lines from the scantron format file for
16047: the domain of the course.
16048: 
16049: If a url for a custom.tab file is listed in domain's configuration.db,
16050: lines are from this file.
16051: 
16052: Otherwise, if a default.tab has been published in RES space by the
16053: domainconfig user, lines are from this file.
16054: 
16055: Otherwise, fall back to getting lines from the legacy file on the
16056: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16057: 
16058: =back
16059: 
16060: =head2 Resource Subroutines
16061: 
16062: =over 4
16063: 
16064: =item *
16065: 
16066: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16067: 
16068: =item *
16069: 
16070: repcopy($filename) : subscribes to the requested file, and attempts to
16071: replicate from the owning library server, Might return
16072: 'unavailable', 'not_found', 'forbidden', 'ok', or
16073: 'bad_request', also attempts to grab the metadata for the
16074: resource. Expects the local filesystem pathname
16075: (/home/httpd/html/res/....)
16076: 
16077: =back
16078: 
16079: =head2 Resource Information
16080: 
16081: =over 4
16082: 
16083: =item *
16084: 
16085: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16086: and returns the value of a variety of different possible values,
16087: $varname should be a request string, and the other parameters can be
16088: used to specify who and what one is asking about. Ordinarily, $cid 
16089: does not need to be specified, as it is retrived from 
16090: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16091: within lonuserstate::loadmap() when initializing a course, before
16092: $env{'request.course.id'} has been set, so it needs to be provided
16093: in that one case.
16094: 
16095: Possible values for $varname are environment.lastname (or other item
16096: from the envirnment hash), user.name (or someother aspect about the
16097: user), resource.0.maxtries (or some other part and parameter of a
16098: resource)
16099: 
16100: =item *
16101: 
16102: directcondval($number) : get current value of a condition; reads from a state
16103: string
16104: 
16105: =item *
16106: 
16107: condval($condidx) : value of condition index based on state
16108: 
16109: =item *
16110: 
16111: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16112: resource's metadata, $what should be either a specific key, or either
16113: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16114: packages that this resource currently uses, the last 3 arguments are 
16115: only used internally for recursive metadata.
16116: 
16117: the toolsymb is only used where the uri is for an external tool (for which
16118: the uri as well as the symb are guaranteed to be unique).
16119: 
16120: this function automatically caches all requests except any made recursively
16121: to retrieve a list of metadata keys for an imported library file ($liburi is 
16122: defined).
16123: 
16124: =item *
16125: 
16126: metadata_query($query,$custom,$customshow) : make a metadata query against the
16127: network of library servers; returns file handle of where SQL and regex results
16128: will be stored for query
16129: 
16130: =item *
16131: 
16132: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16133: return symbolic list entry (all arguments optional). 
16134: 
16135: Args: filename is the filename (including path) for the file for which a symb 
16136: is required; donotrecurse, if true will prevent calls to allowed() being made 
16137: to check access status if more than one resource was found in the bighash 
16138: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16139: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16140: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16141: cause possible symbs to be checked to determine if they are subject to content
16142: blocking, if so they will not be included as possible symbs; possibles is a
16143: ref to a hash, which, as a side effect, will be populated with all possible 
16144: symbs (content blocking not tested).
16145:  
16146: returns the data handle
16147: 
16148: =item *
16149: 
16150: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16151: and is a possible symb for the URL in $thisfn, and if is an encrypted
16152: resource that the user accessed using /enc/ returns a 1 on success, 0
16153: on failure, user must be in a course, as it assumes the existence of
16154: the course initial hash, and uses $env('request.course.id'}.  The third
16155: arg is an optional reference to a scalar.  If this arg is passed in the 
16156: call to symbverify, it will be set to 1 if the symb has been set to be 
16157: encrypted; otherwise it will be null.  
16158: 
16159: =item *
16160: 
16161: symbclean($symb) : removes versions numbers from a symb, returns the
16162: cleaned symb
16163: 
16164: =item *
16165: 
16166: is_on_map($uri) : checks if the $uri is somewhere on the current
16167: course map, user must be in a course for it to work.
16168: 
16169: =item *
16170: 
16171: numval($salt) : return random seed value (addend for rndseed)
16172: 
16173: =item *
16174: 
16175: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16176: a random seed, all arguments are optional, if they aren't sent it uses the
16177: environment to derive them. Note: if symb isn't sent and it can't get one
16178: from &symbread it will use the current time as its return value
16179: 
16180: =item *
16181: 
16182: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16183: unfakeable, receipt
16184: 
16185: =item *
16186: 
16187: receipt() : API to ireceipt working off of env values; given out to users
16188: 
16189: =item *
16190: 
16191: countacc($url) : count the number of accesses to a given URL
16192: 
16193: =item *
16194: 
16195: 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
16196: 
16197: =item *
16198: 
16199: 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)
16200: 
16201: =item *
16202: 
16203: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16204: 
16205: =item *
16206: 
16207: devalidate($symb) : devalidate temporary spreadsheet calculations,
16208: forcing spreadsheet to reevaluate the resource scores next time.
16209: 
16210: =item * 
16211: 
16212: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16213: when viewing in course context.
16214: 
16215:  input: six args -- filename (decluttered), course number, course domain,
16216:                     url, symb (if registered) and group (if this is a 
16217:                     group item -- e.g., bulletin board, group page etc.).
16218: 
16219:  output: array of five scalars --
16220:          $cfile -- url for file editing if editable on current server
16221:          $home -- homeserver of resource (i.e., for author if published,
16222:                                           or course if uploaded.).
16223:          $switchserver --  1 if server switch will be needed.
16224:          $forceedit -- 1 if icon/link should be to go to edit mode 
16225:          $forceview -- 1 if icon/link should be to go to view mode
16226: 
16227: =item *
16228: 
16229: is_course_upload($file,$cnum,$cdom)
16230: 
16231: Used in course context to determine if current file was uploaded to 
16232: the course (i.e., would be found in /userfiles/docs on the course's 
16233: homeserver.
16234: 
16235:   input: 3 args -- filename (decluttered), course number and course domain.
16236:   output: boolean -- 1 if file was uploaded.
16237: 
16238: =back
16239: 
16240: =head2 Storing/Retreiving Data
16241: 
16242: =over 4
16243: 
16244: =item *
16245: 
16246: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16247: permanently for this url; hashref needs to be given and should be a \%hashname;
16248: the remaining args aren't required and if they aren't passed or are '' they will
16249: be derived from the env (with the exception of $laststore, which is an 
16250: optional arg used when a user's submission is stored in grading).
16251: $laststore is $version=$timestamp, where $version is the most recent version
16252: number retrieved for the corresponding $symb in the $namespace db file, and
16253: $timestamp is the timestamp for that transaction (UNIX time).
16254: $laststore is currently only passed when cstore() is called by 
16255: structuretags::finalize_storage().
16256: 
16257: =item *
16258: 
16259: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16260: but uses critical subroutine
16261: 
16262: =item *
16263: 
16264: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16265: all args are optional
16266: 
16267: =item *
16268: 
16269: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16270: dumps the complete (or key matching regexp) namespace into a hash
16271: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16272: normally &store()ed into
16273: 
16274: $range should be either an integer '100' (give me the first 100
16275:                                            matching records)
16276:               or be  two integers sperated by a - with no spaces
16277:                  '30-50' (give me the 30th through the 50th matching
16278:                           records)
16279: 
16280: 
16281: =item *
16282: 
16283: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16284: replaces a &store() version of data with a replacement set of data
16285: for a particular resource in a namespace passed in the $storehash hash 
16286: reference. If $tolog is true, the transaction is logged in the courselog
16287: with an action=PUTSTORE.
16288: 
16289: =item *
16290: 
16291: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16292: works very similar to store/cstore, but all data is stored in a
16293: temporary location and can be reset using tmpreset, $storehash should
16294: be a hash reference, returns nothing on success
16295: 
16296: =item *
16297: 
16298: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16299: similar to restore, but all data is stored in a temporary location and
16300: can be reset using tmpreset. Returns a hash of values on success,
16301: error string otherwise.
16302: 
16303: =item *
16304: 
16305: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16306: deltes all keys for $symb form the temporary storage hash.
16307: 
16308: =item *
16309: 
16310: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16311: reference filled in from namesp ($udom and $uname are optional)
16312: 
16313: =item *
16314: 
16315: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16316: namesp ($udom and $uname are optional)
16317: 
16318: =item *
16319: 
16320: dump($namespace,$udom,$uname,$regexp,$range) : 
16321: dumps the complete (or key matching regexp) namespace into a hash
16322: ($udom, $uname, $regexp, $range are optional)
16323: 
16324: $range should be either an integer '100' (give me the first 100
16325:                                            matching records)
16326:               or be  two integers sperated by a - with no spaces
16327:                  '30-50' (give me the 30th through the 50th matching
16328:                           records)
16329: =item *
16330: 
16331: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16332: $store can be a scalar, an array reference, or if the amount to be 
16333: incremented is > 1, a hash reference.
16334: 
16335: ($udom and $uname are optional)
16336: 
16337: =item *
16338: 
16339: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16340: ($udom and $uname are optional)
16341: 
16342: =item *
16343: 
16344: cput($namespace,$storehash,$udom,$uname) : critical put
16345: ($udom and $uname are optional)
16346: 
16347: =item *
16348: 
16349: newput($namespace,$storehash,$udom,$uname) :
16350: 
16351: Attempts to store the items in the $storehash, but only if they don't
16352: currently exist, if this succeeds you can be certain that you have 
16353: successfully created a new key value pair in the $namespace db.
16354: 
16355: 
16356: Args:
16357:  $namespace: name of database to store values to
16358:  $storehash: hashref to store to the db
16359:  $udom: (optional) domain of user containing the db
16360:  $uname: (optional) name of user caontaining the db
16361: 
16362: Returns:
16363:  'ok' -> succeeded in storing all keys of $storehash
16364:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16365:                         least <key> already existed in the db (other
16366:                         requested keys may also already exist)
16367:  'error: <msg>' -> unable to tie the DB or other error occurred
16368:  'con_lost' -> unable to contact request server
16369:  'refused' -> action was not allowed by remote machine
16370: 
16371: 
16372: =item *
16373: 
16374: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16375: reference filled in from namesp (encrypts the return communication)
16376: ($udom and $uname are optional)
16377: 
16378: =item *
16379: 
16380: log($udom,$name,$home,$message) : write to permanent log for user; use
16381: critical subroutine
16382: 
16383: =item *
16384: 
16385: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16386: array reference filled in from namespace found in domain level on either
16387: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16388: 
16389: =item *
16390: 
16391: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16392: domain level either on specified domain server ($uhome) or primary domain 
16393: server ($udom and $uhome are optional)
16394: 
16395: =item * 
16396: 
16397: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16398: for: authentication, language, quotas, timezone, date locale, and portal URL in
16399: the target domain.
16400: 
16401: May also include additional key => value pairs for the following groups:
16402: 
16403: =over
16404: 
16405: =item
16406: disk quotas (MB allocated by default to portfolios and authoring spaces).
16407: 
16408: =over
16409: 
16410: =item defaultquota, authorquota
16411: 
16412: =back
16413: 
16414: =item
16415: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16416: portfolio for users).
16417: 
16418: =over
16419: 
16420: =item
16421: aboutme, blog, webdav, portfolio
16422: 
16423: =back
16424: 
16425: =item
16426: requestcourses: ability to request courses, and how requests are processed.
16427: 
16428: =over
16429: 
16430: =item
16431: official, unofficial, community, textbook, placement
16432: 
16433: =back
16434: 
16435: =item
16436: inststatus: types of institutional affiliation, and order in which they are displayed.
16437: 
16438: =over
16439: 
16440: =item
16441: inststatustypes, inststatusorder, inststatusguest
16442: 
16443: =back
16444: 
16445: =item
16446: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16447: for course's uploaded content.
16448: 
16449: =over
16450: 
16451: =item
16452: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16453: communityquota, textbookquota, placementquota
16454: 
16455: =back
16456: 
16457: =item
16458: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16459: on your servers.
16460: 
16461: =over
16462: 
16463: =item 
16464: remotesessions, hostedsessions
16465: 
16466: =back
16467: 
16468: =back
16469: 
16470: In cases where a domain coordinator has never used the "Set Domain Configuration"
16471: utility to create a configuration.db file on a domain's primary library server 
16472: only the following domain defaults: auth_def, auth_arg_def, lang_def
16473: -- corresponding values are authentication type (internal, krb4, krb5,
16474: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16475: will be available. Values are retrieved from cache (if current), unless the
16476: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16477: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16478: 
16479: Typical usage:
16480: 
16481: %domdefaults = &get_domain_defaults($target_domain);
16482: 
16483: =back
16484: 
16485: =head2 Network Status Functions
16486: 
16487: =over 4
16488: 
16489: =item *
16490: 
16491: dirlist() : return directory list based on URI (first arg).
16492: 
16493: Inputs: 1 required, 5 optional.
16494: 
16495: =over
16496: 
16497: =item 
16498: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16499: 
16500: =item
16501: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16502: 
16503: =item
16504: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16505: 
16506: =item
16507: $getpropath - boolean: 1 if prepend path using &propath(). 
16508: 
16509: =item
16510: $getuserdir - boolean: 1 if prepend path for "userfiles".
16511: 
16512: =item 
16513: $alternateRoot - path to prepend in place of path from $uri.
16514: 
16515: =back
16516: 
16517: Returns: Array of up to two items.
16518: 
16519: =over
16520: 
16521: a reference to an array of files/subdirectories
16522: 
16523: =over
16524: 
16525: Each element in the array of files/subdirectories is a & separated list of
16526: item name and the result of running stat on the item.  If dirlist was requested
16527: for a file instead of a directory, the item name will be ''. For a directory 
16528: listing, if the item is a metadata file, the element will end &N&M 
16529: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16530: default copyright set (1).  
16531: 
16532: =back
16533: 
16534: a scalar containing error condition (if encountered).
16535: 
16536: =over
16537: 
16538: =item 
16539: no_host (no homeserver identified for $username:$domain).
16540: 
16541: =item 
16542: no_such_host (server contacted for listing not identified as valid host).
16543: 
16544: =item 
16545: con_lost (connection to remote server failed).
16546: 
16547: =item 
16548: refused (invalid $username:$domain received on lond side).
16549: 
16550: =item 
16551: no_such_dir (directory at specified path on lond side does not exist). 
16552: 
16553: =item 
16554: empty (directory at specified path on lond side is empty).
16555: 
16556: =over
16557: 
16558: This is currently not encountered because the &ls3, &ls2, 
16559: &ls (_handler) routines on the lond side do not filter out
16560: . and .. from a directory listing. 
16561: 
16562: =back
16563: 
16564: =back
16565: 
16566: =back
16567: 
16568: =item *
16569: 
16570: spareserver() : find server with least workload from spare.tab
16571: 
16572: 
16573: =item *
16574: 
16575: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16576: if there is no corresponding loncapa host.
16577: 
16578: =back
16579: 
16580: 
16581: =head2 Apache Request
16582: 
16583: =over 4
16584: 
16585: =item *
16586: 
16587: ssi($url,%hash) : server side include, does a complete request cycle on url to
16588: localhost, posts hash
16589: 
16590: =back
16591: 
16592: =head2 Data to String to Data
16593: 
16594: =over 4
16595: 
16596: =item *
16597: 
16598: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16599: and '&' separators, supports elements that are arrayrefs and hashrefs
16600: 
16601: =item *
16602: 
16603: hashref2str($hashref) : convert a hashref into a string complete with
16604: escaping and '=' and '&' separators, supports elements that are
16605: arrayrefs and hashrefs
16606: 
16607: =item *
16608: 
16609: arrayref2str($arrayref) : convert an arrayref into a string complete
16610: with escaping and '&' separators, supports elements that are arrayrefs
16611: and hashrefs
16612: 
16613: =item *
16614: 
16615: str2hash($string) : convert string to hash using unescaping and
16616: splitting on '=' and '&', supports elements that are arrayrefs and
16617: hashrefs
16618: 
16619: =item *
16620: 
16621: str2array($string) : convert string to hash using unescaping and
16622: splitting on '&', supports elements that are arrayrefs and hashrefs
16623: 
16624: =back
16625: 
16626: =head2 Logging Routines
16627: 
16628: 
16629: These routines allow one to make log messages in the lonnet.log and
16630: lonnet.perm logfiles.
16631: 
16632: =over 4
16633: 
16634: =item *
16635: 
16636: logtouch() : make sure the logfile, lonnet.log, exists
16637: 
16638: =item *
16639: 
16640: logthis() : append message to the normal lonnet.log file, it gets
16641: preiodically rolled over and deleted.
16642: 
16643: =item *
16644: 
16645: logperm() : append a permanent message to lonnet.perm.log, this log
16646: file never gets deleted by any automated portion of the system, only
16647: messages of critical importance should go in here.
16648: 
16649: 
16650: =back
16651: 
16652: =head2 General File Helper Routines
16653: 
16654: =over 4
16655: 
16656: =item *
16657: 
16658: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16659: (a) files in /uploaded
16660:   (i) If a local copy of the file exists - 
16661:       compares modification date of local copy with last-modified date for 
16662:       definitive version stored on home server for course. If local copy is 
16663:       stale, requests a new version from the home server and stores it. 
16664:       If the original has been removed from the home server, then local copy 
16665:       is unlinked.
16666:   (ii) If local copy does not exist -
16667:       requests the file from the home server and stores it. 
16668:   
16669:   If $caller is 'uploadrep':  
16670:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16671:     for request for files originally uploaded via DOCS. 
16672:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16673:   
16674:   Otherwise:
16675:      This indicates a call from the content generation phase of the request.
16676:      -  returns the entire contents of the file or -1.
16677:      
16678: (b) files in /res
16679:    - returns the entire contents of a file or -1; 
16680:    it properly subscribes to and replicates the file if neccessary.
16681: 
16682: 
16683: =item *
16684: 
16685: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16686:                   reference
16687: 
16688: returns either a stat() list of data about the file or an empty list
16689: if the file doesn't exist or couldn't find out about it (connection
16690: problems or user unknown)
16691: 
16692: =item *
16693: 
16694: filelocation($dir,$file) : returns file system location of a file
16695: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16696: directory that relative $file lookups are to looked in ($dir of /a/dir
16697: and a file of ../bob will become /a/bob)
16698: 
16699: =item *
16700: 
16701: hreflocation($dir,$file) : returns file system location or a URL; same as
16702: filelocation except for hrefs
16703: 
16704: =item *
16705: 
16706: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16707: also removes beginning /home/httpd/html unless /priv/ follows it.
16708: 
16709: =back
16710: 
16711: =head2 Usererfile file routines (/uploaded*)
16712: 
16713: =over 4
16714: 
16715: =item *
16716: 
16717: userfileupload(): main rotine for putting a file in a user or course's
16718:                   filespace, arguments are,
16719: 
16720:  formname - required - this is the name of the element in $env where the
16721:            filename, and the contents of the file to create/modifed exist
16722:            the filename is in $env{'form.'.$formname.'.filename'} and the
16723:            contents of the file is located in $env{'form.'.$formname}
16724:  context - if coursedoc, store the file in the course of the active role
16725:              of the current user; 
16726:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16727:            if 'canceloverwrite': delete file in tmp/overwrites directory
16728:  subdir - required - subdirectory to put the file in under ../userfiles/
16729:          if undefined, it will be placed in "unknown"
16730: 
16731:  (This routine calls clean_filename() to remove any dangerous
16732:  characters from the filename, and then calls finuserfileupload() to
16733:  complete the transaction)
16734: 
16735:  returns either the url of the uploaded file (/uploaded/....) if successful
16736:  and /adm/notfound.html if unsuccessful
16737: 
16738: =item *
16739: 
16740: clean_filename(): routine for cleaing a filename up for storage in
16741:                  userfile space, argument is:
16742: 
16743:  filename - proposed filename
16744: 
16745: returns: the new clean filename
16746: 
16747: =item *
16748: 
16749: finishuserfileupload(): routine that creates and sends the file to
16750: userspace, probably shouldn't be called directly
16751: 
16752:   docuname: username or courseid of destination for the file
16753:   docudom: domain of user/course of destination for the file
16754:   formname: same as for userfileupload()
16755:   fname: filename (including subdirectories) for the file
16756:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16757:           if hashref, and context is scantron, will convert csv format to standard format
16758:   allfiles: reference to hash used to store objects found by parser
16759:   codebase: reference to hash used for codebases of java objects found by parser
16760:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16761:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16762:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16763:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16764:   context: if 'overwrite', will move the uploaded file from its temporary location to
16765:             userfiles to facilitate overwriting a previously uploaded file with same name.
16766:   mimetype: reference to scalar to accommodate mime type determined
16767:             from File::MMagic if $parser = parse.
16768: 
16769:  returns either the url of the uploaded file (/uploaded/....) if successful
16770:  and /adm/notfound.html if unsuccessful (or an error message if context 
16771:  was 'overwrite').
16772:  
16773: 
16774: =item *
16775: 
16776: renameuserfile(): renames an existing userfile to a new name
16777: 
16778:   Args:
16779:    docuname: username or courseid of destination for the file
16780:    docudom: domain of user/course of destination for the file
16781:    old: current file name (including any subdirs under userfiles)
16782:    new: desired file name (including any subdirs under userfiles)
16783: 
16784: =item *
16785: 
16786: mkdiruserfile(): creates a directory is a userfiles dir
16787: 
16788:   Args:
16789:    docuname: username or courseid of destination for the file
16790:    docudom: domain of user/course of destination for the file
16791:    dir: dir to create (including any subdirs under userfiles)
16792: 
16793: =item *
16794: 
16795: removeuserfile(): removes a file that exists in userfiles
16796: 
16797:   Args:
16798:    docuname: username or courseid of destination for the file
16799:    docudom: domain of user/course of destination for the file
16800:    fname: filname to delete (including any subdirs under userfiles)
16801: 
16802: =item *
16803: 
16804: removeuploadedurl(): convience function for removeuserfile()
16805: 
16806:   Args:
16807:    url:  a full /uploaded/... url to delete
16808: 
16809: =item * 
16810: 
16811: get_portfile_permissions():
16812:   Args:
16813:     domain: domain of user or course contain the portfolio files
16814:     user: name of user or num of course contain the portfolio files
16815:   Returns:
16816:     hashref of a dump of the proper file_permissions.db
16817:    
16818: 
16819: =item * 
16820: 
16821: get_access_controls():
16822: 
16823: Args:
16824:   current_permissions: the hash ref returned from get_portfile_permissions()
16825:   group: (optional) the group you want the files associated with
16826:   file: (optional) the file you want access info on
16827: 
16828: Returns:
16829:     a hash (keys are file names) of hashes containing
16830:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16831:         values are XML containing access control settings (see below) 
16832: 
16833: Internal notes:
16834: 
16835:  access controls are stored in file_permissions.db as key=value pairs.
16836:     key -> path to file/file_name\0uniqueID:scope_end_start
16837:         where scope -> public,guest,course,group,domains or users.
16838:               end -> UNIX time for end of access (0 -> no end date)
16839:               start -> UNIX time for start of access
16840: 
16841:     value -> XML description of access control
16842:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16843:             <start></start>
16844:             <end></end>
16845: 
16846:             <password></password>  for scope type = guest
16847: 
16848:             <domain></domain>     for scope type = course or group
16849:             <number></number>
16850:             <roles id="">
16851:              <role></role>
16852:              <access></access>
16853:              <section></section>
16854:              <group></group>
16855:             </roles>
16856: 
16857:             <dom></dom>         for scope type = domains
16858: 
16859:             <users>             for scope type = users
16860:              <user>
16861:               <uname></uname>
16862:               <udom></udom>
16863:              </user>
16864:             </users>
16865:            </scope> 
16866:               
16867:  Access data is also aggregated for each file in an additional key=value pair:
16868:  key -> path to file/file_name\0accesscontrol 
16869:  value -> reference to hash
16870:           hash contains key = value pairs
16871:           where key = uniqueID:scope_end_start
16872:                 value = UNIX time record was last updated
16873: 
16874:           Used to improve speed of look-ups of access controls for each file.  
16875:  
16876:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16877: 
16878: =item *
16879: 
16880: modify_access_controls():
16881: 
16882: Modifies access controls for a portfolio file
16883: Args
16884: 1. file name
16885: 2. reference to hash of required changes,
16886: 3. domain
16887: 4. username
16888:   where domain,username are the domain of the portfolio owner 
16889:   (either a user or a course) 
16890: 
16891: Returns:
16892: 1. result of additions or updates ('ok' or 'error', with error message). 
16893: 2. result of deletions ('ok' or 'error', with error message).
16894: 3. reference to hash of any new or updated access controls.
16895: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16896:    key = integer (inbound ID)
16897:    value = uniqueID
16898: 
16899: =item *
16900: 
16901: get_timebased_id():
16902: 
16903: Attempts to get a unique timestamp-based suffix for use with items added to a 
16904: course via the Course Editor (e.g., folders, composite pages, 
16905: group bulletin boards).
16906: 
16907: Args: (first three required; six others optional)
16908: 
16909: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16910:    docssequence, or name of group
16911: 
16912: 2. keyid (alphanumeric): name of temporary locking key in hash,
16913:    e.g., num, boardids
16914: 
16915: 3. namespace: name of gdbm file used to store suffixes already assigned;  
16916:    file will be named nohist_namespace.db
16917: 
16918: 4. cdom: domain of course; default is current course domain from %env
16919: 
16920: 5. cnum: course number; default is current course number from %env
16921: 
16922: 6. idtype: set to concat if an additional digit is to be appended to the 
16923:    unix timestamp to form the suffix, if the plain timestamp is already
16924:    in use.  Default is to not do this, but simply increment the unix 
16925:    timestamp by 1 until a unique key is obtained.
16926: 
16927: 7. who: holder of locking key; defaults to user:domain for user.
16928: 
16929: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
16930:    retrying); default is 3.
16931: 
16932: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
16933: 
16934: Returns:
16935: 
16936: 1. suffix obtained (numeric)
16937: 
16938: 2. result of deleting locking key (ok if deleted, or lock never obtained)
16939: 
16940: 3. error: contains (localized) error message if an error occurred.
16941: 
16942: 
16943: =back
16944: 
16945: =head2 HTTP Helper Routines
16946: 
16947: =over 4
16948: 
16949: =item *
16950: 
16951: escape() : unpack non-word characters into CGI-compatible hex codes
16952: 
16953: =item *
16954: 
16955: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
16956: 
16957: =back
16958: 
16959: =head1 PRIVATE SUBROUTINES
16960: 
16961: =head2 Underlying communication routines (Shouldn't call)
16962: 
16963: =over 4
16964: 
16965: =item *
16966: 
16967: subreply() : tries to pass a message to lonc, returns con_lost if incapable
16968: 
16969: =item *
16970: 
16971: reply() : uses subreply to send a message to remote machine, logs all failures
16972: 
16973: =item *
16974: 
16975: critical() : passes a critical message to another server; if cannot
16976: get through then place message in connection buffer directory and
16977: returns con_delayed, if incapable of saving message, returns
16978: con_failed
16979: 
16980: =item *
16981: 
16982: reconlonc() : tries to reconnect lonc client processes.
16983: 
16984: =back
16985: 
16986: =head2 Resource Access Logging
16987: 
16988: =over 4
16989: 
16990: =item *
16991: 
16992: flushcourselogs() : flush (save) buffer logs and access logs
16993: 
16994: =item *
16995: 
16996: courselog($what) : save message for course in hash
16997: 
16998: =item *
16999: 
17000: courseacclog($what) : save message for course using &courselog().  Perform
17001: special processing for specific resource types (problems, exams, quizzes, etc).
17002: 
17003: =item *
17004: 
17005: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17006: as a PerlChildExitHandler
17007: 
17008: =back
17009: 
17010: =head2 Other
17011: 
17012: =over 4
17013: 
17014: =item *
17015: 
17016: symblist($mapname,%newhash) : update symbolic storage links
17017: 
17018: =back
17019: 
17020: =cut
17021: 

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