File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1453: download - view: text, annotated - select for diffs
Mon May 10 18:13:50 2021 UTC (3 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Speed-up &allowed() by ignoring expired or future student or ta roles
  (unless current role) when checking for course.*.lock.sections in %env.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1453 2021/05/10 18:13:50 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:         if ($disk_env{'request.role'}) {
  744:             $userhashref->{'role'} = $disk_env{'request.role'};
  745:         }
  746:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  747:         if ($userhashref->{'lti'}) {
  748:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  749:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  750:         }
  751:     }
  752:     untie(%disk_env);
  753: 
  754:     return $handle;
  755: }
  756: 
  757: sub timed_flock {
  758:     my ($file,$lock_type) = @_;
  759:     my $failed=0;
  760:     eval {
  761: 	local $SIG{__DIE__}='DEFAULT';
  762: 	local $SIG{ALRM}=sub {
  763: 	    $failed=1;
  764: 	    die("failed lock");
  765: 	};
  766: 	alarm(13);
  767: 	flock($file,$lock_type);
  768: 	alarm(0);
  769:     };
  770:     if ($failed) {
  771: 	return undef;
  772:     } else {
  773: 	return 1;
  774:     }
  775: }
  776: 
  777: sub get_sessionfile_vars {
  778:     my ($handle,$lonidsdir,$storearr) = @_;
  779:     my %returnhash;
  780:     unless (ref($storearr) eq 'ARRAY') {
  781:         return %returnhash;
  782:     }
  783:     if (-l "$lonidsdir/$handle.id") {
  784:         my $link = readlink("$lonidsdir/$handle.id");
  785:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  786:             $handle = $1;
  787:         }
  788:     }
  789:     if ((-e "$lonidsdir/$handle.id") &&
  790:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  791:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  792:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  793:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  794:                 flock($idf,LOCK_SH);
  795:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  796:                         &GDBM_READER(),0640)) {
  797:                     foreach my $item (@{$storearr}) {
  798:                         $returnhash{$item} = $disk_env{$item};
  799:                     }
  800:                     untie(%disk_env);
  801:                 }
  802:             }
  803:         }
  804:     }
  805:     return %returnhash;
  806: }
  807: 
  808: # ---------------------------------------------------------- Append Environment
  809: 
  810: sub appenv {
  811:     my ($newenv,$roles) = @_;
  812:     if (ref($newenv) eq 'HASH') {
  813:         foreach my $key (keys(%{$newenv})) {
  814:             my $refused = 0;
  815: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  816:                 $refused = 1;
  817:                 if (ref($roles) eq 'ARRAY') {
  818:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  819:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  820:                         $refused = 0;
  821:                     }
  822:                 }
  823:             }
  824:             if ($refused) {
  825:                 &logthis("<font color=\"blue\">WARNING: ".
  826:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  827:                          .'</font>');
  828: 	        delete($newenv->{$key});
  829:             } else {
  830:                 $env{$key}=$newenv->{$key};
  831:             }
  832:         }
  833:         my $lonids = $perlvar{'lonIDsDir'};
  834:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  835:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  836:             if ($opened
  837: 	        && &timed_flock($env_file,LOCK_EX)
  838: 	        &&
  839: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  840: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  841: 	        while (my ($key,$value) = each(%{$newenv})) {
  842: 	            $disk_env{$key} = $value;
  843: 	        }
  844: 	        untie(%disk_env);
  845:             }
  846:         }
  847:     }
  848:     return 'ok';
  849: }
  850: # ----------------------------------------------------- Delete from Environment
  851: 
  852: sub delenv {
  853:     my ($delthis,$regexp,$roles) = @_;
  854:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  855:         my $refused = 1;
  856:         if (ref($roles) eq 'ARRAY') {
  857:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  858:             if (grep(/^\Q$role\E$/,@{$roles})) {
  859:                 $refused = 0;
  860:             }
  861:         }
  862:         if ($refused) {
  863:             &logthis("<font color=\"blue\">WARNING: ".
  864:                      "Attempt to delete from environment ".$delthis);
  865:             return 'error';
  866:         }
  867:     }
  868:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  869:     if ($opened
  870: 	&& &timed_flock($env_file,LOCK_EX)
  871: 	&&
  872: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  873: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  874: 	foreach my $key (keys(%disk_env)) {
  875: 	    if ($regexp) {
  876:                 if ($key=~/^$delthis/) {
  877:                     delete($env{$key});
  878:                     delete($disk_env{$key});
  879:                 } 
  880:             } else {
  881:                 if ($key=~/^\Q$delthis\E/) {
  882: 		    delete($env{$key});
  883: 		    delete($disk_env{$key});
  884: 	        }
  885:             }
  886: 	}
  887: 	untie(%disk_env);
  888:     }
  889:     return 'ok';
  890: }
  891: 
  892: sub get_env_multiple {
  893:     my ($name) = @_;
  894:     my @values;
  895:     if (defined($env{$name})) {
  896:         # exists is it an array
  897:         if (ref($env{$name})) {
  898:             @values=@{ $env{$name} };
  899:         } else {
  900:             $values[0]=$env{$name};
  901:         }
  902:     }
  903:     return(@values);
  904: }
  905: 
  906: # ------------------------------------------------------------------- Locking
  907: 
  908: sub set_lock {
  909:     my ($text)=@_;
  910:     $locknum++;
  911:     my $id=$$.'-'.$locknum;
  912:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  913:              'session.lock.'.$id => $text});
  914:     return $id;
  915: }
  916: 
  917: sub get_locks {
  918:     my $num=0;
  919:     my %texts=();
  920:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  921:        if ($lock=~/\w/) {
  922:           $num++;
  923:           $texts{$lock}=$env{'session.lock.'.$lock};
  924:        }
  925:    }
  926:    return ($num,%texts);
  927: }
  928: 
  929: sub remove_lock {
  930:     my ($id)=@_;
  931:     my $newlocks='';
  932:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  933:        if (($lock=~/\w/) && ($lock ne $id)) {
  934:           $newlocks.=','.$lock;
  935:        }
  936:     }
  937:     &appenv({'session.locks' => $newlocks});
  938:     &delenv('session.lock.'.$id);
  939: }
  940: 
  941: sub remove_all_locks {
  942:     my $activelocks=$env{'session.locks'};
  943:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  944:        if ($lock=~/\w/) {
  945:           &remove_lock($lock);
  946:        }
  947:     }
  948: }
  949: 
  950: 
  951: # ------------------------------------------ Find out current server userload
  952: sub userload {
  953:     my $numusers=0;
  954:     {
  955: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  956: 	my $filename;
  957: 	my $curtime=time;
  958: 	while ($filename=readdir(LONIDS)) {
  959: 	    next if ($filename eq '.' || $filename eq '..');
  960: 	    next if ($filename =~ /publicuser_\d+\.id/);
  961:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  962: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  963: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  964: 	}
  965: 	closedir(LONIDS);
  966:     }
  967:     my $userloadpercent=0;
  968:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  969:     if ($maxuserload) {
  970: 	$userloadpercent=100*$numusers/$maxuserload;
  971:     }
  972:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  973:     return $userloadpercent;
  974: }
  975: 
  976: # ------------------------------ Find server with least workload from spare.tab
  977: 
  978: sub spareserver {
  979:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  980:     my $spare_server;
  981:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  982:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  983:                                                      :  $userloadpercent;
  984:     my ($uint_dom,$remotesessions);
  985:     if (($udom ne '') && (&domain($udom) ne '')) {
  986:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  987:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  988:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  989:         $remotesessions = $udomdefaults{'remotesessions'};
  990:     }
  991:     my $spareshash = &this_host_spares($udom);
  992:     if (ref($spareshash) eq 'HASH') {
  993:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  994:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  995:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  996:                                              $try_server));
  997: 	        ($spare_server, $lowest_load) =
  998: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  999:             }
 1000:         }
 1001: 
 1002:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1003: 
 1004:         if (!$found_server) {
 1005:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1006: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1007:                     next unless (&spare_can_host($udom,$uint_dom,
 1008:                                                  $remotesessions,$try_server));
 1009: 	            ($spare_server, $lowest_load) =
 1010: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1011:                 }
 1012: 	    }
 1013:         }
 1014:     }
 1015: 
 1016:     if (!$want_server_name) {
 1017:         if (defined($spare_server)) {
 1018:             my $hostname = &hostname($spare_server);
 1019:             if (defined($hostname)) {
 1020:                 my $protocol = 'http';
 1021:                 if ($protocol{$spare_server} eq 'https') {
 1022:                     $protocol = $protocol{$spare_server};
 1023:                 }
 1024:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
 1025:                 $hostname = $alias if ($alias ne '');
 1026: 	        $spare_server = $protocol.'://'.$hostname;
 1027:             }
 1028:         }
 1029:     }
 1030:     return $spare_server;
 1031: }
 1032: 
 1033: sub compare_server_load {
 1034:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1035: 
 1036:     if ($required) {
 1037:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1038:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1039:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1040:         if (($major eq '' && $minor eq '') ||
 1041:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1042:             return ($spare_server,$lowest_load);
 1043:         }
 1044:     }
 1045: 
 1046:     my $loadans     = &reply('load',    $try_server);
 1047:     my $userloadans = &reply('userload',$try_server);
 1048: 
 1049:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1050: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1051:     }
 1052: 
 1053:     my $load;
 1054:     if ($loadans =~ /\d/) {
 1055: 	if ($userloadans =~ /\d/) {
 1056: 	    #both are numbers, pick the bigger one
 1057: 	    $load = ($loadans > $userloadans) ? $loadans 
 1058: 		                              : $userloadans;
 1059: 	} else {
 1060: 	    $load = $loadans;
 1061: 	}
 1062:     } else {
 1063: 	$load = $userloadans;
 1064:     }
 1065: 
 1066:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1067: 	$spare_server = $try_server;
 1068: 	$lowest_load  = $load;
 1069:     }
 1070:     return ($spare_server,$lowest_load);
 1071: }
 1072: 
 1073: # --------------------------- ask offload servers if user already has a session
 1074: sub find_existing_session {
 1075:     my ($udom,$uname) = @_;
 1076:     my $spareshash = &this_host_spares($udom);
 1077:     if (ref($spareshash) eq 'HASH') {
 1078:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1079:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1080:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1081:             }
 1082:         }
 1083:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1084:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1085:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1086:             }
 1087:         }
 1088:     }
 1089:     return;
 1090: }
 1091: 
 1092: sub delusersession {
 1093:     my ($lonid,$udom,$uname) = @_;
 1094:     my $uprimary_id = &domain($udom,'primary');
 1095:     my $uintdom = &internet_dom($uprimary_id);
 1096:     my $intdom = &internet_dom($lonid);
 1097:     my $serverhomedom = &host_domain($lonid);
 1098:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1099:         return &reply(join(':','delusersession',
 1100:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1101:     }
 1102:     return;
 1103: }
 1104: 
 1105: # check if user's browser sent load balancer cookie and server still has session
 1106: # and is not overloaded.
 1107: sub check_for_balancer_cookie {
 1108:     my ($r,$update_mtime) = @_;
 1109:     my ($otherserver,$cookie);
 1110:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1111:     if (exists($cookies{'balanceID'})) {
 1112:         my $balid = $cookies{'balanceID'};
 1113:         $cookie=&LONCAPA::clean_handle($balid->value);
 1114:         my $balancedir=$r->dir_config('lonBalanceDir');
 1115:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1116:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1117:                 my ($possudom,$possuname) = ($1,$2);
 1118:                 my $has_session = 0;
 1119:                 if ((&domain($possudom) ne '') &&
 1120:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1121:                     my $try_server;
 1122:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1123:                     if ($opened) {
 1124:                         flock($idf,LOCK_SH);
 1125:                         while (my $line = <$idf>) {
 1126:                             chomp($line);
 1127:                             if (&hostname($line) ne '') {
 1128:                                 $try_server = $line;
 1129:                                 last;
 1130:                             }
 1131:                         }
 1132:                         close($idf);
 1133:                         if (($try_server) &&
 1134:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1135:                             my $lowest_load = 30000;
 1136:                             ($otherserver,$lowest_load) =
 1137:                                 &compare_server_load($try_server,undef,$lowest_load);
 1138:                             if ($otherserver ne '' && $lowest_load < 100) {
 1139:                                 $has_session = 1;
 1140:                             } else {
 1141:                                 undef($otherserver);
 1142:                             }
 1143:                         }
 1144:                     }
 1145:                 }
 1146:                 if ($has_session) {
 1147:                     if ($update_mtime) {
 1148:                         my $atime = my $mtime = time;
 1149:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1150:                     }
 1151:                 } else {
 1152:                     unlink("$balancedir/$cookie.id");
 1153:                 }
 1154:             }
 1155:         }
 1156:     }
 1157:     return ($otherserver,$cookie);
 1158: }
 1159: 
 1160: sub updatebalcookie {
 1161:     my ($cookie,$balancer,$lastentry)=@_;
 1162:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1163:         my ($udom,$uname) = ($1,$2);
 1164:         my $uprimary_id = &domain($udom,'primary');
 1165:         my $uintdom = &internet_dom($uprimary_id);
 1166:         my $intdom = &internet_dom($balancer);
 1167:         my $serverhomedom = &host_domain($balancer);
 1168:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1169:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1170:         }
 1171:     }
 1172:     return;
 1173: }
 1174: 
 1175: sub delbalcookie {
 1176:     my ($cookie,$balancer) =@_;
 1177:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1178:         my ($udom,$uname) = ($1,$2);
 1179:         my $uprimary_id = &domain($udom,'primary');
 1180:         my $uintdom = &internet_dom($uprimary_id);
 1181:         my $intdom = &internet_dom($balancer);
 1182:         my $serverhomedom = &host_domain($balancer);
 1183:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1184:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1185:         }
 1186:     }
 1187: }
 1188: 
 1189: # -------------------------------- ask if server already has a session for user
 1190: sub has_user_session {
 1191:     my ($lonid,$udom,$uname) = @_;
 1192:     my $result = &reply(join(':','userhassession',
 1193: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1194:     return 1 if ($result eq 'ok');
 1195: 
 1196:     return 0;
 1197: }
 1198: 
 1199: # --------- determine least loaded server in a user's domain which allows login
 1200: 
 1201: sub choose_server {
 1202:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1203:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1204:     my %servers = &get_servers($udom);
 1205:     my $lowest_load = 30000;
 1206:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1207:     if ($skiploadbal) {
 1208:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1209:         unless (defined($cached)) {
 1210:             my $cachetime = 60*60*24;
 1211:             my %domconfig =
 1212:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1213:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1214:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1215:                                            $cachetime);
 1216:             }
 1217:         }
 1218:     }
 1219:     foreach my $lonhost (keys(%servers)) {
 1220:         if ($skiploadbal) {
 1221:             if (ref($balancers) eq 'HASH') {
 1222:                 next if (exists($balancers->{$lonhost}));
 1223:             }
 1224:         }
 1225:         my $loginvia;
 1226:         if ($checkloginvia) {
 1227:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1228:             if ($loginvia) {
 1229:                 my ($server,$path) = split(/:/,$loginvia);
 1230:                 ($login_host, $lowest_load) =
 1231:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1232:                 if ($login_host eq $server) {
 1233:                     $portal_path = $path;
 1234:                     $isredirect = 1;
 1235:                 }
 1236:             } else {
 1237:                 ($login_host, $lowest_load) =
 1238:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1239:                 if ($login_host eq $lonhost) {
 1240:                     $portal_path = '';
 1241:                     $isredirect = ''; 
 1242:                 }
 1243:             }
 1244:         } else {
 1245:             ($login_host, $lowest_load) =
 1246:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1247:         }
 1248:     }
 1249:     if ($login_host ne '') {
 1250:         $hostname = &hostname($login_host);
 1251:     }
 1252:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1253: }
 1254: 
 1255: sub get_course_sessions {
 1256:     my ($cnum,$cdom,$lastactivity) = @_;
 1257:     my %servers = &internet_dom_servers($cdom);
 1258:     my %returnhash;
 1259:     foreach my $server (sort(keys(%servers))) {
 1260:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1261:         my @pairs=split(/\&/,$rep);
 1262:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1263:             foreach my $item (@pairs) {
 1264:                 my ($key,$value)=split(/=/,$item,2);
 1265:                 $key = &unescape($key);
 1266:                 next if ($key =~ /^error: 2 /);
 1267:                 if (exists($returnhash{$key})) {
 1268:                     next if ($value < $returnhash{$key});
 1269:                 }
 1270:                 $returnhash{$key}=$value;
 1271:             }
 1272:         }
 1273:     }
 1274:     return %returnhash;
 1275: }
 1276: 
 1277: # --------------------------------------------- Try to change a user's password
 1278: 
 1279: sub changepass {
 1280:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1281:     $currentpass = &escape($currentpass);
 1282:     $newpass     = &escape($newpass);
 1283:     my $lonhost = $perlvar{'lonHostID'};
 1284:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1285: 		       $server);
 1286:     if (! $answer) {
 1287: 	&logthis("No reply on password change request to $server ".
 1288: 		 "by $uname in domain $udom.");
 1289:     } elsif ($answer =~ "^ok") {
 1290:         &logthis("$uname in $udom successfully changed their password ".
 1291: 		 "on $server.");
 1292:     } elsif ($answer =~ "^pwchange_failure") {
 1293: 	&logthis("$uname in $udom was unable to change their password ".
 1294: 		 "on $server.  The action was blocked by either lcpasswd ".
 1295: 		 "or pwchange");
 1296:     } elsif ($answer =~ "^non_authorized") {
 1297:         &logthis("$uname in $udom did not get their password correct when ".
 1298: 		 "attempting to change it on $server.");
 1299:     } elsif ($answer =~ "^auth_mode_error") {
 1300:         &logthis("$uname in $udom attempted to change their password despite ".
 1301: 		 "not being locally or internally authenticated on $server.");
 1302:     } elsif ($answer =~ "^unknown_user") {
 1303:         &logthis("$uname in $udom attempted to change their password ".
 1304: 		 "on $server but were unable to because $server is not ".
 1305: 		 "their home server.");
 1306:     } elsif ($answer =~ "^refused") {
 1307: 	&logthis("$server refused to change $uname in $udom password because ".
 1308: 		 "it was sent an unencrypted request to change the password.");
 1309:     } elsif ($answer =~ "invalid_client") {
 1310:         &logthis("$server refused to change $uname in $udom password because ".
 1311:                  "it was a reset by e-mail originating from an invalid server.");
 1312:     } elsif ($answer =~ "^prioruse") {
 1313:        &logthis("$server refused to change $uname in $udom password because ".
 1314:                 "the password had been used before");
 1315:     }
 1316:     return $answer;
 1317: }
 1318: 
 1319: # ----------------------- Try to determine user's current authentication scheme
 1320: 
 1321: sub queryauthenticate {
 1322:     my ($uname,$udom)=@_;
 1323:     my $uhome=&homeserver($uname,$udom);
 1324:     if (!$uhome) {
 1325: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1326: 	return 'no_host';
 1327:     }
 1328:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1329:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1330: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1331:     }
 1332:     return $answer;
 1333: }
 1334: 
 1335: # --------- Try to authenticate user from domain's lib servers (first this one)
 1336: 
 1337: sub authenticate {
 1338:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1339:     $upass=&escape($upass);
 1340:     $uname= &LONCAPA::clean_username($uname);
 1341:     my $uhome=&homeserver($uname,$udom,1);
 1342:     my $newhome;
 1343:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1344: # Maybe the machine was offline and only re-appeared again recently?
 1345:         &reconlonc();
 1346: # One more
 1347: 	$uhome=&homeserver($uname,$udom,1);
 1348:         if (($uhome eq 'no_host') && $checkdefauth) {
 1349:             if (defined(&domain($udom,'primary'))) {
 1350:                 $newhome=&domain($udom,'primary');
 1351:             }
 1352:             if ($newhome ne '') {
 1353:                 $uhome = $newhome;
 1354:             }
 1355:         }
 1356: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1357: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1358: 	    return 'no_host';
 1359:         }
 1360:     }
 1361:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1362:     if ($answer eq 'authorized') {
 1363:         if ($newhome) {
 1364:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1365:             return 'no_account_on_host'; 
 1366:         } else {
 1367:             &logthis("User $uname at $udom authorized by $uhome");
 1368:             return $uhome;
 1369:         }
 1370:     }
 1371:     if ($answer eq 'non_authorized') {
 1372: 	&logthis("User $uname at $udom rejected by $uhome");
 1373: 	return 'no_host'; 
 1374:     }
 1375:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1376:     return 'no_host';
 1377: }
 1378: 
 1379: sub can_host_session {
 1380:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1381:     my $canhost = 1;
 1382:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1383:     if (ref($remotesessions) eq 'HASH') {
 1384:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1385:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1386:                 $canhost = 0;
 1387:             } else {
 1388:                 $canhost = 1;
 1389:             }
 1390:         }
 1391:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1392:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1393:                 $canhost = 1;
 1394:             } else {
 1395:                 $canhost = 0;
 1396:             }
 1397:         }
 1398:         if ($canhost) {
 1399:             if ($remotesessions->{'version'} ne '') {
 1400:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1401:                 if ($reqmajor ne '' && $reqminor ne '') {
 1402:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1403:                         my $major = $1;
 1404:                         my $minor = $2;
 1405:                         if (($major < $reqmajor ) ||
 1406:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1407:                             $canhost = 0;
 1408:                         }
 1409:                     } else {
 1410:                         $canhost = 0;
 1411:                     }
 1412:                 }
 1413:             }
 1414:         }
 1415:     }
 1416:     if ($canhost) {
 1417:         if (ref($hostedsessions) eq 'HASH') {
 1418:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1419:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1420:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1421:                 if (($uint_dom ne '') && 
 1422:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1423:                     $canhost = 0;
 1424:                 } else {
 1425:                     $canhost = 1;
 1426:                 }
 1427:             }
 1428:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1429:                 if (($uint_dom ne '') && 
 1430:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1431:                     $canhost = 1;
 1432:                 } else {
 1433:                     $canhost = 0;
 1434:                 }
 1435:             }
 1436:         }
 1437:     }
 1438:     return $canhost;
 1439: }
 1440: 
 1441: sub spare_can_host {
 1442:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1443:     my $canhost=1;
 1444:     my $try_server_hostname = &hostname($try_server);
 1445:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1446:     my $serverhomedom = &host_domain($serverhomeID);
 1447:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1448:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1449:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1450:             $canhost = 0;
 1451:         }
 1452:     }
 1453:     if ($canhost) {
 1454:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1455:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1456:                 unless (&shared_institution($udom,$try_server)) {
 1457:                     $canhost = 0;
 1458:                 }
 1459:             }
 1460:         }
 1461:     }
 1462:     if (($canhost) && ($uint_dom)) {
 1463:         my @intdoms;
 1464:         my $internet_names = &get_internet_names($try_server);
 1465:         if (ref($internet_names) eq 'ARRAY') {
 1466:             @intdoms = @{$internet_names};
 1467:         }
 1468:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1469:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1470:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1471:                                          $remotesessions,
 1472:                                          $defdomdefaults{'hostedsessions'});
 1473:         }
 1474:     }
 1475:     return $canhost;
 1476: }
 1477: 
 1478: sub this_host_spares {
 1479:     my ($dom) = @_;
 1480:     my ($dom_in_use,$lonhost_in_use,$result);
 1481:     my @hosts = &current_machine_ids();
 1482:     foreach my $lonhost (@hosts) {
 1483:         if (&host_domain($lonhost) eq $dom) {
 1484:             $dom_in_use = $dom;
 1485:             $lonhost_in_use = $lonhost;
 1486:             last;
 1487:         }
 1488:     }
 1489:     if ($dom_in_use ne '') {
 1490:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1491:     }
 1492:     if (ref($result) ne 'HASH') {
 1493:         $lonhost_in_use = $perlvar{'lonHostID'};
 1494:         $dom_in_use = &host_domain($lonhost_in_use);
 1495:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1496:         if (ref($result) ne 'HASH') {
 1497:             $result = \%spareid;
 1498:         }
 1499:     }
 1500:     return $result;
 1501: }
 1502: 
 1503: sub spares_for_offload  {
 1504:     my ($dom_in_use,$lonhost_in_use) = @_;
 1505:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1506:     if (defined($cached)) {
 1507:         return $result;
 1508:     } else {
 1509:         my $cachetime = 60*60*24;
 1510:         my %domconfig =
 1511:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1512:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1513:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1514:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1515:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1516:                 }
 1517:             }
 1518:         }
 1519:     }
 1520:     return;
 1521: }
 1522: 
 1523: sub get_lonbalancer_config {
 1524:     my ($servers) = @_;
 1525:     my ($currbalancer,$currtargets);
 1526:     if (ref($servers) eq 'HASH') {
 1527:         foreach my $server (keys(%{$servers})) {
 1528:             my %what = (
 1529:                          spareid => 1,
 1530:                          perlvar => 1,
 1531:                        );
 1532:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1533:             if ($result eq 'ok') {
 1534:                 if (ref($returnhash) eq 'HASH') {
 1535:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1536:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1537:                             $currbalancer = $server;
 1538:                             $currtargets = {};
 1539:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1540:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1541:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1542:                                 }
 1543:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1544:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1545:                                 }
 1546:                             }
 1547:                             last;
 1548:                         }
 1549:                     }
 1550:                 }
 1551:             }
 1552:         }
 1553:     }
 1554:     return ($currbalancer,$currtargets);
 1555: }
 1556: 
 1557: sub check_loadbalancing {
 1558:     my ($uname,$udom,$caller) = @_;
 1559:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1560:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1561:     my $lonhost = $perlvar{'lonHostID'};
 1562:     my @hosts = &current_machine_ids();
 1563:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1564:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1565:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1566:     my $serverhomedom = &host_domain($lonhost);
 1567:     my $domneedscache;
 1568:     my $cachetime = 60*60*24;
 1569: 
 1570:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1571:         $dom_in_use = $udom;
 1572:         $homeintdom = 1;
 1573:     } else {
 1574:         $dom_in_use = $serverhomedom;
 1575:     }
 1576:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1577:     unless (defined($cached)) {
 1578:         my %domconfig =
 1579:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1580:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1581:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1582:         } else {
 1583:             $domneedscache = $dom_in_use;
 1584:         }
 1585:     }
 1586:     if (ref($result) eq 'HASH') {
 1587:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1588:             &check_balancer_result($result,@hosts);
 1589:         if ($is_balancer) {
 1590:             if (ref($currrules) eq 'HASH') {
 1591:                 if ($homeintdom) {
 1592:                     if ($uname ne '') {
 1593:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1594:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1595:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1596:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1597:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1598:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1599:                             }
 1600:                         }
 1601:                         if ($rule_in_effect eq '') {
 1602:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1603:                             if ($userenv{'inststatus'} ne '') {
 1604:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1605:                                 my ($othertitle,$usertypes,$types) =
 1606:                                     &Apache::loncommon::sorted_inst_types($udom);
 1607:                                 if (ref($types) eq 'ARRAY') {
 1608:                                     foreach my $type (@{$types}) {
 1609:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1610:                                             if (exists($currrules->{$type})) {
 1611:                                                 $rule_in_effect = $currrules->{$type};
 1612:                                             }
 1613:                                         }
 1614:                                     }
 1615:                                 }
 1616:                             } else {
 1617:                                 if (exists($currrules->{'default'})) {
 1618:                                     $rule_in_effect = $currrules->{'default'};
 1619:                                 }
 1620:                             }
 1621:                         }
 1622:                     } else {
 1623:                         if (exists($currrules->{'default'})) {
 1624:                             $rule_in_effect = $currrules->{'default'};
 1625:                         }
 1626:                     }
 1627:                 } else {
 1628:                     if ($currrules->{'_LC_external'} ne '') {
 1629:                         $rule_in_effect = $currrules->{'_LC_external'};
 1630:                     }
 1631:                 }
 1632:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1633:                                                        $uname,$udom);
 1634:             }
 1635:         }
 1636:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1637:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1638:         unless (defined($cached)) {
 1639:             my %domconfig =
 1640:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1641:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1642:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1643:             } else {
 1644:                 $domneedscache = $serverhomedom;
 1645:             }
 1646:         }
 1647:         if (ref($result) eq 'HASH') {
 1648:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1649:                 &check_balancer_result($result,@hosts);
 1650:             if ($is_balancer) {
 1651:                 if (ref($currrules) eq 'HASH') {
 1652:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1653:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1654:                     }
 1655:                 }
 1656:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1657:                                                        $uname,$udom);
 1658:             }
 1659:         } else {
 1660:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1661:                 $is_balancer = 1;
 1662:                 $offloadto = &this_host_spares($dom_in_use);
 1663:             }
 1664:             unless (defined($cached)) {
 1665:                 $domneedscache = $serverhomedom;
 1666:             }
 1667:         }
 1668:     } else {
 1669:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1670:             $is_balancer = 1;
 1671:             $offloadto = &this_host_spares($dom_in_use);
 1672:         }
 1673:         unless (defined($cached)) {
 1674:             $domneedscache = $serverhomedom;
 1675:         }
 1676:     }
 1677:     if ($domneedscache) {
 1678:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1679:     }
 1680:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1681:         my $lowest_load = 30000;
 1682:         if (ref($offloadto) eq 'HASH') {
 1683:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1684:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1685:                     ($otherserver,$lowest_load) =
 1686:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1687:                 }
 1688:             }
 1689:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1690: 
 1691:             if (!$found_server) {
 1692:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1693:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1694:                         ($otherserver,$lowest_load) =
 1695:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1696:                     }
 1697:                 }
 1698:             }
 1699:         } elsif (ref($offloadto) eq 'ARRAY') {
 1700:             if (@{$offloadto} == 1) {
 1701:                 $otherserver = $offloadto->[0];
 1702:             } elsif (@{$offloadto} > 1) {
 1703:                 foreach my $try_server (@{$offloadto}) {
 1704:                     ($otherserver,$lowest_load) =
 1705:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1706:                 }
 1707:             }
 1708:         }
 1709:         unless ($caller eq 'login') {
 1710:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1711:                 $is_balancer = 0;
 1712:                 if ($uname ne '' && $udom ne '') {
 1713:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1714:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1715:                                  'user.loadbalcheck.time' => time});
 1716:                     }
 1717:                 }
 1718:             }
 1719:         }
 1720:     }
 1721:     if (($is_balancer) && (!$homeintdom)) {
 1722:         undef($setcookie);
 1723:     }
 1724:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1725: }
 1726: 
 1727: sub check_balancer_result {
 1728:     my ($result,@hosts) = @_;
 1729:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1730:     if (ref($result) eq 'HASH') {
 1731:         if ($result->{'lonhost'} ne '') {
 1732:             my $currbalancer = $result->{'lonhost'};
 1733:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1734:                 $is_balancer = 1;
 1735:                 $currtargets = $result->{'targets'};
 1736:                 $currrules = $result->{'rules'};
 1737:             }
 1738:             $dom_balancers = $currbalancer;
 1739:         } else {
 1740:             if (keys(%{$result})) {
 1741:                 foreach my $key (keys(%{$result})) {
 1742:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1743:                         (ref($result->{$key}) eq 'HASH')) {
 1744:                         $is_balancer = 1;
 1745:                         $currrules = $result->{$key}{'rules'};
 1746:                         $currtargets = $result->{$key}{'targets'};
 1747:                         $setcookie = $result->{$key}{'cookie'};
 1748:                         last;
 1749:                     }
 1750:                 }
 1751:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1752:             }
 1753:         }
 1754:     }
 1755:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1756: }
 1757: 
 1758: sub get_loadbalancer_targets {
 1759:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1760:     my $offloadto;
 1761:     if ($rule_in_effect eq 'none') {
 1762:         return [$perlvar{'lonHostID'}];
 1763:     } elsif ($rule_in_effect eq '') {
 1764:         $offloadto = $currtargets;
 1765:     } else {
 1766:         if ($rule_in_effect eq 'homeserver') {
 1767:             my $homeserver = &homeserver($uname,$udom);
 1768:             if ($homeserver ne 'no_host') {
 1769:                 $offloadto = [$homeserver];
 1770:             }
 1771:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1772:             my %domconfig =
 1773:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1774:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1775:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1776:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1777:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1778:                     }
 1779:                 }
 1780:             } else {
 1781:                 my %servers = &internet_dom_servers($udom);
 1782:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1783:                 if (&hostname($remotebalancer) ne '') {
 1784:                     $offloadto = [$remotebalancer];
 1785:                 }
 1786:             }
 1787:         } elsif (&hostname($rule_in_effect) ne '') {
 1788:             $offloadto = [$rule_in_effect];
 1789:         }
 1790:     }
 1791:     return $offloadto;
 1792: }
 1793: 
 1794: sub internet_dom_servers {
 1795:     my ($dom) = @_;
 1796:     my (%uniqservers,%servers);
 1797:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1798:     my @machinedoms = &machine_domains($primaryserver);
 1799:     foreach my $mdom (@machinedoms) {
 1800:         my %currservers = %servers;
 1801:         my %server = &get_servers($mdom);
 1802:         %servers = (%currservers,%server);
 1803:     }
 1804:     my %by_hostname;
 1805:     foreach my $id (keys(%servers)) {
 1806:         push(@{$by_hostname{$servers{$id}}},$id);
 1807:     }
 1808:     foreach my $hostname (sort(keys(%by_hostname))) {
 1809:         if (@{$by_hostname{$hostname}} > 1) {
 1810:             my $match = 0;
 1811:             foreach my $id (@{$by_hostname{$hostname}}) {
 1812:                 if (&host_domain($id) eq $dom) {
 1813:                     $uniqservers{$id} = $hostname;
 1814:                     $match = 1;
 1815:                 }
 1816:             }
 1817:             unless ($match) {
 1818:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1819:             }
 1820:         } else {
 1821:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1822:         }
 1823:     }
 1824:     return %uniqservers;
 1825: }
 1826: 
 1827: sub trusted_domains {
 1828:     my ($cmdtype,$calldom) = @_;
 1829:     my ($trusted,$untrusted);
 1830:     if (&domain($calldom) eq '') {
 1831:         return ($trusted,$untrusted);
 1832:     }
 1833:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1834:         return ($trusted,$untrusted);
 1835:     }
 1836:     my $callprimary = &domain($calldom,'primary');
 1837:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1838:     if ($intcalldom eq '') {
 1839:         return ($trusted,$untrusted);
 1840:     }
 1841: 
 1842:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1843:     unless (defined($cached)) {
 1844:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1845:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1846:         $trustconfig = $domconfig{'trust'};
 1847:     }
 1848:     if (ref($trustconfig)) {
 1849:         my (%possexc,%possinc,@allexc,@allinc); 
 1850:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1851:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1852:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1853:             }
 1854:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1855:                 $possinc{$intcalldom} = 1;
 1856:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1857:             }
 1858:         }
 1859:         if (keys(%possexc)) {
 1860:             if (keys(%possinc)) {
 1861:                 foreach my $key (sort(keys(%possexc))) {
 1862:                     next if ($key eq $intcalldom);
 1863:                     unless ($possinc{$key}) {
 1864:                         push(@allexc,$key);
 1865:                     }
 1866:                 }
 1867:             } else {
 1868:                 @allexc = sort(keys(%possexc));
 1869:             }
 1870:         }
 1871:         if (keys(%possinc)) {
 1872:             $possinc{$intcalldom} = 1;
 1873:             @allinc = sort(keys(%possinc));
 1874:         }
 1875:         if ((@allexc > 0) || (@allinc > 0)) {
 1876:             my %doms_by_intdom;
 1877:             my %allintdoms = &all_host_intdom();
 1878:             my %alldoms = &all_host_domain();
 1879:             foreach my $key (%allintdoms) {
 1880:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1881:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1882:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1883:                     }
 1884:                 } else {
 1885:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1886:                 }
 1887:             }
 1888:             foreach my $exc (@allexc) {
 1889:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1890:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1891:                 }
 1892:             }
 1893:             foreach my $inc (@allinc) {
 1894:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1895:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1896:                 }
 1897:             }
 1898:         }
 1899:     }
 1900:     return ($trusted,$untrusted);
 1901: }
 1902: 
 1903: sub will_trust {
 1904:     my ($cmdtype,$domain,$possdom) = @_;
 1905:     return 1 if ($domain eq $possdom);
 1906:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1907:     my $willtrust; 
 1908:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1909:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1910:             $willtrust = 1;
 1911:         }
 1912:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1913:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1914:             $willtrust = 1;
 1915:         }
 1916:     } else {
 1917:         $willtrust = 1;
 1918:     }
 1919:     return $willtrust;
 1920: }
 1921: 
 1922: # ---------------------- Find the homebase for a user from domain's lib servers
 1923: 
 1924: my %homecache;
 1925: sub homeserver {
 1926:     my ($uname,$udom,$ignoreBadCache)=@_;
 1927:     my $index="$uname:$udom";
 1928: 
 1929:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1930: 
 1931:     my %servers = &get_servers($udom,'library');
 1932:     foreach my $tryserver (keys(%servers)) {
 1933:         next if ($ignoreBadCache ne 'true' && 
 1934: 		 exists($badServerCache{$tryserver}));
 1935: 
 1936: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1937: 	if ($answer eq 'found') {
 1938: 	    delete($badServerCache{$tryserver}); 
 1939: 	    return $homecache{$index}=$tryserver;
 1940: 	} elsif ($answer eq 'no_host') {
 1941: 	    $badServerCache{$tryserver}=1;
 1942: 	}
 1943:     }    
 1944:     return 'no_host';
 1945: }
 1946: 
 1947: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1948: 
 1949: sub idget {
 1950:     my ($udom,$idsref,$namespace)=@_;
 1951:     my %returnhash=();
 1952:     my @ids=(); 
 1953:     if (ref($idsref) eq 'ARRAY') {
 1954:         @ids = @{$idsref};
 1955:     } else {
 1956:         return %returnhash; 
 1957:     }
 1958:     if ($namespace eq '') {
 1959:         $namespace = 'ids';
 1960:     }
 1961:     
 1962:     my %servers = &get_servers($udom,'library');
 1963:     foreach my $tryserver (keys(%servers)) {
 1964: 	my $idlist=join('&', map { &escape($_); } @ids);
 1965: 	if ($namespace eq 'ids') {
 1966: 	    $idlist=~tr/A-Z/a-z/;
 1967: 	}
 1968: 	my $reply;
 1969: 	if ($namespace eq 'ids') {
 1970: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1971: 	} else {
 1972: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1973: 	}
 1974: 	my @answer=();
 1975: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1976: 	    @answer=split(/\&/,$reply);
 1977: 	}                    ;
 1978: 	my $i;
 1979: 	for ($i=0;$i<=$#ids;$i++) {
 1980: 	    if ($answer[$i]) {
 1981: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1982: 	    }
 1983: 	}
 1984:     }
 1985:     return %returnhash;
 1986: }
 1987: 
 1988: # ------------------------------------- Find the IDs behind a list of usernames
 1989: 
 1990: sub idrget {
 1991:     my ($udom,@unames)=@_;
 1992:     my %returnhash=();
 1993:     foreach my $uname (@unames) {
 1994:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1995:     }
 1996:     return %returnhash;
 1997: }
 1998: 
 1999: # Store away a list of names and associated student/employee IDs or clicker IDs
 2000: 
 2001: sub idput {
 2002:     my ($udom,$idsref,$uhom,$namespace)=@_;
 2003:     my %servers=();
 2004:     my %ids=();
 2005:     my %byid = ();
 2006:     if (ref($idsref) eq 'HASH') {
 2007:         %ids=%{$idsref};
 2008:     }
 2009:     if ($namespace eq '') {
 2010:         $namespace = 'ids'; 
 2011:     }
 2012:     foreach my $uname (keys(%ids)) {
 2013: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2014:         if ($uhom eq '') {
 2015:             $uhom=&homeserver($uname,$udom);
 2016:         }
 2017:         if ($uhom ne 'no_host') {
 2018:             my $esc_unam=&escape($uname);
 2019:             if ($namespace eq 'ids') {
 2020:                 my $id=&escape($ids{$uname});
 2021:                 $id=~tr/A-Z/a-z/;
 2022:                 my $esc_unam=&escape($uname);
 2023:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2024:             } else {
 2025:                 my @currids = split(/,/,$ids{$uname});
 2026:                 foreach my $id (@currids) {
 2027:                     $byid{$uhom}{$id} .= $uname.',';
 2028:                 }
 2029:             }
 2030:         }
 2031:     }
 2032:     if ($namespace eq 'clickers') {
 2033:         foreach my $server (keys(%byid)) {
 2034:             if (ref($byid{$server}) eq 'HASH') {
 2035:                 foreach my $id (keys(%{$byid{$server}})) {
 2036:                     $byid{$server} =~ s/,$//;
 2037:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2038:                 }
 2039:             }
 2040:         }
 2041:     }
 2042:     foreach my $server (keys(%servers)) {
 2043:         $servers{$server} =~ s/\&$//;
 2044:         if ($namespace eq 'ids') {     
 2045:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2046:         } else {
 2047:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2048:         }
 2049:     }
 2050: }
 2051: 
 2052: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2053: 
 2054: sub iddel {
 2055:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2056:     my %result=();
 2057:     my %ids=();
 2058:     my %byid = ();
 2059:     if (ref($idshashref) eq 'HASH') {
 2060:         %ids=%{$idshashref};
 2061:     } else {
 2062:         return %result;
 2063:     }
 2064:     if ($namespace eq '') {
 2065:         $namespace = 'ids';
 2066:     }
 2067:     my %servers=();
 2068:     while (my ($id,$unamestr) = each(%ids)) {
 2069:         if ($namespace eq 'ids') {
 2070:             my $uhom = $uhome;
 2071:             if ($uhom eq '') { 
 2072:                 $uhom=&homeserver($unamestr,$udom);
 2073:             }
 2074:             if ($uhom ne 'no_host') {
 2075:                 $servers{$uhom}.='&'.&escape($id);
 2076:             }
 2077:          } else {
 2078:             my @curritems = split(/,/,$ids{$id});
 2079:             foreach my $uname (@curritems) {
 2080:                 my $uhom = $uhome;
 2081:                 if ($uhom eq '') {
 2082:                     $uhom=&homeserver($uname,$udom);
 2083:                 }
 2084:                 if ($uhom ne 'no_host') { 
 2085:                     $byid{$uhom}{$id} .= $uname.',';
 2086:                 }
 2087:             }
 2088:         }
 2089:     }
 2090:     if ($namespace eq 'clickers') {
 2091:         foreach my $server (keys(%byid)) {
 2092:             if (ref($byid{$server}) eq 'HASH') {
 2093:                 foreach my $id (keys(%{$byid{$server}})) {
 2094:                     $byid{$server}{$id} =~ s/,$//;
 2095:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2096:                 }
 2097:             }
 2098:         }
 2099:     }
 2100:     foreach my $server (keys(%servers)) {
 2101:         $servers{$server} =~ s/\&$//;
 2102:         if ($namespace eq 'ids') {
 2103:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2104:         } elsif ($namespace eq 'clickers') {
 2105:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2106:         }
 2107:     }
 2108:     return %result;
 2109: }
 2110: 
 2111: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2112: 
 2113: sub updateclickers {
 2114:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2115:     my %clickers;
 2116:     if (ref($idshashref) eq 'HASH') {
 2117:         %clickers=%{$idshashref};
 2118:     } else {
 2119:         return;
 2120:     }
 2121:     my $items='';
 2122:     foreach my $item (keys(%clickers)) {
 2123:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2124:     }
 2125:     $items=~s/\&$//;
 2126:     my $request = "updateclickers:$udom:$action:$items";
 2127:     if ($critical) {
 2128:         return &critical($request,$uhome);
 2129:     } else {
 2130:         return &reply($request,$uhome);
 2131:     }
 2132: }
 2133: 
 2134: # ------------------------------dump from db file owned by domainconfig user
 2135: sub dump_dom {
 2136:     my ($namespace, $udom, $regexp) = @_;
 2137: 
 2138:     $udom ||= $env{'user.domain'};
 2139: 
 2140:     return () unless $udom;
 2141: 
 2142:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2143: }
 2144: 
 2145: # ------------------------------------------ get items from domain db files   
 2146: 
 2147: sub get_dom {
 2148:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2149:     return if ($udom eq 'public');
 2150:     my $items='';
 2151:     foreach my $item (@$storearr) {
 2152:         $items.=&escape($item).'&';
 2153:     }
 2154:     $items=~s/\&$//;
 2155:     if (!$udom) {
 2156:         $udom=$env{'user.domain'};
 2157:         return if ($udom eq 'public');
 2158:         if (defined(&domain($udom,'primary'))) {
 2159:             $uhome=&domain($udom,'primary');
 2160:         } else {
 2161:             undef($uhome);
 2162:         }
 2163:     } else {
 2164:         if (!$uhome) {
 2165:             if (defined(&domain($udom,'primary'))) {
 2166:                 $uhome=&domain($udom,'primary');
 2167:             }
 2168:         }
 2169:     }
 2170:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2171:         my $rep;
 2172:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2173:             # domain information is hosted on this machine
 2174:             my $cmd = 'getdom';
 2175:             if ($namespace =~ /^enc/) {
 2176:                 $cmd = 'egetdom';
 2177:             }
 2178:             $rep = &LONCAPA::Lond::get_dom("$cmd:$udom:$namespace:$items");
 2179:         } else {
 2180:             if ($namespace =~ /^enc/) {
 2181:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2182:             } else {
 2183:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2184:             }
 2185:         }
 2186:         my %returnhash;
 2187:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2188:             return %returnhash;
 2189:         }
 2190:         my @pairs=split(/\&/,$rep);
 2191:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2192:             return @pairs;
 2193:         }
 2194:         my $i=0;
 2195:         foreach my $item (@$storearr) {
 2196:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2197:             $i++;
 2198:         }
 2199:         return %returnhash;
 2200:     } else {
 2201:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2202:     }
 2203: }
 2204: 
 2205: # -------------------------------------------- put items in domain db files 
 2206: 
 2207: sub put_dom {
 2208:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2209:     if (!$udom) {
 2210:         $udom=$env{'user.domain'};
 2211:         if (defined(&domain($udom,'primary'))) {
 2212:             $uhome=&domain($udom,'primary');
 2213:         } else {
 2214:             undef($uhome);
 2215:         }
 2216:     } else {
 2217:         if (!$uhome) {
 2218:             if (defined(&domain($udom,'primary'))) {
 2219:                 $uhome=&domain($udom,'primary');
 2220:             }
 2221:         }
 2222:     } 
 2223:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2224:         my $items='';
 2225:         foreach my $item (keys(%$storehash)) {
 2226:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2227:         }
 2228:         $items=~s/\&$//;
 2229:         if ($namespace =~ /^enc/) {
 2230:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2231:         } else {
 2232:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2233:         }
 2234:     } else {
 2235:         &logthis("put_dom failed - no homeserver and/or domain");
 2236:     }
 2237: }
 2238: 
 2239: # --------------------- newput for items in db file owned by domainconfig user
 2240: sub newput_dom {
 2241:     my ($namespace,$storehash,$udom) = @_;
 2242:     my $result;
 2243:     if (!$udom) {
 2244:         $udom=$env{'user.domain'};
 2245:     }
 2246:     if ($udom) {
 2247:         my $uname = &get_domainconfiguser($udom);
 2248:         $result = &newput($namespace,$storehash,$udom,$uname);
 2249:     }
 2250:     return $result;
 2251: }
 2252: 
 2253: # --------------------- delete for items in db file owned by domainconfig user
 2254: sub del_dom {
 2255:     my ($namespace,$storearr,$udom)=@_;
 2256:     if (ref($storearr) eq 'ARRAY') {
 2257:         if (!$udom) {
 2258:             $udom=$env{'user.domain'};
 2259:         }
 2260:         if ($udom) {
 2261:             my $uname = &get_domainconfiguser($udom); 
 2262:             return &del($namespace,$storearr,$udom,$uname);
 2263:         }
 2264:     }
 2265: }
 2266: 
 2267: # ----------------------------------construct domainconfig user for a domain 
 2268: sub get_domainconfiguser {
 2269:     my ($udom) = @_;
 2270:     return $udom.'-domainconfig';
 2271: }
 2272: 
 2273: sub retrieve_inst_usertypes {
 2274:     my ($udom) = @_;
 2275:     my (%returnhash,@order);
 2276:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2277:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2278:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2279:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2280:     } else {
 2281:         if (defined(&domain($udom,'primary'))) {
 2282:             my $uhome=&domain($udom,'primary');
 2283:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2284:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2285:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2286:                 return (\%returnhash,\@order);
 2287:             }
 2288:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2289:             my @pairs=split(/\&/,$hashitems);
 2290:             foreach my $item (@pairs) {
 2291:                 my ($key,$value)=split(/=/,$item,2);
 2292:                 $key = &unescape($key);
 2293:                 next if ($key =~ /^error: 2 /);
 2294:                 $returnhash{$key}=&thaw_unescape($value);
 2295:             }
 2296:             my @esc_order = split(/\&/,$orderitems);
 2297:             foreach my $item (@esc_order) {
 2298:                 push(@order,&unescape($item));
 2299:             }
 2300:         } else {
 2301:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2302:         }
 2303:         return (\%returnhash,\@order);
 2304:     }
 2305: }
 2306: 
 2307: sub is_domainimage {
 2308:     my ($url) = @_;
 2309:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2310:         if (&domain($1) ne '') {
 2311:             return '1';
 2312:         }
 2313:     }
 2314:     return;
 2315: }
 2316: 
 2317: sub inst_directory_query {
 2318:     my ($srch) = @_;
 2319:     my $udom = $srch->{'srchdomain'};
 2320:     my %results;
 2321:     my $homeserver = &domain($udom,'primary');
 2322:     my $outcome;
 2323:     if ($homeserver ne '') {
 2324:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2325:             if ($srch->{'srchby'} eq 'email') {
 2326:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2327:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2328:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2329:                     (($major == 2) && ($minor < 12))) {
 2330:                     return;
 2331:                 }
 2332:             }
 2333:         }
 2334: 	my $queryid=&reply("querysend:instdirsearch:".
 2335: 			   &escape($srch->{'srchby'}).':'.
 2336: 			   &escape($srch->{'srchterm'}).':'.
 2337: 			   &escape($srch->{'srchtype'}),$homeserver);
 2338: 	my $host=&hostname($homeserver);
 2339: 	if ($queryid !~/^\Q$host\E\_/) {
 2340: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2341: 	    return;
 2342: 	}
 2343: 	my $response = &get_query_reply($queryid);
 2344: 	my $maxtries = 5;
 2345: 	my $tries = 1;
 2346: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2347: 	    $response = &get_query_reply($queryid);
 2348: 	    $tries ++;
 2349: 	}
 2350: 
 2351:         if (!&error($response) && $response ne 'refused') {
 2352:             if ($response eq 'unavailable') {
 2353:                 $outcome = $response;
 2354:             } else {
 2355:                 $outcome = 'ok';
 2356:                 my @matches = split(/\n/,$response);
 2357:                 foreach my $match (@matches) {
 2358:                     my ($key,$value) = split(/=/,$match);
 2359:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2360:                 }
 2361:             }
 2362:         }
 2363:     }
 2364:     return ($outcome,%results);
 2365: }
 2366: 
 2367: sub usersearch {
 2368:     my ($srch) = @_;
 2369:     my $dom = $srch->{'srchdomain'};
 2370:     my %results;
 2371:     my %libserv = &all_library();
 2372:     my $query = 'usersearch';
 2373:     foreach my $tryserver (keys(%libserv)) {
 2374:         if (&host_domain($tryserver) eq $dom) {
 2375:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2376:                 if ($srch->{'srchby'} eq 'email') {
 2377:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2378:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2379:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2380:                              (($major == 2) && ($minor < 12)));
 2381:                 }
 2382:             }
 2383:             my $host=&hostname($tryserver);
 2384:             my $queryid=
 2385:                 &reply("querysend:".&escape($query).':'.
 2386:                        &escape($srch->{'srchby'}).':'.
 2387:                        &escape($srch->{'srchtype'}).':'.
 2388:                        &escape($srch->{'srchterm'}),$tryserver);
 2389:             if ($queryid !~/^\Q$host\E\_/) {
 2390:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2391:                 next;
 2392:             }
 2393:             my $reply = &get_query_reply($queryid);
 2394:             my $maxtries = 1;
 2395:             my $tries = 1;
 2396:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2397:                 $reply = &get_query_reply($queryid);
 2398:                 $tries ++;
 2399:             }
 2400:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2401:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2402:             } else {
 2403:                 my @matches;
 2404:                 if ($reply =~ /\n/) {
 2405:                     @matches = split(/\n/,$reply);
 2406:                 } else {
 2407:                     @matches = split(/\&/,$reply);
 2408:                 }
 2409:                 foreach my $match (@matches) {
 2410:                     my ($uname,$udom,%userhash);
 2411:                     foreach my $entry (split(/:/,$match)) {
 2412:                         my ($key,$value) =
 2413:                             map {&unescape($_);} split(/=/,$entry);
 2414:                         $userhash{$key} = $value;
 2415:                         if ($key eq 'username') {
 2416:                             $uname = $value;
 2417:                         } elsif ($key eq 'domain') {
 2418:                             $udom = $value;
 2419:                         }
 2420:                     }
 2421:                     $results{$uname.':'.$udom} = \%userhash;
 2422:                 }
 2423:             }
 2424:         }
 2425:     }
 2426:     return %results;
 2427: }
 2428: 
 2429: sub get_instuser {
 2430:     my ($udom,$uname,$id) = @_;
 2431:     my $homeserver = &domain($udom,'primary');
 2432:     my ($outcome,%results);
 2433:     if ($homeserver ne '') {
 2434:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2435:                            &escape($id).':'.&escape($udom),$homeserver);
 2436:         my $host=&hostname($homeserver);
 2437:         if ($queryid !~/^\Q$host\E\_/) {
 2438:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2439:             return;
 2440:         }
 2441:         my $response = &get_query_reply($queryid);
 2442:         my $maxtries = 5;
 2443:         my $tries = 1;
 2444:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2445:             $response = &get_query_reply($queryid);
 2446:             $tries ++;
 2447:         }
 2448:         if (!&error($response) && $response ne 'refused') {
 2449:             if ($response eq 'unavailable') {
 2450:                 $outcome = $response;
 2451:             } else {
 2452:                 $outcome = 'ok';
 2453:                 my @matches = split(/\n/,$response);
 2454:                 foreach my $match (@matches) {
 2455:                     my ($key,$value) = split(/=/,$match);
 2456:                     $results{&unescape($key)} = &thaw_unescape($value);
 2457:                 }
 2458:             }
 2459:         }
 2460:     }
 2461:     my %userinfo;
 2462:     if (ref($results{$uname}) eq 'HASH') {
 2463:         %userinfo = %{$results{$uname}};
 2464:     } 
 2465:     return ($outcome,%userinfo);
 2466: }
 2467: 
 2468: sub get_multiple_instusers {
 2469:     my ($udom,$users,$caller) = @_;
 2470:     my ($outcome,$results);
 2471:     if (ref($users) eq 'HASH') {
 2472:         my $count = keys(%{$users}); 
 2473:         my $requested = &freeze_escape($users);
 2474:         my $homeserver = &domain($udom,'primary');
 2475:         if ($homeserver ne '') {
 2476:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2477:             my $host=&hostname($homeserver);
 2478:             if ($queryid !~/^\Q$host\E\_/) {
 2479:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2480:                          ' for host: '.$homeserver.'in domain '.$udom);
 2481:                 return ($outcome,$results);
 2482:             }
 2483:             my $response = &get_query_reply($queryid);
 2484:             my $maxtries = 5;
 2485:             if ($count > 100) {
 2486:                 $maxtries = 1+int($count/20);
 2487:             }
 2488:             my $tries = 1;
 2489:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2490:                 $response = &get_query_reply($queryid);
 2491:                 $tries ++;
 2492:             }
 2493:             if ($response eq '') {
 2494:                 $results = {};
 2495:                 foreach my $key (keys(%{$users})) {
 2496:                     my ($uname,$id);
 2497:                     if ($caller eq 'id') {
 2498:                         $id = $key;
 2499:                     } else {
 2500:                         $uname = $key;
 2501:                     }
 2502:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2503:                     $outcome = $resp;
 2504:                     if ($resp eq 'ok') {
 2505:                         %{$results} = (%{$results}, %info);
 2506:                     } else {
 2507:                         last;
 2508:                     }
 2509:                 }
 2510:             } elsif(!&error($response) && ($response ne 'refused')) {
 2511:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2512:                     $outcome = $response;
 2513:                 } else {
 2514:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2515:                     if ($outcome eq 'ok') {
 2516:                         $results = &thaw_unescape($userdata); 
 2517:                     }
 2518:                 }
 2519:             }
 2520:         }
 2521:     }
 2522:     return ($outcome,$results);
 2523: }
 2524: 
 2525: sub inst_rulecheck {
 2526:     my ($udom,$uname,$id,$item,$rules) = @_;
 2527:     my %returnhash;
 2528:     if ($udom ne '') {
 2529:         if (ref($rules) eq 'ARRAY') {
 2530:             @{$rules} = map {&escape($_);} (@{$rules});
 2531:             my $rulestr = join(':',@{$rules});
 2532:             my $homeserver=&domain($udom,'primary');
 2533:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2534:                 my $response;
 2535:                 if ($item eq 'username') {                
 2536:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2537:                                               ':'.&escape($uname).':'.$rulestr,
 2538:                                               $homeserver));
 2539:                 } elsif ($item eq 'id') {
 2540:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2541:                                               ':'.&escape($id).':'.$rulestr,
 2542:                                               $homeserver));
 2543:                 } elsif ($item eq 'selfcreate') {
 2544:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2545:                                                &escape($udom).':'.&escape($uname).
 2546:                                               ':'.$rulestr,$homeserver));
 2547:                 }
 2548:                 if ($response ne 'refused') {
 2549:                     my @pairs=split(/\&/,$response);
 2550:                     foreach my $item (@pairs) {
 2551:                         my ($key,$value)=split(/=/,$item,2);
 2552:                         $key = &unescape($key);
 2553:                         next if ($key =~ /^error: 2 /);
 2554:                         $returnhash{$key}=&thaw_unescape($value);
 2555:                     }
 2556:                 }
 2557:             }
 2558:         }
 2559:     }
 2560:     return %returnhash;
 2561: }
 2562: 
 2563: sub inst_userrules {
 2564:     my ($udom,$check) = @_;
 2565:     my (%ruleshash,@ruleorder);
 2566:     if ($udom ne '') {
 2567:         my $homeserver=&domain($udom,'primary');
 2568:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2569:             my $response;
 2570:             if ($check eq 'id') {
 2571:                 $response=&reply('instidrules:'.&escape($udom),
 2572:                                  $homeserver);
 2573:             } elsif ($check eq 'email') {
 2574:                 $response=&reply('instemailrules:'.&escape($udom),
 2575:                                  $homeserver);
 2576:             } else {
 2577:                 $response=&reply('instuserrules:'.&escape($udom),
 2578:                                  $homeserver);
 2579:             }
 2580:             if (($response ne 'refused') && ($response ne 'error') && 
 2581:                 ($response ne 'unknown_cmd') && 
 2582:                 ($response ne 'no_such_host')) {
 2583:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2584:                 my @pairs=split(/\&/,$hashitems);
 2585:                 foreach my $item (@pairs) {
 2586:                     my ($key,$value)=split(/=/,$item,2);
 2587:                     $key = &unescape($key);
 2588:                     next if ($key =~ /^error: 2 /);
 2589:                     $ruleshash{$key}=&thaw_unescape($value);
 2590:                 }
 2591:                 my @esc_order = split(/\&/,$orderitems);
 2592:                 foreach my $item (@esc_order) {
 2593:                     push(@ruleorder,&unescape($item));
 2594:                 }
 2595:             }
 2596:         }
 2597:     }
 2598:     return (\%ruleshash,\@ruleorder);
 2599: }
 2600: 
 2601: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2602: 
 2603: sub get_domain_defaults {
 2604:     my ($domain,$ignore_cache) = @_;
 2605:     return if (($domain eq '') || ($domain eq 'public'));
 2606:     my $cachetime = 60*60*24;
 2607:     unless ($ignore_cache) {
 2608:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2609:         if (defined($cached)) {
 2610:             if (ref($result) eq 'HASH') {
 2611:                 return %{$result};
 2612:             }
 2613:         }
 2614:     }
 2615:     my %domdefaults;
 2616:     my %domconfig =
 2617:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2618:                                   'requestcourses','inststatus',
 2619:                                   'coursedefaults','usersessions',
 2620:                                   'requestauthor','selfenrollment',
 2621:                                   'coursecategories','ssl','autoenroll',
 2622:                                   'trust','helpsettings','wafproxy'],$domain);
 2623:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2624:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2625:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2626:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2627:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2628:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2629:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2630:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2631:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2632:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2633:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2634:     } else {
 2635:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2636:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2637:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2638:     }
 2639:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2640:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2641:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2642:         } else {
 2643:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2644:         }
 2645:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2646:         foreach my $item (@usertools) {
 2647:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2648:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2649:             }
 2650:         }
 2651:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2652:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2653:         }
 2654:     }
 2655:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2656:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2657:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2658:         }
 2659:     }
 2660:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2661:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2662:     }
 2663:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2664:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2665:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2666:         }
 2667:     }
 2668:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2669:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2670:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2671:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2672:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2673:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2674:         }
 2675:         foreach my $type (@coursetypes) {
 2676:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2677:                 unless ($type eq 'community') {
 2678:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2679:                 }
 2680:             }
 2681:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2682:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2683:             }
 2684:             if ($domdefaults{'postsubmit'} eq 'on') {
 2685:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2686:                     $domdefaults{$type.'postsubtimeout'} = 
 2687:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2688:                 }
 2689:             }
 2690:         }
 2691:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2692:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2693:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2694:                 if (@clonecodes) {
 2695:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2696:                 }
 2697:             }
 2698:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2699:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2700:         }
 2701:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2702:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2703:         } 
 2704:     }
 2705:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2706:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2707:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2708:         }
 2709:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2710:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2711:         }
 2712:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2713:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2714:         }
 2715:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2716:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2717:         }
 2718:     }
 2719:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2720:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2721:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2722:                             'approval','limit');
 2723:             foreach my $type (@coursetypes) {
 2724:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2725:                     my @mgrdc = ();
 2726:                     foreach my $item (@settings) {
 2727:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2728:                             push(@mgrdc,$item);
 2729:                         }
 2730:                     }
 2731:                     if (@mgrdc) {
 2732:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2733:                     }
 2734:                 }
 2735:             }
 2736:         }
 2737:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2738:             foreach my $type (@coursetypes) {
 2739:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2740:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2741:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2742:                     }
 2743:                 }
 2744:             }
 2745:         }
 2746:     }
 2747:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2748:         $domdefaults{'catauth'} = 'std';
 2749:         $domdefaults{'catunauth'} = 'std';
 2750:         if ($domconfig{'coursecategories'}{'auth'}) {
 2751:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2752:         }
 2753:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2754:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2755:         }
 2756:     }
 2757:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2758:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2759:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2760:         }
 2761:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2762:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2763:         }
 2764:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2765:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2766:         }
 2767:     }
 2768:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2769:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2770:         foreach my $prefix (@prefixes) {
 2771:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2772:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2773:             }
 2774:         }
 2775:     }
 2776:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2777:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2778:     }
 2779:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2780:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2781:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2782:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2783:         }
 2784:     }
 2785:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2786:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2787:             if ($domconfig{'wafproxy'}{$item}) {
 2788:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2789:             }
 2790:         }
 2791:     } 
 2792:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2793:     return %domdefaults;
 2794: }
 2795: 
 2796: sub get_dom_cats {
 2797:     my ($dom) = @_;
 2798:     return unless (&domain($dom));
 2799:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2800:     unless (defined($cached)) {
 2801:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2802:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2803:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2804:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2805:             } else {
 2806:                 $cats = {};
 2807:             }
 2808:         } else {
 2809:             $cats = {};
 2810:         }
 2811:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2812:     }
 2813:     return $cats;
 2814: }
 2815: 
 2816: sub get_dom_instcats {
 2817:     my ($dom) = @_;
 2818:     return unless (&domain($dom));
 2819:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2820:     unless (defined($cached)) {
 2821:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2822:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2823:         if ($totcodes > 0) {
 2824:             my $caller = 'global';
 2825:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2826:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2827:                 $instcats = {
 2828:                                 codes => \%codes,
 2829:                                 codetitles => \@codetitles,
 2830:                                 cat_titles => \%cat_titles,
 2831:                                 cat_order => \%cat_order,
 2832:                             };
 2833:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2834:             }
 2835:         }
 2836:     }
 2837:     return $instcats;
 2838: }
 2839: 
 2840: sub retrieve_instcodes {
 2841:     my ($coursecodes,$dom) = @_;
 2842:     my $totcodes;
 2843:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2844:     foreach my $course (keys(%courses)) {
 2845:         if (ref($courses{$course}) eq 'HASH') {
 2846:             if ($courses{$course}{'inst_code'} ne '') {
 2847:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2848:                 $totcodes ++;
 2849:             }
 2850:         }
 2851:     }
 2852:     return $totcodes;
 2853: }
 2854: 
 2855: sub course_portal_url {
 2856:     my ($cnum,$cdom,$r) = @_;
 2857:     my $chome = &homeserver($cnum,$cdom);
 2858:     my $hostname = &hostname($chome);
 2859:     my $protocol = $protocol{$chome};
 2860:     $protocol = 'http' if ($protocol ne 'https');
 2861:     my %domdefaults = &get_domain_defaults($cdom);
 2862:     my $firsturl;
 2863:     if ($domdefaults{'portal_def'}) {
 2864:         $firsturl = $domdefaults{'portal_def'};
 2865:     } else {
 2866:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
 2867:         $hostname = $alias if ($alias ne '');
 2868:         $firsturl = $protocol.'://'.$hostname;
 2869:     }
 2870:     return $firsturl;
 2871: }
 2872: 
 2873: # --------------------------------------------- Get domain config for passwords
 2874: 
 2875: sub get_passwdconf {
 2876:     my ($dom) = @_;
 2877:     my (%passwdconf,$gotconf,$lookup);
 2878:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2879:     if (defined($cached)) {
 2880:         if (ref($result) eq 'HASH') {
 2881:             %passwdconf = %{$result};
 2882:             $gotconf = 1;
 2883:         }
 2884:     }
 2885:     unless ($gotconf) {
 2886:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2887:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2888:             %passwdconf = %{$domconfig{'passwords'}};
 2889:         }
 2890:         my $cachetime = 24*60*60;
 2891:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2892:     }
 2893:     return %passwdconf;
 2894: }
 2895: 
 2896: # --------------------------------------------------- Assign a key to a student
 2897: 
 2898: sub assign_access_key {
 2899: #
 2900: # a valid key looks like uname:udom#comments
 2901: # comments are being appended
 2902: #
 2903:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2904:     $kdom=
 2905:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2906:     $knum=
 2907:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2908:     $cdom=
 2909:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2910:     $cnum=
 2911:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2912:     $udom=$env{'user.name'} unless (defined($udom));
 2913:     $uname=$env{'user.domain'} unless (defined($uname));
 2914:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2915:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2916:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2917:                                                   # assigned to this person
 2918:                                                   # - this should not happen,
 2919:                                                   # unless something went wrong
 2920:                                                   # the first time around
 2921: # ready to assign
 2922:         $logentry=$1.'; '.$logentry;
 2923:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2924:                                                  $kdom,$knum) eq 'ok') {
 2925: # key now belongs to user
 2926: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2927:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2928:                 &appenv({'environment.'.$envkey => $ckey});
 2929:                 return 'ok';
 2930:             } else {
 2931:                 return 
 2932:   'error: Count not permanently assign key, will need to be re-entered later.';
 2933: 	    }
 2934:         } else {
 2935:             return 'error: Could not assign key, try again later.';
 2936:         }
 2937:     } elsif (!$existing{$ckey}) {
 2938: # the key does not exist
 2939: 	return 'error: The key does not exist';
 2940:     } else {
 2941: # the key is somebody else's
 2942: 	return 'error: The key is already in use';
 2943:     }
 2944: }
 2945: 
 2946: # ------------------------------------------ put an additional comment on a key
 2947: 
 2948: sub comment_access_key {
 2949: #
 2950: # a valid key looks like uname:udom#comments
 2951: # comments are being appended
 2952: #
 2953:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2954:     $cdom=
 2955:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2956:     $cnum=
 2957:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2958:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2959:     if ($existing{$ckey}) {
 2960:         $existing{$ckey}.='; '.$logentry;
 2961: # ready to assign
 2962:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2963:                                                  $cdom,$cnum) eq 'ok') {
 2964: 	    return 'ok';
 2965:         } else {
 2966: 	    return 'error: Count not store comment.';
 2967:         }
 2968:     } else {
 2969: # the key does not exist
 2970: 	return 'error: The key does not exist';
 2971:     }
 2972: }
 2973: 
 2974: # ------------------------------------------------------ Generate a set of keys
 2975: 
 2976: sub generate_access_keys {
 2977:     my ($number,$cdom,$cnum,$logentry)=@_;
 2978:     $cdom=
 2979:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2980:     $cnum=
 2981:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2982:     unless (&allowed('mky',$cdom)) { return 0; }
 2983:     unless (($cdom) && ($cnum)) { return 0; }
 2984:     if ($number>10000) { return 0; }
 2985:     sleep(2); # make sure don't get same seed twice
 2986:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2987:     my $total=0;
 2988:     for (my $i=1;$i<=$number;$i++) {
 2989:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2990:                   sprintf("%lx",int(100000*rand)).'-'.
 2991:                   sprintf("%lx",int(100000*rand));
 2992:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2993:        $newkey=~s/0/h/g; # and also 0 and O
 2994:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2995:        if ($existing{$newkey}) {
 2996:            $i--;
 2997:        } else {
 2998: 	  if (&put('accesskeys',
 2999:               { $newkey => '# generated '.localtime().
 3000:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3001:                            '; '.$logentry },
 3002: 		   $cdom,$cnum) eq 'ok') {
 3003:               $total++;
 3004: 	  }
 3005:        }
 3006:     }
 3007:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3008:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3009:     return $total;
 3010: }
 3011: 
 3012: # ------------------------------------------------------- Validate an accesskey
 3013: 
 3014: sub validate_access_key {
 3015:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3016:     $cdom=
 3017:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3018:     $cnum=
 3019:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3020:     $udom=$env{'user.domain'} unless (defined($udom));
 3021:     $uname=$env{'user.name'} unless (defined($uname));
 3022:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3023:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3024: }
 3025: 
 3026: # ------------------------------------- Find the section of student in a course
 3027: sub devalidate_getsection_cache {
 3028:     my ($udom,$unam,$courseid)=@_;
 3029:     my $hashid="$udom:$unam:$courseid";
 3030:     &devalidate_cache_new('getsection',$hashid);
 3031: }
 3032: 
 3033: sub courseid_to_courseurl {
 3034:     my ($courseid) = @_;
 3035:     #already url style courseid
 3036:     return $courseid if ($courseid =~ m{^/});
 3037: 
 3038:     if (exists($env{'course.'.$courseid.'.num'})) {
 3039: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3040: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3041: 	return "/$cdom/$cnum";
 3042:     }
 3043: 
 3044:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 3045:     if (exists($courseinfo{'num'})) {
 3046: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3047:     }
 3048: 
 3049:     return undef;
 3050: }
 3051: 
 3052: sub getsection {
 3053:     my ($udom,$unam,$courseid)=@_;
 3054:     my $cachetime=1800;
 3055: 
 3056:     my $hashid="$udom:$unam:$courseid";
 3057:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3058:     if (defined($cached)) { return $result; }
 3059: 
 3060:     my %Pending; 
 3061:     my %Expired;
 3062:     #
 3063:     # Each role can either have not started yet (pending), be active, 
 3064:     #    or have expired.
 3065:     #
 3066:     # If there is an active role, we are done.
 3067:     #
 3068:     # If there is more than one role which has not started yet, 
 3069:     #     choose the one which will start sooner
 3070:     # If there is one role which has not started yet, return it.
 3071:     #
 3072:     # If there is more than one expired role, choose the one which ended last.
 3073:     # If there is a role which has expired, return it.
 3074:     #
 3075:     $courseid = &courseid_to_courseurl($courseid);
 3076:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3077:     foreach my $key (keys(%roleshash)) {
 3078:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3079:         my $section=$1;
 3080:         if ($key eq $courseid.'_st') { $section=''; }
 3081:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3082:         my $now=time;
 3083:         if (defined($end) && $end && ($now > $end)) {
 3084:             $Expired{$end}=$section;
 3085:             next;
 3086:         }
 3087:         if (defined($start) && $start && ($now < $start)) {
 3088:             $Pending{$start}=$section;
 3089:             next;
 3090:         }
 3091:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3092:     }
 3093:     #
 3094:     # Presumedly there will be few matching roles from the above
 3095:     # loop and the sorting time will be negligible.
 3096:     if (scalar(keys(%Pending))) {
 3097:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3098:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3099:     } 
 3100:     if (scalar(keys(%Expired))) {
 3101:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3102:         my $time = pop(@sorted);
 3103:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3104:     }
 3105:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3106: }
 3107: 
 3108: sub save_cache {
 3109:     &purge_remembered();
 3110:     #&Apache::loncommon::validate_page();
 3111:     undef(%env);
 3112:     undef($env_loaded);
 3113: }
 3114: 
 3115: my $to_remember=-1;
 3116: my %remembered;
 3117: my %accessed;
 3118: my $kicks=0;
 3119: my $hits=0;
 3120: sub make_key {
 3121:     my ($name,$id) = @_;
 3122:     if (length($id) > 65 
 3123: 	&& length(&escape($id)) > 200) {
 3124: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3125:     }
 3126:     return &escape($name.':'.$id);
 3127: }
 3128: 
 3129: sub devalidate_cache_new {
 3130:     my ($name,$id,$debug) = @_;
 3131:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3132:     my $remembered_id=$name.':'.$id;
 3133:     $id=&make_key($name,$id);
 3134:     $memcache->delete($id);
 3135:     delete($remembered{$remembered_id});
 3136:     delete($accessed{$remembered_id});
 3137: }
 3138: 
 3139: sub is_cached_new {
 3140:     my ($name,$id,$debug) = @_;
 3141:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3142:     if (exists($remembered{$remembered_id})) {
 3143: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3144: 	$accessed{$remembered_id}=[&gettimeofday()];
 3145: 	$hits++;
 3146: 	return ($remembered{$remembered_id},1);
 3147:     }
 3148:     $id=&make_key($name,$id);
 3149:     my $value = $memcache->get($id);
 3150:     if (!(defined($value))) {
 3151: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3152: 	return (undef,undef);
 3153:     }
 3154:     if ($value eq '__undef__') {
 3155: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3156: 	$value=undef;
 3157:     }
 3158:     &make_room($remembered_id,$value,$debug);
 3159:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3160:     return ($value,1);
 3161: }
 3162: 
 3163: sub do_cache_new {
 3164:     my ($name,$id,$value,$time,$debug) = @_;
 3165:     my $remembered_id=$name.':'.$id;
 3166:     $id=&make_key($name,$id);
 3167:     my $setvalue=$value;
 3168:     if (!defined($setvalue)) {
 3169: 	$setvalue='__undef__';
 3170:     }
 3171:     if (!defined($time) ) {
 3172: 	$time=600;
 3173:     }
 3174:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3175:     my $result = $memcache->set($id,$setvalue,$time);
 3176:     if (! $result) {
 3177: 	&logthis("caching of id -> $id  failed");
 3178: 	$memcache->disconnect_all();
 3179:     }
 3180:     # need to make a copy of $value
 3181:     &make_room($remembered_id,$value,$debug);
 3182:     return $value;
 3183: }
 3184: 
 3185: sub make_room {
 3186:     my ($remembered_id,$value,$debug)=@_;
 3187: 
 3188:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3189:                                     : $value;
 3190:     if ($to_remember<0) { return; }
 3191:     $accessed{$remembered_id}=[&gettimeofday()];
 3192:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3193:     my $to_kick;
 3194:     my $max_time=0;
 3195:     foreach my $other (keys(%accessed)) {
 3196: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3197: 	    $to_kick=$other;
 3198: 	    $max_time=&tv_interval($accessed{$other});
 3199: 	}
 3200:     }
 3201:     delete($remembered{$to_kick});
 3202:     delete($accessed{$to_kick});
 3203:     $kicks++;
 3204:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3205:     return;
 3206: }
 3207: 
 3208: sub purge_remembered {
 3209:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3210:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3211:     undef(%remembered);
 3212:     undef(%accessed);
 3213: }
 3214: # ------------------------------------- Read an entry from a user's environment
 3215: 
 3216: sub userenvironment {
 3217:     my ($udom,$unam,@what)=@_;
 3218:     my $items;
 3219:     foreach my $item (@what) {
 3220:         $items.=&escape($item).'&';
 3221:     }
 3222:     $items=~s/\&$//;
 3223:     my %returnhash=();
 3224:     my $uhome = &homeserver($unam,$udom);
 3225:     unless ($uhome eq 'no_host') {
 3226:         my @answer=split(/\&/, 
 3227:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3228:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3229:             return %returnhash;
 3230:         }
 3231:         my $i;
 3232:         for ($i=0;$i<=$#what;$i++) {
 3233: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3234:         }
 3235:     }
 3236:     return %returnhash;
 3237: }
 3238: 
 3239: # ---------------------------------------------------------- Get a studentphoto
 3240: sub studentphoto {
 3241:     my ($udom,$unam,$ext) = @_;
 3242:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3243:     if (defined($env{'request.course.id'})) {
 3244:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3245:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3246:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3247:             } else {
 3248:                 my ($result,$perm_reqd)=
 3249: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3250:                 if ($result eq 'ok') {
 3251:                     if (!($perm_reqd eq 'yes')) {
 3252:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3253:                     }
 3254:                 }
 3255:             }
 3256:         }
 3257:     } else {
 3258:         my ($result,$perm_reqd) = 
 3259: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3260:         if ($result eq 'ok') {
 3261:             if (!($perm_reqd eq 'yes')) {
 3262:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3263:             }
 3264:         }
 3265:     }
 3266:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3267: }
 3268: 
 3269: sub retrievestudentphoto {
 3270:     my ($udom,$unam,$ext,$type) = @_;
 3271:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3272:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3273:     if ($ret eq 'ok') {
 3274:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3275:         if ($type eq 'thumbnail') {
 3276:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3277:         }
 3278:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3279:         return $tokenurl;
 3280:     } else {
 3281:         if ($type eq 'thumbnail') {
 3282:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3283:         } else { 
 3284:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3285:         }
 3286:     }
 3287: }
 3288: 
 3289: # -------------------------------------------------------------------- New chat
 3290: 
 3291: sub chatsend {
 3292:     my ($newentry,$anon,$group)=@_;
 3293:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3294:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3295:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3296:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3297: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3298: 		   &escape($newentry)).':'.$group,$chome);
 3299: }
 3300: 
 3301: # ------------------------------------------ Find current version of a resource
 3302: 
 3303: sub getversion {
 3304:     my $fname=&clutter(shift);
 3305:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3306:     return &currentversion(&filelocation('',$fname));
 3307: }
 3308: 
 3309: sub currentversion {
 3310:     my $fname=shift;
 3311:     my $author=$fname;
 3312:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3313:     my ($udom,$uname)=split(/\//,$author);
 3314:     my $home=&homeserver($uname,$udom);
 3315:     if ($home eq 'no_host') { 
 3316:         return -1; 
 3317:     }
 3318:     my $answer=&reply("currentversion:$fname",$home);
 3319:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3320: 	return -1;
 3321:     }
 3322:     return $answer;
 3323: }
 3324: 
 3325: #
 3326: # Return special version number of resource if set by override, empty otherwise
 3327: #
 3328: sub usedversion {
 3329:     my $fname=shift;
 3330:     unless ($fname) { $fname=$env{'request.uri'}; }
 3331:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3332:     if ($urlversion) { return $urlversion; }
 3333:     return '';
 3334: }
 3335: 
 3336: # ----------------------------- Subscribe to a resource, return URL if possible
 3337: 
 3338: sub subscribe {
 3339:     my $fname=shift;
 3340:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3341:     $fname=~s/[\n\r]//g;
 3342:     my $author=$fname;
 3343:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3344:     my ($udom,$uname)=split(/\//,$author);
 3345:     my $home=homeserver($uname,$udom);
 3346:     if ($home eq 'no_host') {
 3347:         return 'not_found';
 3348:     }
 3349:     my $answer=reply("sub:$fname",$home);
 3350:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3351: 	$answer.=' by '.$home;
 3352:     }
 3353:     return $answer;
 3354: }
 3355:     
 3356: # -------------------------------------------------------------- Replicate file
 3357: 
 3358: sub repcopy {
 3359:     my $filename=shift;
 3360:     $filename=~s/\/+/\//g;
 3361:     my $londocroot = $perlvar{'lonDocRoot'};
 3362:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3363:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3364:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3365: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3366: 	return &repcopy_userfile($filename);
 3367:     }
 3368:     $filename=~s/[\n\r]//g;
 3369:     my $transname="$filename.in.transfer";
 3370: # FIXME: this should flock
 3371:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3372:     my $remoteurl=subscribe($filename);
 3373:     if ($remoteurl =~ /^con_lost by/) {
 3374: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3375:            return 'unavailable';
 3376:     } elsif ($remoteurl eq 'not_found') {
 3377: 	   #&logthis("Subscribe returned not_found: $filename");
 3378: 	   return 'not_found';
 3379:     } elsif ($remoteurl =~ /^rejected by/) {
 3380: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3381:            return 'forbidden';
 3382:     } elsif ($remoteurl eq 'directory') {
 3383:            return 'ok';
 3384:     } else {
 3385:         my $author=$filename;
 3386:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3387:         my ($udom,$uname)=split(/\//,$author);
 3388:         my $home=homeserver($uname,$udom);
 3389:         unless ($home eq $perlvar{'lonHostID'}) {
 3390:            my @parts=split(/\//,$filename);
 3391:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3392:            if ($path ne "$londocroot/res") {
 3393:                &logthis("Malconfiguration for replication: $filename");
 3394: 	       return 'bad_request';
 3395:            }
 3396:            my $count;
 3397:            for ($count=5;$count<$#parts;$count++) {
 3398:                $path.="/$parts[$count]";
 3399:                if ((-e $path)!=1) {
 3400: 		   mkdir($path,0777);
 3401:                }
 3402:            }
 3403:            my $request=new HTTP::Request('GET',"$remoteurl");
 3404:            my $response;
 3405:            if ($remoteurl =~ m{/raw/}) {
 3406:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3407:            } else {
 3408:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3409:            }
 3410:            if ($response->is_error()) {
 3411: 	       unlink($transname);
 3412:                my $message=$response->status_line;
 3413:                &logthis("<font color=\"blue\">WARNING:"
 3414:                        ." LWP get: $message: $filename</font>");
 3415:                return 'unavailable';
 3416:            } else {
 3417: 	       if ($remoteurl!~/\.meta$/) {
 3418:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3419:                   my $mresponse;
 3420:                   if ($remoteurl =~ m{/raw/}) {
 3421:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3422:                   } else {
 3423:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3424:                   }
 3425:                   if ($mresponse->is_error()) {
 3426: 		      unlink($filename.'.meta');
 3427:                       &logthis(
 3428:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3429:                   }
 3430: 	       }
 3431:                rename($transname,$filename);
 3432:                return 'ok';
 3433:            }
 3434:        }
 3435:     }
 3436: }
 3437: 
 3438: # ------------------------------------------------- Unsubscribe from a resource
 3439: 
 3440: sub unsubscribe {
 3441:     my ($fname) = @_;
 3442:     my $answer;
 3443:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3444:     $fname=~s/[\n\r]//g;
 3445:     my $author=$fname;
 3446:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3447:     my ($udom,$uname)=split(/\//,$author);
 3448:     my $home=homeserver($uname,$udom);
 3449:     if ($home eq 'no_host') {
 3450:         $answer = 'no_host';
 3451:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3452:         $answer = 'home';
 3453:     } else {
 3454:         my $defdom = $perlvar{'lonDefDomain'};
 3455:         if (&will_trust('content',$defdom,$udom)) {
 3456:             $answer = reply("unsub:$fname",$home);
 3457:         } else {
 3458:             $answer = 'untrusted';
 3459:         }
 3460:     }
 3461:     return $answer;
 3462: }
 3463: 
 3464: # ------------------------------------------------ Get server side include body
 3465: sub ssi_body {
 3466:     my ($filelink,%form)=@_;
 3467:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3468:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3469:     }
 3470:     my $output='';
 3471:     my $response;
 3472:     if ($filelink=~/^https?\:/) {
 3473:        ($output,$response)=&externalssi($filelink);
 3474:     } else {
 3475:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3476:        $filelink .= 'inhibitmenu=yes';
 3477:        ($output,$response)=&ssi($filelink,%form);
 3478:     }
 3479:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3480:     $output=~s/^.*?\<body[^\>]*\>//si;
 3481:     $output=~s/\<\/body\s*\>.*?$//si;
 3482:     if (wantarray) {
 3483:         return ($output, $response);
 3484:     } else {
 3485:         return $output;
 3486:     }
 3487: }
 3488: 
 3489: # --------------------------------------------------------- Server Side Include
 3490: 
 3491: sub absolute_url {
 3492:     my ($host_name,$unalias,$keep_proto) = @_;
 3493:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3494:     if ($host_name eq '') {
 3495: 	$host_name = $ENV{'SERVER_NAME'};
 3496:     }
 3497:     if ($unalias) {
 3498:         my $alias = &get_proxy_alias();
 3499:         if ($alias eq $host_name) {
 3500:             my $lonhost = $perlvar{'lonHostID'};
 3501:             my $hostname = &hostname($lonhost);
 3502:             my $lcproto; 
 3503:             if (($keep_proto) || ($hostname eq '')) {
 3504:                 $lcproto = $protocol;
 3505:             } else {
 3506:                 $lcproto = $protocol{$lonhost};
 3507:                 $lcproto = 'http' if ($lcproto ne 'https');
 3508:                 $lcproto .= '://';
 3509:             }
 3510:             unless ($hostname eq '') {
 3511:                 return $lcproto.$hostname;
 3512:             }
 3513:         }
 3514:     }
 3515:     return $protocol.$host_name;
 3516: }
 3517: 
 3518: #
 3519: #   Server side include.
 3520: # Parameters:
 3521: #  fn     Possibly encrypted resource name/id.
 3522: #  form   Hash that describes how the rendering should be done
 3523: #         and other things.
 3524: # Returns:
 3525: #   Scalar context: The content of the response.
 3526: #   Array context:  2 element list of the content and the full response object.
 3527: #     
 3528: sub ssi {
 3529: 
 3530:     my ($fn,%form)=@_;
 3531:     my ($host,$request,$response);
 3532:     $host = &absolute_url('',1);
 3533: 
 3534:     $form{'no_update_last_known'}=1;
 3535:     &Apache::lonenc::check_encrypt(\$fn);
 3536:     if (%form) {
 3537:       $request=new HTTP::Request('POST',$host.$fn);
 3538:       $request->content(join('&',map { 
 3539:             my $name = escape($_);
 3540:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3541:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3542:             : &escape($form{$_}) );    
 3543:         } keys(%form)));
 3544:     } else {
 3545:       $request=new HTTP::Request('GET',$host.$fn);
 3546:     }
 3547: 
 3548:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3549:     my $lonhost = $perlvar{'lonHostID'};
 3550:     my $islocal;
 3551:     if (($env{'request.course.id'}) &&
 3552:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3553:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3554:         ($form{'grade_symb'} ne '') &&
 3555:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3556:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3557:         $islocal = 1;
 3558:     }
 3559:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3560:                                              '','','',$islocal);
 3561: 
 3562:     if (wantarray) {
 3563: 	return ($response->content, $response);
 3564:     } else {
 3565: 	return $response->content;
 3566:     }
 3567: }
 3568: 
 3569: sub externalssi {
 3570:     my ($url)=@_;
 3571:     my $request=new HTTP::Request('GET',$url);
 3572:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3573:     if (wantarray) {
 3574:         return ($response->content, $response);
 3575:     } else {
 3576:         return $response->content;
 3577:     }
 3578: }
 3579: 
 3580: 
 3581: # If the local copy of a replicated resource is outdated, trigger a  
 3582: # connection from the homeserver to flush the delayed queue. If no update 
 3583: # happens, remove local copies of outdated resource (and corresponding
 3584: # metadata file).
 3585: 
 3586: sub remove_stale_resfile {
 3587:     my ($url) = @_;
 3588:     my $removed;
 3589:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3590:         my $audom = $1;
 3591:         my $auname = $2;
 3592:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3593:             my $homeserver = &homeserver($auname,$audom);
 3594:             unless (($homeserver eq 'no_host') ||
 3595:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3596:                 my $fname = &filelocation('',$url);
 3597:                 if (-e $fname) {
 3598:                     my $hostname = &hostname($homeserver);
 3599:                     if ($hostname) {
 3600:                         my $protocol = $protocol{$homeserver};
 3601:                         $protocol = 'http' if ($protocol ne 'https');
 3602:                         my $uri = &declutter($url);
 3603:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3604:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3605:                         if ($response->is_success()) {
 3606:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3607:                             my $locmodtime = (stat($fname))[9];
 3608:                             if ($locmodtime < $remmodtime) {
 3609:                                 my $stale;
 3610:                                 my $answer = &reply('pong',$homeserver);
 3611:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3612:                                     sleep(0.2);
 3613:                                     $locmodtime = (stat($fname))[9];
 3614:                                     if ($locmodtime < $remmodtime) {
 3615:                                         my $posstransfer = $fname.'.in.transfer';
 3616:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3617:                                             $removed = 1;
 3618:                                         } else {
 3619:                                             $stale = 1;
 3620:                                         }
 3621:                                     } else {
 3622:                                         $removed = 1;
 3623:                                     }
 3624:                                 } else {
 3625:                                     $stale = 1;
 3626:                                 }
 3627:                                 if ($stale) {
 3628:                                     if (unlink($fname)) {
 3629:                                         if ($uri!~/\.meta$/) {
 3630:                                             if (-e $fname.'.meta') {
 3631:                                                 unlink($fname.'.meta');
 3632:                                             }
 3633:                                         }
 3634:                                         my $unsubresult = &unsubscribe($fname);
 3635:                                         unless ($unsubresult eq 'ok') {
 3636:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3637:                                         }
 3638:                                         $removed = 1;
 3639:                                     }
 3640:                                 }
 3641:                             }
 3642:                         }
 3643:                     }
 3644:                 }
 3645:             }
 3646:         }
 3647:     }
 3648:     return $removed;
 3649: }
 3650: 
 3651: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3652: 
 3653: sub allowuploaded {
 3654:     my ($srcurl,$url)=@_;
 3655:     $url=&clutter(&declutter($url));
 3656:     my $dir=$url;
 3657:     $dir=~s/\/[^\/]+$//;
 3658:     my %httpref=();
 3659:     my $httpurl=&hreflocation('',$url);
 3660:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3661:     &Apache::lonnet::appenv(\%httpref);
 3662: }
 3663: 
 3664: #
 3665: # Determine if the current user should be able to edit a particular resource,
 3666: # when viewing in course context.
 3667: # (a) When viewing resource used to determine if "Edit" item is included in 
 3668: #     Functions.
 3669: # (b) When displaying folder contents in course editor, used to determine if
 3670: #     "Edit" link will be displayed alongside resource.
 3671: #
 3672: #  input: six args -- filename (decluttered), course number, course domain,
 3673: #                   url, symb (if registered) and group (if this is a group
 3674: #                   item -- e.g., bulletin board, group page etc.).
 3675: #  output: array of five scalars -- 
 3676: #          $cfile -- url for file editing if editable on current server
 3677: #          $home -- homeserver of resource (i.e., for author if published,
 3678: #                                           or course if uploaded.).
 3679: #          $switchserver --  1 if server switch will be needed.
 3680: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3681: #          $forceview -- 1 if icon/link should be to go to view mode
 3682: #
 3683: 
 3684: sub can_edit_resource {
 3685:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3686:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3687: #
 3688: # For aboutme pages user can only edit his/her own.
 3689: #
 3690:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3691:         my ($sdom,$sname) = ($1,$2);
 3692:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3693:             $home = $env{'user.home'};
 3694:             $cfile = $resurl;
 3695:             if ($env{'form.forceedit'}) {
 3696:                 $forceview = 1;
 3697:             } else {
 3698:                 $forceedit = 1;
 3699:             }
 3700:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3701:         } else {
 3702:             return;
 3703:         }
 3704:     }
 3705: 
 3706:     if ($env{'request.course.id'}) {
 3707:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3708:         if ($group ne '') {
 3709: # if this is a group homepage or group bulletin board, check group privs
 3710:             my $allowed = 0;
 3711:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3712:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3713:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3714:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3715:                     $allowed = 1;
 3716:                 }
 3717:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3718:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3719:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3720:                     $allowed = 1;
 3721:                 }
 3722:             }
 3723:             if ($allowed) {
 3724:                 $home=&homeserver($cnum,$cdom);
 3725:                 if ($env{'form.forceedit'}) {
 3726:                     $forceview = 1;
 3727:                 } else {
 3728:                     $forceedit = 1;
 3729:                 }
 3730:                 $cfile = $resurl;
 3731:             } else {
 3732:                 return;
 3733:             }
 3734:         } else {
 3735:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3736:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3737:                     return;
 3738:                 }
 3739:             } elsif (!$crsedit) {
 3740: #
 3741: # No edit allowed where CC has switched to student role.
 3742: #
 3743:                 return;
 3744:             }
 3745:         }
 3746:     }
 3747: 
 3748:     if ($file ne '') {
 3749:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3750:             if (&is_course_upload($file,$cnum,$cdom)) {
 3751:                 $uploaded = 1;
 3752:                 $incourse = 1;
 3753:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3754:                     $cfile = &hreflocation('',$file);
 3755:                     if ($env{'form.forceedit'}) {
 3756:                         $forceview = 1;
 3757:                     } else {
 3758:                         $forceedit = 1;
 3759:                     }
 3760:                 }
 3761:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3762:                 $incourse = 1;
 3763:                 if ($env{'form.forceedit'}) {
 3764:                     $forceview = 1;
 3765:                 } else {
 3766:                     $forceedit = 1;
 3767:                 }
 3768:                 $cfile = $resurl;
 3769:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3770:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3771:                     $incourse = 1;
 3772:                     if ($env{'form.forceedit'}) {
 3773:                         $forceview = 1;
 3774:                     } else {
 3775:                         $forceedit = 1;
 3776:                     }
 3777:                     $cfile = $resurl;
 3778:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3779:                     $incourse = 1;
 3780:                     $cfile = $resurl.'/smpedit';
 3781:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3782:                     $incourse = 1;
 3783:                     if ($env{'form.forceedit'}) {
 3784:                         $forceview = 1;
 3785:                     } else {
 3786:                         $forceedit = 1;
 3787:                     }
 3788:                     $cfile = $resurl;
 3789:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3790:                     my ($map,$id,$res) = &decode_symb($symb);
 3791:                     if ($map =~ /\.page$/) {
 3792:                         $incourse = 1;
 3793:                         if ($env{'form.forceedit'}) {
 3794:                             $forceview = 1;
 3795:                             $cfile = $map;
 3796:                         } else {
 3797:                             $forceedit = 1;
 3798:                             $cfile =  '/adm/wrapper'.$resurl;
 3799:                         }
 3800:                     }
 3801:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3802:                     $incourse = 1;
 3803:                     if ($env{'form.forceedit'}) {
 3804:                         $forceview = 1;
 3805:                     } else {
 3806:                         $forceedit = 1;
 3807:                     }
 3808:                     $cfile = $resurl;
 3809:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3810:                     $incourse = 1;
 3811:                     if ($env{'form.forceedit'}) {
 3812:                         $forceview = 1;
 3813:                     } else {
 3814:                         $forceedit = 1;
 3815:                     }
 3816:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3817:                 }
 3818:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3819:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3820:                 if (&is_on_map($template)) { 
 3821:                     $incourse = 1;
 3822:                     $forceview = 1;
 3823:                     $cfile = $template;
 3824:                 }
 3825:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3826:                 $incourse = 1;
 3827:                 if ($env{'form.forceedit'}) {
 3828:                     $forceview = 1;
 3829:                 } else {
 3830:                     $forceedit = 1;
 3831:                 }
 3832:                 $cfile = $resurl;
 3833:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3834:                 $incourse = 1;
 3835:                 if ($env{'form.forceedit'}) {
 3836:                     $forceview = 1;
 3837:                 } else {
 3838:                     $forceedit = 1;
 3839:                 }
 3840:                 $cfile = $resurl;
 3841:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3842:                 $incourse = 1;
 3843:                 $forceview = 1;
 3844:                 if ($symb) {
 3845:                     my ($map,$id,$res)=&decode_symb($symb);
 3846:                     $env{'request.symb'} = $symb;
 3847:                     $cfile = &clutter($res);
 3848:                 } else {
 3849:                     $cfile = $env{'form.suppurl'};
 3850:                     my $escfile = &unescape($cfile);
 3851:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3852:                         $cfile = '/adm/wrapper'.$escfile;
 3853:                     } else {
 3854:                         $escfile =~ s{^http://}{};
 3855:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3856:                     }
 3857:                 }
 3858:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3859:                 if ($env{'form.forceedit'}) {
 3860:                     $forceview = 1;
 3861:                 } else {
 3862:                     $forceedit = 1;
 3863:                 }
 3864:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3865:             }
 3866:         }
 3867:         if ($uploaded || $incourse) {
 3868:             $home=&homeserver($cnum,$cdom);
 3869:         } elsif ($file !~ m{/$}) {
 3870:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3871:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3872:             # Check that the user has permission to edit this resource
 3873:             my $setpriv = 1;
 3874:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3875:             if (defined($cfudom)) {
 3876:                 $home=&homeserver($cfuname,$cfudom);
 3877:                 $cfile=$file;
 3878:             }
 3879:         }
 3880:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3881:             (($home ne '') && ($home ne 'no_host'))) {
 3882:             my @ids=&current_machine_ids();
 3883:             unless (grep(/^\Q$home\E$/,@ids)) {
 3884:                 $switchserver=1;
 3885:             }
 3886:         }
 3887:     }
 3888:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3889: }
 3890: 
 3891: sub is_course_upload {
 3892:     my ($file,$cnum,$cdom) = @_;
 3893:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3894:     $uploadpath =~ s{^\/}{};
 3895:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3896:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3897:         return 1;
 3898:     }
 3899:     return;
 3900: }
 3901: 
 3902: sub in_course {
 3903:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3904:     if ($hideprivileged) {
 3905:         my $skipuser;
 3906:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3907:         my @possdoms = ($cdom);  
 3908:         if ($coursehash{'checkforpriv'}) { 
 3909:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3910:         }
 3911:         if (&privileged($uname,$udom,\@possdoms)) {
 3912:             $skipuser = 1;
 3913:             if ($coursehash{'nothideprivileged'}) {
 3914:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3915:                     my $user;
 3916:                     if ($item =~ /:/) {
 3917:                         $user = $item;
 3918:                     } else {
 3919:                         $user = join(':',split(/[\@]/,$item));
 3920:                     }
 3921:                     if ($user eq $uname.':'.$udom) {
 3922:                         undef($skipuser);
 3923:                         last;
 3924:                     }
 3925:                 }
 3926:             }
 3927:             if ($skipuser) {
 3928:                 return 0;
 3929:             }
 3930:         }
 3931:     }
 3932:     $type ||= 'any';
 3933:     if (!defined($cdom) || !defined($cnum)) {
 3934:         my $cid  = $env{'request.course.id'};
 3935:         $cdom = $env{'course.'.$cid.'.domain'};
 3936:         $cnum = $env{'course.'.$cid.'.num'};
 3937:     }
 3938:     my $typesref;
 3939:     if (($type eq 'any') || ($type eq 'all')) {
 3940:         $typesref = ['active','previous','future'];
 3941:     } elsif ($type eq 'previous' || $type eq 'future') {
 3942:         $typesref = [$type];
 3943:     }
 3944:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3945:                               $typesref,undef,[$cdom]);
 3946:     my ($tmp) = keys(%roles);
 3947:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3948:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3949:     if (@course_roles > 0) {
 3950:         return 1;
 3951:     }
 3952:     return 0;
 3953: }
 3954: 
 3955: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3956: # input: action, courseID, current domain, intended
 3957: #        path to file, source of file, instruction to parse file for objects,
 3958: #        ref to hash for embedded objects,
 3959: #        ref to hash for codebase of java objects.
 3960: #        reference to scalar to accommodate mime type determined
 3961: #          from File::MMagic if $parser = parse.
 3962: #
 3963: # output: url to file (if action was uploaddoc), 
 3964: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3965: #
 3966: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3967: # course.
 3968: #
 3969: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3970: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3971: #          course's home server.
 3972: #
 3973: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3974: #          be copied from $source (current location) to 
 3975: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3976: #         and will then be copied to
 3977: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3978: #         course's home server.
 3979: #
 3980: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3981: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3982: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3983: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3984: #         in course's home server.
 3985: #
 3986: 
 3987: sub process_coursefile {
 3988:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3989:         $mimetype)=@_;
 3990:     my $fetchresult;
 3991:     my $home=&homeserver($docuname,$docudom);
 3992:     if ($action eq 'propagate') {
 3993:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3994: 			     $home);
 3995:     } else {
 3996:         my $fpath = '';
 3997:         my $fname = $file;
 3998:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3999:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4000:         my $filepath = &build_filepath($fpath);
 4001:         if ($action eq 'copy') {
 4002:             if ($source eq '') {
 4003:                 $fetchresult = 'no source file';
 4004:                 return $fetchresult;
 4005:             } else {
 4006:                 my $destination = $filepath.'/'.$fname;
 4007:                 rename($source,$destination);
 4008:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4009:                                  $home);
 4010:             }
 4011:         } elsif ($action eq 'uploaddoc') {
 4012:             open(my $fh,'>',$filepath.'/'.$fname);
 4013:             print $fh $env{'form.'.$source};
 4014:             close($fh);
 4015:             if ($parser eq 'parse') {
 4016:                 my $mm = new File::MMagic;
 4017:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4018:                 if ($type eq 'text/html') {
 4019:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4020:                     unless ($parse_result eq 'ok') {
 4021:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4022:                     }
 4023:                 }
 4024:                 if (ref($mimetype)) {
 4025:                     $$mimetype = $type;
 4026:                 } 
 4027:             }
 4028:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4029:                                  $home);
 4030:             if ($fetchresult eq 'ok') {
 4031:                 return '/uploaded/'.$fpath.'/'.$fname;
 4032:             } else {
 4033:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4034:                         ' to host '.$home.': '.$fetchresult);
 4035:                 return '/adm/notfound.html';
 4036:             }
 4037:         }
 4038:     }
 4039:     unless ( $fetchresult eq 'ok') {
 4040:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4041:              ' to host '.$home.': '.$fetchresult);
 4042:     }
 4043:     return $fetchresult;
 4044: }
 4045: 
 4046: sub build_filepath {
 4047:     my ($fpath) = @_;
 4048:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4049:     unless ($fpath eq '') {
 4050:         my @parts=split('/',$fpath);
 4051:         foreach my $part (@parts) {
 4052:             $filepath.= '/'.$part;
 4053:             if ((-e $filepath)!=1) {
 4054:                 mkdir($filepath,0777);
 4055:             }
 4056:         }
 4057:     }
 4058:     return $filepath;
 4059: }
 4060: 
 4061: sub store_edited_file {
 4062:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4063:     my $file = $primary_url;
 4064:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4065:     my $fpath = '';
 4066:     my $fname = $file;
 4067:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4068:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4069:     my $filepath = &build_filepath($fpath);
 4070:     open(my $fh,'>',$filepath.'/'.$fname);
 4071:     print $fh $content;
 4072:     close($fh);
 4073:     my $home=&homeserver($docuname,$docudom);
 4074:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4075: 			  $home);
 4076:     if ($$fetchresult eq 'ok') {
 4077:         return '/uploaded/'.$fpath.'/'.$fname;
 4078:     } else {
 4079:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4080: 		 ' to host '.$home.': '.$$fetchresult);
 4081:         return '/adm/notfound.html';
 4082:     }
 4083: }
 4084: 
 4085: sub clean_filename {
 4086:     my ($fname,$args)=@_;
 4087: # Replace Windows backslashes by forward slashes
 4088:     $fname=~s/\\/\//g;
 4089:     if (!$args->{'keep_path'}) {
 4090:         # Get rid of everything but the actual filename
 4091: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4092:     }
 4093: # Replace spaces by underscores
 4094:     $fname=~s/\s+/\_/g;
 4095: # Transliterate non-ascii text to ascii
 4096:     my $lang = &Apache::lonlocal::current_language();
 4097:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4098: # Replace all other weird characters by nothing
 4099:     $fname=~s{[^/\w\.\-]}{}g;
 4100: # Replace all .\d. sequences with _\d. so they no longer look like version
 4101: # numbers
 4102:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4103: # Replace three or more adjacent underscores with one for consistency 
 4104: # with loncfile::filename_check() so complete url can be extracted by
 4105: # lonnet::decode_symb()
 4106:     $fname=~s/_{3,}/_/g;
 4107:     return $fname;
 4108: }
 4109: 
 4110: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4111: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4112: # image with the same aspect ratio as the original, but with dimensions which do 
 4113: # not exceed $resizewidth and $resizeheight.
 4114:  
 4115: sub resizeImage {
 4116:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4117:     my $ima = Image::Magick->new;
 4118:     my $resized;
 4119:     if (-e $img_path) {
 4120:         $ima->Read($img_path);
 4121:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4122:             my $width = $ima->Get('width');
 4123:             my $height = $ima->Get('height');
 4124:             if ($width > $resizewidth) {
 4125: 	        my $factor = $width/$resizewidth;
 4126:                 my $newheight = $height/$factor;
 4127:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4128:                 $resized = 1;
 4129:             }
 4130:         }
 4131:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4132:             my $width = $ima->Get('width');
 4133:             my $height = $ima->Get('height');
 4134:             if ($height > $resizeheight) {
 4135:                 my $factor = $height/$resizeheight;
 4136:                 my $newwidth = $width/$factor;
 4137:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4138:                 $resized = 1;
 4139:             }
 4140:         }
 4141:         if ($resized) {
 4142:             $ima->Write($img_path);
 4143:         }
 4144:     }
 4145:     return;
 4146: }
 4147: 
 4148: # --------------- Take an uploaded file and put it into the userfiles directory
 4149: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4150: #                    the desired filename is in $env{"form.$formname.filename"}
 4151: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4152: #                                    canceloverwrite, scantron or ''.
 4153: #                   if 'coursedoc': upload to the current course
 4154: #                   if 'existingfile': write file to tmp/overwrites directory 
 4155: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4156: #                   $context is passed as argument to &finishuserfileupload
 4157: #        $subdir - directory in userfile to store the file into
 4158: #        $parser - instruction to parse file for objects ($parser = parse) or
 4159: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4160: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4161: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4162: #        $allfiles - reference to hash for embedded objects
 4163: #        $codebase - reference to hash for codebase of java objects
 4164: #        $desuname - username for permanent storage of uploaded file
 4165: #        $dsetudom - domain for permanaent storage of uploaded file
 4166: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4167: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4168: #        $resizewidth - width (pixels) to which to resize uploaded image
 4169: #        $resizeheight - height (pixels) to which to resize uploaded image
 4170: #        $mimetype - reference to scalar to accommodate mime type determined
 4171: #                    from File::MMagic.
 4172: # 
 4173: # output: url of file in userspace, or error: <message> 
 4174: #             or /adm/notfound.html if failure to upload occurse
 4175: 
 4176: sub userfileupload {
 4177:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4178:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4179:     if (!defined($subdir)) { $subdir='unknown'; }
 4180:     my $fname=$env{'form.'.$formname.'.filename'};
 4181:     $fname=&clean_filename($fname);
 4182:     # See if there is anything left
 4183:     unless ($fname) { return 'error: no uploaded file'; }
 4184:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4185:     if ($fname =~ /^\./) {
 4186:         my ($s,$usec) = &gettimeofday();
 4187:         while (length($usec) < 6) {
 4188:             $usec = '0'.$usec;
 4189:         }
 4190:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4191:     }
 4192:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4193:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4194:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4195:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4196:         my $now = time;
 4197:         my $filepath;
 4198:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4199:              $filepath = 'tmp/helprequests/'.$now;
 4200:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4201:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4202:                          '_'.$env{'user.domain'}.'/pending';
 4203:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4204:             my ($docuname,$docudom);
 4205:             if ($destudom =~ /^$match_domain$/) {
 4206:                 $docudom = $destudom;
 4207:             } else {
 4208:                 $docudom = $env{'user.domain'};
 4209:             }
 4210:             if ($destuname =~ /^$match_username$/) {
 4211:                 $docuname = $destuname;
 4212:             } else {
 4213:                 $docuname = $env{'user.name'};
 4214:             }
 4215:             if (exists($env{'form.group'})) {
 4216:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4217:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4218:             }
 4219:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4220:             if ($context eq 'canceloverwrite') {
 4221:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4222:                 if (-e  $tempfile) {
 4223:                     my @info = stat($tempfile);
 4224:                     if ($info[9] eq $env{'form.timestamp'}) {
 4225:                         unlink($tempfile);
 4226:                     }
 4227:                 }
 4228:                 return;
 4229:             }
 4230:         }
 4231:         # Create the directory if not present
 4232:         my @parts=split(/\//,$filepath);
 4233:         my $fullpath = $perlvar{'lonDaemons'};
 4234:         for (my $i=0;$i<@parts;$i++) {
 4235:             $fullpath .= '/'.$parts[$i];
 4236:             if ((-e $fullpath)!=1) {
 4237:                 mkdir($fullpath,0777);
 4238:             }
 4239:         }
 4240:         open(my $fh,'>',$fullpath.'/'.$fname);
 4241:         print $fh $env{'form.'.$formname};
 4242:         close($fh);
 4243:         if ($context eq 'existingfile') {
 4244:             my @info = stat($fullpath.'/'.$fname);
 4245:             return ($fullpath.'/'.$fname,$info[9]);
 4246:         } else {
 4247:             return $fullpath.'/'.$fname;
 4248:         }
 4249:     }
 4250:     if ($subdir eq 'scantron') {
 4251:         $fname = 'scantron_orig_'.$fname;
 4252:     } else {
 4253:         $fname="$subdir/$fname";
 4254:     }
 4255:     if ($context eq 'coursedoc') {
 4256: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4257: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4258:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4259:             return &finishuserfileupload($docuname,$docudom,
 4260: 					 $formname,$fname,$parser,$allfiles,
 4261: 					 $codebase,$thumbwidth,$thumbheight,
 4262:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4263:         } else {
 4264:             if ($env{'form.folder'}) {
 4265:                 $fname=$env{'form.folder'}.'/'.$fname;
 4266:             }
 4267:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4268: 				       $fname,$formname,$parser,
 4269: 				       $allfiles,$codebase,$mimetype);
 4270:         }
 4271:     } elsif (defined($destuname)) {
 4272:         my $docuname=$destuname;
 4273:         my $docudom=$destudom;
 4274: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4275: 				     $parser,$allfiles,$codebase,
 4276:                                      $thumbwidth,$thumbheight,
 4277:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4278:     } else {
 4279:         my $docuname=$env{'user.name'};
 4280:         my $docudom=$env{'user.domain'};
 4281:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4282:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4283:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4284:         }
 4285: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4286: 				     $parser,$allfiles,$codebase,
 4287:                                      $thumbwidth,$thumbheight,
 4288:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4289:     }
 4290: }
 4291: 
 4292: sub finishuserfileupload {
 4293:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4294:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4295:     my $path=$docudom.'/'.$docuname.'/';
 4296:     my $filepath=$perlvar{'lonDocRoot'};
 4297:   
 4298:     my ($fnamepath,$file,$fetchthumb);
 4299:     $file=$fname;
 4300:     if ($fname=~m|/|) {
 4301:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4302: 	$path.=$fnamepath.'/';
 4303:     }
 4304:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4305:     my $count;
 4306:     for ($count=4;$count<=$#parts;$count++) {
 4307:         $filepath.="/$parts[$count]";
 4308:         if ((-e $filepath)!=1) {
 4309: 	    mkdir($filepath,0777);
 4310:         }
 4311:     }
 4312: 
 4313: # Save the file
 4314:     {
 4315: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4316: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4317: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4318: 	    return '/adm/notfound.html';
 4319: 	}
 4320:         if ($context eq 'overwrite') {
 4321:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4322:             my $target = $filepath.'/'.$file;
 4323:             if (-e $source) {
 4324:                 my @info = stat($source);
 4325:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4326:                     unless (&File::Copy::move($source,$target)) {
 4327:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4328:                         return "Moving from $source failed";
 4329:                     }
 4330:                 } else {
 4331:                     return "Temporary file: $source had unexpected date/time for last modification";
 4332:                 }
 4333:             } else {
 4334:                 return "Temporary file: $source missing";
 4335:             }
 4336:         } elsif (!print FH ($env{'form.'.$formname})) {
 4337: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4338: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4339: 	    return '/adm/notfound.html';
 4340: 	}
 4341: 	close(FH);
 4342:         if ($resizewidth && $resizeheight) {
 4343:             my $mm = new File::MMagic;
 4344:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4345:             if ($mime_type =~ m{^image/}) {
 4346: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4347:             }  
 4348: 	}
 4349:     }
 4350:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4351:         if (ref($mimetype)) {
 4352:             if ($$mimetype eq '') {
 4353:                 my $mm = new File::MMagic;
 4354:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4355:                 $$mimetype = $type;
 4356:             }
 4357:         }
 4358:     }
 4359:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4360:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4361:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4362:                                                        $allfiles,$codebase);
 4363:             unless ($parse_result eq 'ok') {
 4364:                 &logthis('Failed to parse '.$filepath.$file.
 4365: 	   	         ' for embedded media: '.$parse_result); 
 4366:             }
 4367:         }
 4368:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4369:         my $format = $env{'form.scantron_format'};
 4370:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4371:     }
 4372:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4373:         my $input = $filepath.'/'.$file;
 4374:         my $output = $filepath.'/'.'tn-'.$file;
 4375:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4376:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4377:         system({$args[0]} @args);
 4378:         if (-e $filepath.'/'.'tn-'.$file) {
 4379:             $fetchthumb  = 1; 
 4380:         }
 4381:     }
 4382:  
 4383: # Notify homeserver to grep it
 4384: #
 4385:     my $docuhome=&homeserver($docuname,$docudom);	
 4386:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4387:     if ($fetchresult eq 'ok') {
 4388:         if ($fetchthumb) {
 4389:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4390:             if ($thumbresult ne 'ok') {
 4391:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4392:                          $docuhome.': '.$thumbresult);
 4393:             }
 4394:         }
 4395: #
 4396: # Return the URL to it
 4397:         return '/uploaded/'.$path.$file;
 4398:     } else {
 4399:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4400: 		 ': '.$fetchresult);
 4401:         return '/adm/notfound.html';
 4402:     }
 4403: }
 4404: 
 4405: sub extract_embedded_items {
 4406:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4407:     my @state = ();
 4408:     my (%lastids,%related,%shockwave,%flashvars);
 4409:     my %javafiles = (
 4410:                       codebase => '',
 4411:                       code => '',
 4412:                       archive => ''
 4413:                     );
 4414:     my %mediafiles = (
 4415:                       src => '',
 4416:                       movie => '',
 4417:                      );
 4418:     my $p;
 4419:     if ($content) {
 4420:         $p = HTML::LCParser->new($content);
 4421:     } else {
 4422:         $p = HTML::LCParser->new($fullpath);
 4423:     }
 4424:     while (my $t=$p->get_token()) {
 4425: 	if ($t->[0] eq 'S') {
 4426: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4427: 	    push(@state, $tagname);
 4428:             if (lc($tagname) eq 'allow') {
 4429:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4430:             }
 4431: 	    if (lc($tagname) eq 'img') {
 4432: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4433: 	    }
 4434: 	    if (lc($tagname) eq 'a') {
 4435:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4436:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4437:                 }
 4438: 	    }
 4439:             if (lc($tagname) eq 'script') {
 4440:                 my $src;
 4441:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4442:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4443:                 } else {
 4444:                     if ($attr->{'src'} ne '') {
 4445:                         $src = $attr->{'src'};
 4446:                         &add_filetype($allfiles,$src,'src');
 4447:                     }
 4448:                 }
 4449:                 my $text = $p->get_trimmed_text();
 4450:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4451:                     my @swfargs = split(/,/,$1);
 4452:                     foreach my $item (@swfargs) {
 4453:                         $item =~ s/["']//g;
 4454:                         $item =~ s/^\s+//;
 4455:                         $item =~ s/\s+$//;
 4456:                     }
 4457:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4458:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4459:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4460:                         } else {
 4461:                             $related{$swfargs[0]} = [$swfargs[2]];
 4462:                         }
 4463:                     }
 4464:                 }
 4465:             }
 4466:             if (lc($tagname) eq 'link') {
 4467:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4468:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4469:                 }
 4470:             }
 4471: 	    if (lc($tagname) eq 'object' ||
 4472: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4473: 		foreach my $item (keys(%javafiles)) {
 4474: 		    $javafiles{$item} = '';
 4475: 		}
 4476:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4477:                     $lastids{lc($tagname)} = $attr->{'id'};
 4478:                 }
 4479: 	    }
 4480: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4481: 		my $name = lc($attr->{'name'});
 4482: 		foreach my $item (keys(%javafiles)) {
 4483: 		    if ($name eq $item) {
 4484: 			$javafiles{$item} = $attr->{'value'};
 4485: 			last;
 4486: 		    }
 4487: 		}
 4488:                 my $pathfrom;
 4489: 		foreach my $item (keys(%mediafiles)) {
 4490: 		    if ($name eq $item) {
 4491:                         $pathfrom = $attr->{'value'};
 4492:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4493: 			&add_filetype($allfiles,$pathfrom,$name);
 4494: 			last;
 4495: 		    }
 4496: 		}
 4497:                 if ($name eq 'flashvars') {
 4498:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4499:                 }
 4500:                 if ($pathfrom ne '') {
 4501:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4502:                                          $pathfrom);
 4503:                 }
 4504: 	    }
 4505: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4506: 		foreach my $item (keys(%javafiles)) {
 4507: 		    if ($attr->{$item}) {
 4508: 			$javafiles{$item} = $attr->{$item};
 4509: 			last;
 4510: 		    }
 4511: 		}
 4512: 		foreach my $item (keys(%mediafiles)) {
 4513: 		    if ($attr->{$item}) {
 4514: 			&add_filetype($allfiles,$attr->{$item},$item);
 4515: 			last;
 4516: 		    }
 4517: 		}
 4518:                 if (lc($tagname) eq 'embed') {
 4519:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4520:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4521:                                              $attr->{'src'});
 4522:                     }
 4523:                 }
 4524: 	    }
 4525:             if (lc($tagname) eq 'iframe') {
 4526:                 my $src = $attr->{'src'} ;
 4527:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4528:                     &add_filetype($allfiles,$src,'src');
 4529:                 } elsif ($src =~ m{^/}) {
 4530:                     if ($env{'request.course.id'}) {
 4531:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4532:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4533:                         my $url = &hreflocation('',$fullpath);
 4534:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4535:                             my $relpath = $1;
 4536:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4537:                                 &add_filetype($allfiles,$1,'src');
 4538:                             }
 4539:                         }
 4540:                     }
 4541:                 }
 4542:             }
 4543:             if ($t->[4] =~ m{/>$}) {
 4544:                 pop(@state);
 4545:             }
 4546: 	} elsif ($t->[0] eq 'E') {
 4547: 	    my ($tagname) = ($t->[1]);
 4548: 	    if ($javafiles{'codebase'} ne '') {
 4549: 		$javafiles{'codebase'} .= '/';
 4550: 	    }  
 4551: 	    if (lc($tagname) eq 'applet' ||
 4552: 		lc($tagname) eq 'object' ||
 4553: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4554: 		) {
 4555: 		foreach my $item (keys(%javafiles)) {
 4556: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4557: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4558: 			&add_filetype($allfiles,$file,$item);
 4559: 		    }
 4560: 		}
 4561: 	    } 
 4562: 	    pop @state;
 4563: 	}
 4564:     }
 4565:     foreach my $id (sort(keys(%flashvars))) {
 4566:         if ($shockwave{$id} ne '') {
 4567:             my @pairs = split(/\&/,$flashvars{$id});
 4568:             foreach my $pair (@pairs) {
 4569:                 my ($key,$value) = split(/\=/,$pair);
 4570:                 if ($key eq 'thumb') {
 4571:                     &add_filetype($allfiles,$value,$key);
 4572:                 } elsif ($key eq 'content') {
 4573:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4574:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4575:                     if ($ext ne '') {
 4576:                         &add_filetype($allfiles,$path.$value,$ext);
 4577:                     }
 4578:                 }
 4579:             }
 4580:         }
 4581:     }
 4582:     return 'ok';
 4583: }
 4584: 
 4585: sub add_filetype {
 4586:     my ($allfiles,$file,$type)=@_;
 4587:     if (exists($allfiles->{$file})) {
 4588: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4589: 	    push(@{$allfiles->{$file}}, &escape($type));
 4590: 	}
 4591:     } else {
 4592: 	@{$allfiles->{$file}} = (&escape($type));
 4593:     }
 4594: }
 4595: 
 4596: sub embedded_dependency {
 4597:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4598:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4599:         if (($identifier ne '') &&
 4600:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4601:             ($pathfrom ne '')) {
 4602:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4603:             foreach my $dep (@{$related->{$identifier}}) {
 4604:                 &add_filetype($allfiles,$path.$dep,'object');
 4605:             }
 4606:         }
 4607:     }
 4608:     return;
 4609: }
 4610: 
 4611: sub bubblesheet_converter {
 4612:     my ($cdom,$fullpath,$config,$format) = @_;
 4613:     if ((&domain($cdom) ne '') &&
 4614:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4615:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4616:         my (%csvcols,%csvoptions);
 4617:         if (ref($config->{'fields'}) eq 'HASH') {  
 4618:             %csvcols = %{$config->{'fields'}};
 4619:         }
 4620:         if (ref($config->{'options'}) eq 'HASH') {
 4621:             %csvoptions = %{$config->{'options'}};
 4622:         }
 4623:         my %csvbynum = reverse(%csvcols);
 4624:         my %scantronconf = &get_scantron_config($format,$cdom);
 4625:         if (keys(%scantronconf)) {
 4626:             my %bynum = (
 4627:                           $scantronconf{CODEstart} => 'CODEstart',
 4628:                           $scantronconf{IDstart}   => 'IDstart',
 4629:                           $scantronconf{PaperID}   => 'PaperID',
 4630:                           $scantronconf{FirstName} => 'FirstName',
 4631:                           $scantronconf{LastName}  => 'LastName',
 4632:                           $scantronconf{Qstart}    => 'Qstart',
 4633:                         );
 4634:             my @ordered;
 4635:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4636:                 push(@ordered,$bynum{$item});
 4637:             }
 4638:             my %mapstart = (
 4639:                               CODEstart => 'CODE',
 4640:                               IDstart   => 'ID',
 4641:                               PaperID   => 'PaperID',
 4642:                               FirstName => 'FirstName',
 4643:                               LastName  => 'LastName',
 4644:                               Qstart    => 'FirstQuestion',
 4645:                            );
 4646:             my %maplength = (
 4647:                               CODEstart => 'CODElength',
 4648:                               IDstart   => 'IDlength',
 4649:                               PaperID   => 'PaperIDlength',
 4650:                               FirstName => 'FirstNamelength',
 4651:                               LastName  => 'LastNamelength',
 4652:             );
 4653:             if (open(my $fh,'<',$fullpath)) {
 4654:                 my $output;
 4655:                 my %lettdig = &letter_to_digits();
 4656:                 my %diglett = reverse(%lettdig);
 4657:                 my $numletts = scalar(keys(%lettdig));
 4658:                 my $num = 0;
 4659:                 while (my $line=<$fh>) {
 4660:                     $num ++;
 4661:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4662:                     $line =~ s{[\r\n]+$}{};
 4663:                     my %found;
 4664:                     my @values = split(/,/,$line);
 4665:                     my ($qstart,$record);
 4666:                     for (my $i=0; $i<@values; $i++) {
 4667:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4668:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4669:                             if ($values[$i] eq '') {
 4670:                                 $values[$i] = $scantronconf{'Qoff'};
 4671:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4672:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4673:                                     $values[$i] = $lettdig{uc($values[$i])};
 4674:                                 }
 4675:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4676:                                 if ($values[$i] =~ /^[0-9]$/) {
 4677:                                     $values[$i] = $diglett{$values[$i]};
 4678:                                 }
 4679:                             } else {
 4680:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4681:                                     my $digit;
 4682:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4683:                                         $digit = $lettdig{uc($values[$i])}-1;
 4684:                                         if ($values[$i] eq 'J') {
 4685:                                             $digit += $numletts;
 4686:                                         }
 4687:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4688:                                         $digit = $values[$i]-1;
 4689:                                         if ($values[$i] eq '0') {
 4690:                                             $digit += $numletts;
 4691:                                         }
 4692:                                     }
 4693:                                     my $qval='';
 4694:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4695:                                         if ($j == $digit) {
 4696:                                             $qval .= $scantronconf{'Qon'};
 4697:                                         } else {
 4698:                                             $qval .= $scantronconf{'Qoff'};
 4699:                                         }
 4700:                                     }
 4701:                                     $values[$i] = $qval;
 4702:                                 }
 4703:                             }
 4704:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4705:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4706:                             }
 4707:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4708:                             if ($numblank > 0) {
 4709:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4710:                             }
 4711:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4712:                                 $qstart = $i;
 4713:                                 $found{$csvbynum{$i}} = $values[$i];
 4714:                             } else {
 4715:                                 $found{'FirstQuestion'} .= $values[$i];
 4716:                             }
 4717:                         } elsif (exists($csvbynum{$i})) {
 4718:                             if ($csvoptions{'rem'}) {
 4719:                                 $values[$i] =~ s/^\s+//;
 4720:                             }
 4721:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4722:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4723:                                     $values[$i] = '0'.$values[$i];
 4724:                                 }
 4725:                             }
 4726:                             $found{$csvbynum{$i}} = $values[$i];
 4727:                         }
 4728:                     }
 4729:                     foreach my $item (@ordered) {
 4730:                         my $currlength = 1+length($record);
 4731:                         my $numspaces = $scantronconf{$item} - $currlength;
 4732:                         if ($numspaces > 0) {
 4733:                             $record .= (' ' x $numspaces);
 4734:                         }
 4735:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4736:                             unless ($item eq 'Qstart') {
 4737:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4738:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4739:                                 }
 4740:                             }
 4741:                             $record .= $found{$mapstart{$item}};
 4742:                         }
 4743:                     }
 4744:                     $output .= "$record\n";
 4745:                 }
 4746:                 close($fh);
 4747:                 if ($output) {
 4748:                     if (open(my $fh,'>',$fullpath)) {
 4749:                         print $fh $output;
 4750:                         close($fh);
 4751:                     }
 4752:                 }
 4753:             }
 4754:         }
 4755:         return;
 4756:     }
 4757: }
 4758: 
 4759: sub letter_to_digits {
 4760:     my %lettdig = (
 4761:                     A => 1,
 4762:                     B => 2,
 4763:                     C => 3,
 4764:                     D => 4,
 4765:                     E => 5,
 4766:                     F => 6,
 4767:                     G => 7,
 4768:                     H => 8,
 4769:                     I => 9,
 4770:                     J => 0,
 4771:                   );
 4772:     return %lettdig;
 4773: }
 4774: 
 4775: sub get_scantron_config {
 4776:     my ($which,$cdom) = @_;
 4777:     my @lines = &get_scantronformat_file($cdom);
 4778:     my %config;
 4779:     #FIXME probably should move to XML it has already gotten a bit much now
 4780:     foreach my $line (@lines) {
 4781:         my ($name,$descrip)=split(/:/,$line);
 4782:         if ($name ne $which ) { next; }
 4783:         chomp($line);
 4784:         my @config=split(/:/,$line);
 4785:         $config{'name'}=$config[0];
 4786:         $config{'description'}=$config[1];
 4787:         $config{'CODElocation'}=$config[2];
 4788:         $config{'CODEstart'}=$config[3];
 4789:         $config{'CODElength'}=$config[4];
 4790:         $config{'IDstart'}=$config[5];
 4791:         $config{'IDlength'}=$config[6];
 4792:         $config{'Qstart'}=$config[7];
 4793:         $config{'Qlength'}=$config[8];
 4794:         $config{'Qoff'}=$config[9];
 4795:         $config{'Qon'}=$config[10];
 4796:         $config{'PaperID'}=$config[11];
 4797:         $config{'PaperIDlength'}=$config[12];
 4798:         $config{'FirstName'}=$config[13];
 4799:         $config{'FirstNamelength'}=$config[14];
 4800:         $config{'LastName'}=$config[15];
 4801:         $config{'LastNamelength'}=$config[16];
 4802:         $config{'BubblesPerRow'}=$config[17];
 4803:         last;
 4804:     }
 4805:     return %config;
 4806: }
 4807: 
 4808: sub get_scantronformat_file {
 4809:     my ($cdom) = @_;
 4810:     if ($cdom eq '') {
 4811:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4812:     }
 4813:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4814:     my $gottab = 0;
 4815:     my @lines;
 4816:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4817:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4818:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4819:             if ($formatfile ne '-1') {
 4820:                 @lines = split("\n",$formatfile,-1);
 4821:                 $gottab = 1;
 4822:             }
 4823:         }
 4824:     }
 4825:     if (!$gottab) {
 4826:         my $confname = $cdom.'-domainconfig';
 4827:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4828:         my $formatfile = &getfile($default);
 4829:         if ($formatfile ne '-1') {
 4830:             @lines = split("\n",$formatfile,-1);
 4831:             $gottab = 1;
 4832:         }
 4833:     }
 4834:     if (!$gottab) {
 4835:         my @domains = &current_machine_domains();
 4836:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4837:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4838:                 @lines = <$fh>;
 4839:                 close($fh);
 4840:             }
 4841:         } else {
 4842:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4843:                 @lines = <$fh>;
 4844:                 close($fh);
 4845:             }
 4846:         }
 4847:     }
 4848:     return @lines;
 4849: }
 4850: 
 4851: sub removeuploadedurl {
 4852:     my ($url)=@_;	
 4853:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4854:     return &removeuserfile($uname,$udom,$fname);
 4855: }
 4856: 
 4857: sub removeuserfile {
 4858:     my ($docuname,$docudom,$fname)=@_;
 4859:     my $home=&homeserver($docuname,$docudom);    
 4860:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4861:     if ($result eq 'ok') {	
 4862:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4863:             my $metafile = $fname.'.meta';
 4864:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4865: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4866:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4867:             my $sqlresult = 
 4868:                 &update_portfolio_table($docuname,$docudom,$file,
 4869:                                         'portfolio_metadata',$group,
 4870:                                         'delete');
 4871:         }
 4872:     }
 4873:     return $result;
 4874: }
 4875: 
 4876: sub mkdiruserfile {
 4877:     my ($docuname,$docudom,$dir)=@_;
 4878:     my $home=&homeserver($docuname,$docudom);
 4879:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4880: }
 4881: 
 4882: sub renameuserfile {
 4883:     my ($docuname,$docudom,$old,$new)=@_;
 4884:     my $home=&homeserver($docuname,$docudom);
 4885:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4886:                         &escape("$old").':'.&escape("$new"),$home);
 4887:     if ($result eq 'ok') {
 4888:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4889:             my $oldmeta = $old.'.meta';
 4890:             my $newmeta = $new.'.meta';
 4891:             my $metaresult = 
 4892:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4893: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4894:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4895:             my $sqlresult = 
 4896:                 &update_portfolio_table($docuname,$docudom,$file,
 4897:                                         'portfolio_metadata',$group,
 4898:                                         'delete');
 4899:         }
 4900:     }
 4901:     return $result;
 4902: }
 4903: 
 4904: # ------------------------------------------------------------------------- Log
 4905: 
 4906: sub log {
 4907:     my ($dom,$nam,$hom,$what)=@_;
 4908:     return critical("log:$dom:$nam:$what",$hom);
 4909: }
 4910: 
 4911: # ------------------------------------------------------------------ Course Log
 4912: #
 4913: # This routine flushes several buffers of non-mission-critical nature
 4914: #
 4915: 
 4916: sub flushcourselogs {
 4917:     &logthis('Flushing log buffers');
 4918: #
 4919: # course logs
 4920: # This is a log of all transactions in a course, which can be used
 4921: # for data mining purposes
 4922: #
 4923: # It also collects the courseid database, which lists last transaction
 4924: # times and course titles for all courseids
 4925: #
 4926:     my %courseidbuffer=();
 4927:     foreach my $crsid (keys(%courselogs)) {
 4928:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4929: 		          &escape($courselogs{$crsid}),
 4930: 		          $coursehombuf{$crsid}) eq 'ok') {
 4931: 	    delete $courselogs{$crsid};
 4932:         } else {
 4933:             &logthis('Failed to flush log buffer for '.$crsid);
 4934:             if (length($courselogs{$crsid})>40000) {
 4935:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4936:                         " exceeded maximum size, deleting.</font>");
 4937:                delete $courselogs{$crsid};
 4938:             }
 4939:         }
 4940:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4941:             'description' => $coursedescrbuf{$crsid},
 4942:             'inst_code'    => $courseinstcodebuf{$crsid},
 4943:             'type'        => $coursetypebuf{$crsid},
 4944:             'owner'       => $courseownerbuf{$crsid},
 4945:         };
 4946:     }
 4947: #
 4948: # Write course id database (reverse lookup) to homeserver of courses 
 4949: # Is used in pickcourse
 4950: #
 4951:     foreach my $crs_home (keys(%courseidbuffer)) {
 4952:         my $response = &courseidput(&host_domain($crs_home),
 4953:                                     $courseidbuffer{$crs_home},
 4954:                                     $crs_home,'timeonly');
 4955:     }
 4956: #
 4957: # File accesses
 4958: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4959: #
 4960:     foreach my $entry (keys(%accesshash)) {
 4961:         if ($entry =~ /___count$/) {
 4962:             my ($dom,$name);
 4963:             ($dom,$name,undef)=
 4964: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4965:             if (! defined($dom) || $dom eq '' || 
 4966:                 ! defined($name) || $name eq '') {
 4967:                 my $cid = $env{'request.course.id'};
 4968:                 $dom  = $env{'request.'.$cid.'.domain'};
 4969:                 $name = $env{'request.'.$cid.'.num'};
 4970:             }
 4971:             my $value = $accesshash{$entry};
 4972:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4973:             my %temphash=($url => $value);
 4974:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4975:             if ($result eq 'ok') {
 4976:                 delete $accesshash{$entry};
 4977:             }
 4978:         } else {
 4979:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4980:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4981:             my %temphash=($entry => $accesshash{$entry});
 4982:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4983:                 delete $accesshash{$entry};
 4984:             }
 4985:         }
 4986:     }
 4987: #
 4988: # Roles
 4989: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4990: #
 4991:     foreach my $entry (keys(%userrolehash)) {
 4992:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4993: 	    split(/\:/,$entry);
 4994:         if (&Apache::lonnet::put('nohist_userroles',
 4995:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4996:                 $rudom,$runame) eq 'ok') {
 4997: 	    delete $userrolehash{$entry};
 4998:         }
 4999:     }
 5000: #
 5001: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5002: #
 5003:     my %domrolebuffer = ();
 5004:     foreach my $entry (keys(%domainrolehash)) {
 5005:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5006:         if ($domrolebuffer{$rudom}) {
 5007:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5008:                       '='.&escape($domainrolehash{$entry});
 5009:         } else {
 5010:             $domrolebuffer{$rudom}.=&escape($entry).
 5011:                       '='.&escape($domainrolehash{$entry});
 5012:         }
 5013:         delete $domainrolehash{$entry};
 5014:     }
 5015:     foreach my $dom (keys(%domrolebuffer)) {
 5016: 	my %servers;
 5017: 	if (defined(&domain($dom,'primary'))) {
 5018: 	    my $primary=&domain($dom,'primary');
 5019: 	    my $hostname=&hostname($primary);
 5020: 	    $servers{$primary} = $hostname;
 5021: 	} else { 
 5022: 	    %servers = &get_servers($dom,'library');
 5023: 	}
 5024: 	foreach my $tryserver (keys(%servers)) {
 5025: 	    if (&reply('domroleput:'.$dom.':'.
 5026: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5027: 		last;
 5028: 	    } else {  
 5029: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5030: 	    }
 5031:         }
 5032:     }
 5033:     $dumpcount++;
 5034: }
 5035: 
 5036: sub courselog {
 5037:     my $what=shift;
 5038:     $what=time.':'.$what;
 5039:     unless ($env{'request.course.id'}) { return ''; }
 5040:     $coursedombuf{$env{'request.course.id'}}=
 5041:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5042:     $coursenumbuf{$env{'request.course.id'}}=
 5043:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5044:     $coursehombuf{$env{'request.course.id'}}=
 5045:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5046:     $coursedescrbuf{$env{'request.course.id'}}=
 5047:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5048:     $courseinstcodebuf{$env{'request.course.id'}}=
 5049:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5050:     $courseownerbuf{$env{'request.course.id'}}=
 5051:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5052:     $coursetypebuf{$env{'request.course.id'}}=
 5053:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5054:     if (defined $courselogs{$env{'request.course.id'}}) {
 5055: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5056:     } else {
 5057: 	$courselogs{$env{'request.course.id'}}.=$what;
 5058:     }
 5059:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5060: 	&flushcourselogs();
 5061:     }
 5062: }
 5063: 
 5064: sub courseacclog {
 5065:     my $fnsymb=shift;
 5066:     unless ($env{'request.course.id'}) { return ''; }
 5067:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5068:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5069:         $what.=':POST';
 5070:         # FIXME: Probably ought to escape things....
 5071: 	foreach my $key (keys(%env)) {
 5072:             if ($key=~/^form\.(.*)/) {
 5073:                 my $formitem = $1;
 5074:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5075:                     $what.=':'.$formitem.'='.$env{$key};
 5076:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5077:                     if ($formitem eq 'proctorpassword') {
 5078:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5079:                     } else {
 5080:                         $what.=':'.$formitem.'='.$env{$key};
 5081:                     }
 5082:                 }
 5083:             }
 5084:         }
 5085:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5086:         # FIXME: We should not be depending on a form parameter that someone
 5087:         # editing lonsearchcat.pm might change in the future.
 5088:         if ($env{'form.phase'} eq 'course_search') {
 5089:             $what.= ':POST';
 5090:             # FIXME: Probably ought to escape things....
 5091:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5092:                                  'crsdiscuss') {
 5093:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5094:             }
 5095:         }
 5096:     }
 5097:     &courselog($what);
 5098: }
 5099: 
 5100: sub countacc {
 5101:     my $url=&declutter(shift);
 5102:     return if (! defined($url) || $url eq '');
 5103:     unless ($env{'request.course.id'}) { return ''; }
 5104: #
 5105: # Mark that this url was used in this course
 5106: #
 5107:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5108: #
 5109: # Increase the access count for this resource in this child process
 5110: #
 5111:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5112:     $accesshash{$key}++;
 5113: }
 5114: 
 5115: sub linklog {
 5116:     my ($from,$to)=@_;
 5117:     $from=&declutter($from);
 5118:     $to=&declutter($to);
 5119:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5120:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5121: }
 5122: 
 5123: sub statslog {
 5124:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5125:     if ($users<2) { return; }
 5126:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5127:             'course'       => $env{'request.course.id'},
 5128:             'sections'     => '"all"',
 5129:             'num_students' => $users,
 5130:             'part'         => $part,
 5131:             'symb'         => $symb,
 5132:             'mean_tries'   => $av_attempts,
 5133:             'deg_of_diff'  => $degdiff});
 5134:     foreach my $key (keys(%dynstore)) {
 5135:         $accesshash{$key}=$dynstore{$key};
 5136:     }
 5137: }
 5138:   
 5139: sub userrolelog {
 5140:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5141:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5142:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5143:        $userrolehash
 5144:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5145:                     =$tend.':'.$tstart;
 5146:     }
 5147:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5148:        $userrolehash
 5149:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5150:                     =$tend.':'.$tstart;
 5151:     }
 5152:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5153:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5154:        $domainrolehash
 5155:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5156:                     = $tend.':'.$tstart;
 5157:     }
 5158: }
 5159: 
 5160: sub courserolelog {
 5161:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 5162:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5163:         my $cdom = $1;
 5164:         my $cnum = $2;
 5165:         my $sec = $3;
 5166:         my $namespace = 'rolelog';
 5167:         my %storehash = (
 5168:                            role    => $trole,
 5169:                            start   => $tstart,
 5170:                            end     => $tend,
 5171:                            selfenroll => $selfenroll,
 5172:                            context    => $context,
 5173:                         );
 5174:         if ($trole eq 'gr') {
 5175:             $namespace = 'groupslog';
 5176:             $storehash{'group'} = $sec;
 5177:         } else {
 5178:             $storehash{'section'} = $sec;
 5179:         }
 5180:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5181:                    $domain,$cnum,$cdom);
 5182:         if (($trole ne 'st') || ($sec ne '')) {
 5183:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5184:         }
 5185:     }
 5186:     return;
 5187: }
 5188: 
 5189: sub domainrolelog {
 5190:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5191:     if ($area =~ m{^/($match_domain)/$}) {
 5192:         my $cdom = $1;
 5193:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 5194:         my $namespace = 'rolelog';
 5195:         my %storehash = (
 5196:                            role    => $trole,
 5197:                            start   => $tstart,
 5198:                            end     => $tend,
 5199:                            context => $context,
 5200:                         );
 5201:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5202:                    $domain,$domconfiguser,$cdom);
 5203:     }
 5204:     return;
 5205: 
 5206: }
 5207: 
 5208: sub coauthorrolelog {
 5209:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 5210:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5211:         my $audom = $1;
 5212:         my $auname = $2;
 5213:         my $namespace = 'rolelog';
 5214:         my %storehash = (
 5215:                            role    => $trole,
 5216:                            start   => $tstart,
 5217:                            end     => $tend,
 5218:                            context => $context,
 5219:                         );
 5220:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5221:                    $domain,$auname,$audom);
 5222:     }
 5223:     return;
 5224: }
 5225: 
 5226: sub get_course_adv_roles {
 5227:     my ($cid,$codes) = @_;
 5228:     $cid=$env{'request.course.id'} unless (defined($cid));
 5229:     my %coursehash=&coursedescription($cid);
 5230:     my $crstype = &Apache::loncommon::course_type($cid);
 5231:     my %nothide=();
 5232:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5233:         if ($user !~ /:/) {
 5234: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5235:         } else {
 5236:             $nothide{$user}=1;
 5237:         }
 5238:     }
 5239:     my @possdoms = ($coursehash{'domain'});
 5240:     if ($coursehash{'checkforpriv'}) {
 5241:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5242:     }
 5243:     my %returnhash=();
 5244:     my %dumphash=
 5245:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5246:     my $now=time;
 5247:     my %privileged;
 5248:     foreach my $entry (keys(%dumphash)) {
 5249: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5250:         if (($tstart) && ($tstart<0)) { next; }
 5251:         if (($tend) && ($tend<$now)) { next; }
 5252:         if (($tstart) && ($now<$tstart)) { next; }
 5253:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5254: 	if ($username eq '' || $domain eq '') { next; }
 5255:         if ((&privileged($username,$domain,\@possdoms)) &&
 5256:             (!$nothide{$username.':'.$domain})) { next; }
 5257: 	if ($role eq 'cr') { next; }
 5258:         if ($codes) {
 5259:             if ($section) { $role .= ':'.$section; }
 5260:             if ($returnhash{$role}) {
 5261:                 $returnhash{$role}.=','.$username.':'.$domain;
 5262:             } else {
 5263:                 $returnhash{$role}=$username.':'.$domain;
 5264:             }
 5265:         } else {
 5266:             my $key=&plaintext($role,$crstype);
 5267:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5268:             if ($returnhash{$key}) {
 5269: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5270:             } else {
 5271:                 $returnhash{$key}=$username.':'.$domain;
 5272:             }
 5273:         }
 5274:     }
 5275:     return %returnhash;
 5276: }
 5277: 
 5278: sub get_my_roles {
 5279:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5280:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5281:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5282:     my (%dumphash,%nothide);
 5283:     if ($context eq 'userroles') {
 5284:         %dumphash = &dump('roles',$udom,$uname);
 5285:     } else {
 5286:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5287:         if ($hidepriv) {
 5288:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5289:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5290:                 if ($user !~ /:/) {
 5291:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5292:                 } else {
 5293:                     $nothide{$user} = 1;
 5294:                 }
 5295:             }
 5296:         }
 5297:     }
 5298:     my %returnhash=();
 5299:     my $now=time;
 5300:     my %privileged;
 5301:     foreach my $entry (keys(%dumphash)) {
 5302:         my ($role,$tend,$tstart);
 5303:         if ($context eq 'userroles') {
 5304:             next if ($entry =~ /^rolesdef/);
 5305: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5306:         } else {
 5307:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5308:         }
 5309:         if (($tstart) && ($tstart<0)) { next; }
 5310:         my $status = 'active';
 5311:         if (($tend) && ($tend<=$now)) {
 5312:             $status = 'previous';
 5313:         } 
 5314:         if (($tstart) && ($now<$tstart)) {
 5315:             $status = 'future';
 5316:         }
 5317:         if (ref($types) eq 'ARRAY') {
 5318:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5319:                 next;
 5320:             } 
 5321:         } else {
 5322:             if ($status ne 'active') {
 5323:                 next;
 5324:             }
 5325:         }
 5326:         my ($rolecode,$username,$domain,$section,$area);
 5327:         if ($context eq 'userroles') {
 5328:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5329:             (undef,$domain,$username,$section) = split(/\//,$area);
 5330:         } else {
 5331:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5332:         }
 5333:         if (ref($roledoms) eq 'ARRAY') {
 5334:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5335:                 next;
 5336:             }
 5337:         }
 5338:         if (ref($roles) eq 'ARRAY') {
 5339:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5340:                 if ($role =~ /^cr\//) {
 5341:                     if (!grep(/^cr$/,@{$roles})) {
 5342:                         next;
 5343:                     }
 5344:                 } elsif ($role =~ /^gr\//) {
 5345:                     if (!grep(/^gr$/,@{$roles})) {
 5346:                         next;
 5347:                     }
 5348:                 } else {
 5349:                     next;
 5350:                 }
 5351:             }
 5352:         }
 5353:         if ($hidepriv) {
 5354:             my @privroles = ('dc','su');
 5355:             if ($context eq 'userroles') {
 5356:                 next if (grep(/^\Q$role\E$/,@privroles));
 5357:             } else {
 5358:                 my $possdoms = [$domain];
 5359:                 if (ref($roledoms) eq 'ARRAY') {
 5360:                    push(@{$possdoms},@{$roledoms}); 
 5361:                 }
 5362:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5363:                     if (!$nothide{$username.':'.$domain}) {
 5364:                         next;
 5365:                     }
 5366:                 }
 5367:             }
 5368:         }
 5369:         if ($withsec) {
 5370:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5371:                 $tstart.':'.$tend;
 5372:         } else {
 5373:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5374:         }
 5375:     }
 5376:     return %returnhash;
 5377: }
 5378: 
 5379: sub get_all_adhocroles {
 5380:     my ($dom) = @_;
 5381:     my @roles_by_num = ();
 5382:     my %domdefaults = &get_domain_defaults($dom);
 5383:     my (%description,%access_in_dom,%access_info);
 5384:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5385:         my $count = 0;
 5386:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5387:         my %ordered;
 5388:         foreach my $role (sort(keys(%domcurrent))) {
 5389:             my ($order,$desc,$access_in_dom);
 5390:             if (ref($domcurrent{$role}) eq 'HASH') {
 5391:                 $order = $domcurrent{$role}{'order'};
 5392:                 $desc = $domcurrent{$role}{'desc'};
 5393:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5394:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5395:             }
 5396:             if ($order eq '') {
 5397:                 $order = $count;
 5398:             }
 5399:             $ordered{$order} = $role;
 5400:             if ($desc ne '') {
 5401:                 $description{$role} = $desc;
 5402:             } else {
 5403:                 $description{$role}= $role;
 5404:             }
 5405:             $count++;
 5406:         }
 5407:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5408:             push(@roles_by_num,$ordered{$item});
 5409:         }
 5410:     }
 5411:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5412: }
 5413: 
 5414: sub get_my_adhocroles {
 5415:     my ($cid,$checkreg) = @_;
 5416:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5417:     if ($env{'request.course.id'} eq $cid) {
 5418:         $cdom = $env{'course.'.$cid.'.domain'};
 5419:         $cnum = $env{'course.'.$cid.'.num'};
 5420:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5421:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5422:         $cdom = $1;
 5423:         $cnum = $2;
 5424:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5425:                                      $cdom,$cnum);
 5426:     }
 5427:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5428:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5429:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5430:         if ($rosterhash{$user} ne '') {
 5431:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5432:             return ([],{}) if ($type eq 'auto');
 5433:         }
 5434:     }
 5435:     if (($cdom ne '') && ($cnum ne ''))  {
 5436:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5437:             my $then=$env{'user.login.time'};
 5438:             my $update=$env{'user.update.time'};
 5439:             if (!$update) {
 5440:                 $update = $then;
 5441:             }
 5442:             my @liveroles;
 5443:             foreach my $role ('dh','da') {
 5444:                 if ($env{"user.role.$role./$cdom/"}) {
 5445:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5446:                     my $limit = $update;
 5447:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5448:                         $limit = $then;
 5449:                     }
 5450:                     my $activerole = 1;
 5451:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5452:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5453:                     if ($activerole) {
 5454:                         push(@liveroles,$role);
 5455:                     }
 5456:                 }
 5457:             }
 5458:             if (@liveroles) {
 5459:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5460:                     my ($accessref,$accessinfo,%access_in_dom);
 5461:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5462:                     if (ref($roles_by_num) eq 'ARRAY') {
 5463:                         if (@{$roles_by_num}) {
 5464:                             my %settings;
 5465:                             if ($env{'request.course.id'} eq $cid) {
 5466:                                 foreach my $envkey (keys(%env)) {
 5467:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5468:                                         $settings{$1} = $env{$envkey};
 5469:                                     }
 5470:                                 }
 5471:                             } else {
 5472:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5473:                             }
 5474:                             my %setincrs;
 5475:                             if ($settings{'internal.adhocaccess'}) {
 5476:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5477:                             }
 5478:                             my @statuses;
 5479:                             if ($env{'environment.inststatus'}) {
 5480:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5481:                             }
 5482:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5483:                             if (ref($accessref) eq 'HASH') {
 5484:                                 %access_in_dom = %{$accessref};
 5485:                             }
 5486:                             foreach my $role (@{$roles_by_num}) {
 5487:                                 my ($curraccess,@okstatus,@personnel);
 5488:                                 if ($setincrs{$role}) {
 5489:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5490:                                     if ($curraccess eq 'status') {
 5491:                                         @okstatus = split(/\&/,$rest);
 5492:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5493:                                         @personnel = split(/\&/,$rest);
 5494:                                     }
 5495:                                 } else {
 5496:                                     $curraccess = $access_in_dom{$role};
 5497:                                     if (ref($accessinfo) eq 'HASH') {
 5498:                                         if ($curraccess eq 'status') {
 5499:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5500:                                                 @okstatus = @{$accessinfo->{$role}};
 5501:                                             }
 5502:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5503:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5504:                                                 @personnel = @{$accessinfo->{$role}};
 5505:                                             }
 5506:                                         }
 5507:                                     }
 5508:                                 }
 5509:                                 if ($curraccess eq 'none') {
 5510:                                     next;
 5511:                                 } elsif ($curraccess eq 'all') {
 5512:                                     push(@possroles,$role);
 5513:                                 } elsif ($curraccess eq 'dh') {
 5514:                                     if (grep(/^dh$/,@liveroles)) {
 5515:                                         push(@possroles,$role);
 5516:                                     } else {
 5517:                                         next;
 5518:                                     }
 5519:                                 } elsif ($curraccess eq 'da') {
 5520:                                     if (grep(/^da$/,@liveroles)) {
 5521:                                         push(@possroles,$role);
 5522:                                     } else {
 5523:                                         next;
 5524:                                     }
 5525:                                 } elsif ($curraccess eq 'status') {
 5526:                                     if (@okstatus) {
 5527:                                         if (!@statuses) {
 5528:                                             if (grep(/^default$/,@okstatus)) {
 5529:                                                 push(@possroles,$role);
 5530:                                             }
 5531:                                         } else {
 5532:                                             foreach my $status (@okstatus) {
 5533:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5534:                                                     push(@possroles,$role);
 5535:                                                     last;
 5536:                                                 }
 5537:                                             }
 5538:                                         }
 5539:                                     }
 5540:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5541:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5542:                                         if ($curraccess eq 'exc') {
 5543:                                             push(@possroles,$role);
 5544:                                         }
 5545:                                     } elsif ($curraccess eq 'inc') {
 5546:                                         push(@possroles,$role);
 5547:                                     }
 5548:                                 }
 5549:                             }
 5550:                         }
 5551:                     }
 5552:                 }
 5553:             }
 5554:         }
 5555:     }
 5556:     unless (ref($description) eq 'HASH') {
 5557:         if (ref($roles_by_num) eq 'ARRAY') {
 5558:             my %desc;
 5559:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5560:             $description = \%desc;
 5561:         } else {
 5562:             $description = {};
 5563:         }
 5564:     }
 5565:     return (\@possroles,$description);
 5566: }
 5567: 
 5568: # ----------------------------------------------------- Frontpage Announcements
 5569: #
 5570: #
 5571: 
 5572: sub postannounce {
 5573:     my ($server,$text)=@_;
 5574:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5575:     unless ($text=~/\w/) { $text=''; }
 5576:     return &reply('setannounce:'.&escape($text),$server);
 5577: }
 5578: 
 5579: sub getannounce {
 5580: 
 5581:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5582: 	my $announcement='';
 5583: 	while (my $line = <$fh>) { $announcement .= $line; }
 5584: 	close($fh);
 5585: 	if ($announcement=~/\w/) { 
 5586: 	    return 
 5587:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5588:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5589: 	} else {
 5590: 	    return '';
 5591: 	}
 5592:     } else {
 5593: 	return '';
 5594:     }
 5595: }
 5596: 
 5597: # ---------------------------------------------------------- Course ID routines
 5598: # Deal with domain's nohist_courseid.db files
 5599: #
 5600: 
 5601: sub courseidput {
 5602:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5603:     return unless (ref($storehash) eq 'HASH');
 5604:     my $outcome;
 5605:     if ($caller eq 'timeonly') {
 5606:         my $cids = '';
 5607:         foreach my $item (keys(%$storehash)) {
 5608:             $cids.=&escape($item).'&';
 5609:         }
 5610:         $cids=~s/\&$//;
 5611:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5612:                           $coursehome);       
 5613:     } else {
 5614:         my $items = '';
 5615:         foreach my $item (keys(%$storehash)) {
 5616:             $items.= &escape($item).'='.
 5617:                      &freeze_escape($$storehash{$item}).'&';
 5618:         }
 5619:         $items=~s/\&$//;
 5620:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5621:                           $coursehome);
 5622:     }
 5623:     if ($outcome eq 'unknown_cmd') {
 5624:         my $what;
 5625:         foreach my $cid (keys(%$storehash)) {
 5626:             $what .= &escape($cid).'=';
 5627:             foreach my $item ('description','inst_code','owner','type') {
 5628:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5629:             }
 5630:             $what =~ s/\:$/&/;
 5631:         }
 5632:         $what =~ s/\&$//;  
 5633:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5634:     } else {
 5635:         return $outcome;
 5636:     }
 5637: }
 5638: 
 5639: sub courseiddump {
 5640:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5641:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5642:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5643:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5644:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5645:     my $as_hash = 1;
 5646:     my %returnhash;
 5647:     if (!$domfilter) { $domfilter=''; }
 5648:     my %libserv = &all_library();
 5649:     foreach my $tryserver (keys(%libserv)) {
 5650:         if ( (  $hostidflag == 1 
 5651: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5652: 	     || (!defined($hostidflag)) ) {
 5653: 
 5654: 	    if (($domfilter eq '') ||
 5655: 		(&host_domain($tryserver) eq $domfilter)) {
 5656:                 my $rep;
 5657:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5658:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5659:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5660:                                 &escape($descfilter), &escape($instcodefilter), 
 5661:                                 &escape($ownerfilter), &escape($coursefilter),
 5662:                                 &escape($typefilter), &escape($regexp_ok), 
 5663:                                 $as_hash, &escape($selfenrollonly), 
 5664:                                 &escape($catfilter), $showhidden, $caller, 
 5665:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5666:                                 &escape($createdbefore), &escape($createdafter), 
 5667:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5668:                                 $reqcrsdom,&escape($reqinstcode))));
 5669:                 } else {
 5670:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5671:                              $sincefilter.':'.&escape($descfilter).':'.
 5672:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5673:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5674:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5675:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5676:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5677:                              &escape($cc_clone).':'.$cloneonly.':'.
 5678:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5679:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5680:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5681:                 }
 5682:                      
 5683:                 my @pairs=split(/\&/,$rep);
 5684:                 foreach my $item (@pairs) {
 5685:                     my ($key,$value)=split(/\=/,$item,2);
 5686:                     $key = &unescape($key);
 5687:                     next if ($key =~ /^error: 2 /);
 5688:                     my $result = &thaw_unescape($value);
 5689:                     if (ref($result) eq 'HASH') {
 5690:                         $returnhash{$key}=$result;
 5691:                     } else {
 5692:                         my @responses = split(/:/,$value);
 5693:                         my @items = ('description','inst_code','owner','type');
 5694:                         for (my $i=0; $i<@responses; $i++) {
 5695:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5696:                         }
 5697:                     }
 5698:                 }
 5699:             }
 5700:         }
 5701:     }
 5702:     return %returnhash;
 5703: }
 5704: 
 5705: sub courselastaccess {
 5706:     my ($cdom,$cnum,$hostidref) = @_;
 5707:     my %returnhash;
 5708:     if ($cdom && $cnum) {
 5709:         my $chome = &homeserver($cnum,$cdom);
 5710:         if ($chome ne 'no_host') {
 5711:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5712:             &extract_lastaccess(\%returnhash,$rep);
 5713:         }
 5714:     } else {
 5715:         if (!$cdom) { $cdom=''; }
 5716:         my %libserv = &all_library();
 5717:         foreach my $tryserver (keys(%libserv)) {
 5718:             if (ref($hostidref) eq 'ARRAY') {
 5719:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5720:             } 
 5721:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5722:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5723:                 &extract_lastaccess(\%returnhash,$rep);
 5724:             }
 5725:         }
 5726:     }
 5727:     return %returnhash;
 5728: }
 5729: 
 5730: sub extract_lastaccess {
 5731:     my ($returnhash,$rep) = @_;
 5732:     if (ref($returnhash) eq 'HASH') {
 5733:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5734:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5735:                  $rep eq '') {
 5736:             my @pairs=split(/\&/,$rep);
 5737:             foreach my $item (@pairs) {
 5738:                 my ($key,$value)=split(/\=/,$item,2);
 5739:                 $key = &unescape($key);
 5740:                 next if ($key =~ /^error: 2 /);
 5741:                 $returnhash->{$key} = &thaw_unescape($value);
 5742:             }
 5743:         }
 5744:     }
 5745:     return;
 5746: }
 5747: 
 5748: # ---------------------------------------------------------- DC e-mail
 5749: 
 5750: sub dcmailput {
 5751:     my ($domain,$msgid,$message,$server)=@_;
 5752:     my $status = &Apache::lonnet::critical(
 5753:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5754:        &escape($message),$server);
 5755:     return $status;
 5756: }
 5757: 
 5758: sub dcmaildump {
 5759:     my ($dom,$startdate,$enddate,$senders) = @_;
 5760:     my %returnhash=();
 5761: 
 5762:     if (defined(&domain($dom,'primary'))) {
 5763:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5764:                                                          &escape($enddate).':';
 5765: 	my @esc_senders=map { &escape($_)} @$senders;
 5766: 	$cmd.=&escape(join('&',@esc_senders));
 5767: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5768:             my ($key,$value) = split(/\=/,$line,2);
 5769:             if (($key) && ($value)) {
 5770:                 $returnhash{&unescape($key)} = &unescape($value);
 5771:             }
 5772:         }
 5773:     }
 5774:     return %returnhash;
 5775: }
 5776: # ---------------------------------------------------------- Domain roles
 5777: 
 5778: sub get_domain_roles {
 5779:     my ($dom,$roles,$startdate,$enddate)=@_;
 5780:     if ((!defined($startdate)) || ($startdate eq '')) {
 5781:         $startdate = '.';
 5782:     }
 5783:     if ((!defined($enddate)) || ($enddate eq '')) {
 5784:         $enddate = '.';
 5785:     }
 5786:     my $rolelist;
 5787:     if (ref($roles) eq 'ARRAY') {
 5788:         $rolelist = join('&',@{$roles});
 5789:     }
 5790:     my %personnel = ();
 5791: 
 5792:     my %servers = &get_servers($dom,'library');
 5793:     foreach my $tryserver (keys(%servers)) {
 5794: 	%{$personnel{$tryserver}}=();
 5795: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5796: 					    &escape($startdate).':'.
 5797: 					    &escape($enddate).':'.
 5798: 					    &escape($rolelist), $tryserver))) {
 5799: 	    my ($key,$value) = split(/\=/,$line,2);
 5800: 	    if (($key) && ($value)) {
 5801: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5802: 	    }
 5803: 	}
 5804:     }
 5805:     return %personnel;
 5806: }
 5807: 
 5808: sub get_active_domroles {
 5809:     my ($dom,$roles) = @_;
 5810:     return () unless (ref($roles) eq 'ARRAY');
 5811:     my $now = time;
 5812:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5813:     my %domroles;
 5814:     foreach my $server (keys(%dompersonnel)) {
 5815:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5816:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5817:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5818:         }
 5819:     }
 5820:     return %domroles;
 5821: }
 5822: 
 5823: # ----------------------------------------------------------- Interval timing 
 5824: 
 5825: {
 5826: # Caches needed for speedup of navmaps
 5827: # We don't want to cache this for very long at all (5 seconds at most)
 5828: # 
 5829: # The user for whom we cache
 5830: my $cachedkey='';
 5831: # The cached times for this user
 5832: my %cachedtimes=();
 5833: # When this was last done
 5834: my $cachedtime='';
 5835: 
 5836: sub load_all_first_access {
 5837:     my ($uname,$udom,$ignorecache)=@_;
 5838:     if (($cachedkey eq $uname.':'.$udom) &&
 5839:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5840:         (!$ignorecache)) {
 5841:         return;
 5842:     }
 5843:     $cachedtime=time;
 5844:     $cachedkey=$uname.':'.$udom;
 5845:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5846: }
 5847: 
 5848: sub get_first_access {
 5849:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5850:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5851:     if ($argsymb) { $symb=$argsymb; }
 5852:     my ($map,$id,$res)=&decode_symb($symb);
 5853:     if ($argmap) { $map = $argmap; }
 5854:     if ($type eq 'course') {
 5855: 	$res='course';
 5856:     } elsif ($type eq 'map') {
 5857: 	$res=&symbread($map);
 5858:     } else {
 5859: 	$res=$symb;
 5860:     }
 5861:     &load_all_first_access($uname,$udom,$ignorecache);
 5862:     return $cachedtimes{"$courseid\0$res"};
 5863: }
 5864: 
 5865: sub set_first_access {
 5866:     my ($type,$interval)=@_;
 5867:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5868:     my ($map,$id,$res)=&decode_symb($symb);
 5869:     if ($type eq 'course') {
 5870: 	$res='course';
 5871:     } elsif ($type eq 'map') {
 5872: 	$res=&symbread($map);
 5873:     } else {
 5874: 	$res=$symb;
 5875:     }
 5876:     $cachedkey='';
 5877:     my $firstaccess=&get_first_access($type,$symb,$map);
 5878:     if ($firstaccess) {
 5879:         &logthis("First access time already set ($firstaccess) when attempting ".
 5880:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5881:                  "in $courseid");
 5882:         return 'already_set';
 5883:     } else {
 5884:         my $start = time;
 5885: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5886:                           $udom,$uname);
 5887:         if ($putres eq 'ok') {
 5888:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5889:                  $udom,$uname); 
 5890:             &appenv(
 5891:                      {
 5892:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5893:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5894:                      }
 5895:                   );
 5896:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5897:                 $cachedtimes{"$courseid\0$res"} = $start;
 5898:             }
 5899:         } elsif ($putres ne 'refused') {
 5900:             &logthis("Result: $putres when attempting to set first access time ".
 5901:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5902:         }
 5903:         return $putres;
 5904:     }
 5905:     return 'already_set';
 5906: }
 5907: }
 5908: 
 5909: # --------------------------------------------- Set Expire Date for Spreadsheet
 5910: 
 5911: sub expirespread {
 5912:     my ($uname,$udom,$stype,$usymb)=@_;
 5913:     my $cid=$env{'request.course.id'}; 
 5914:     if ($cid) {
 5915:        my $now=time;
 5916:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5917:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5918:                             $env{'course.'.$cid.'.num'}.
 5919: 	        	    ':nohist_expirationdates:'.
 5920:                             &escape($key).'='.$now,
 5921:                             $env{'course.'.$cid.'.home'})
 5922:     }
 5923:     return 'ok';
 5924: }
 5925: 
 5926: # ----------------------------------------------------- Devalidate Spreadsheets
 5927: 
 5928: sub devalidate {
 5929:     my ($symb,$uname,$udom)=@_;
 5930:     my $cid=$env{'request.course.id'}; 
 5931:     if ($cid) {
 5932:         # delete the stored spreadsheets for
 5933:         # - the student level sheet of this user in course's homespace
 5934:         # - the assessment level sheet for this resource 
 5935:         #   for this user in user's homespace
 5936: 	# - current conditional state info
 5937: 	my $key=$uname.':'.$udom.':';
 5938:         my $status=
 5939: 	    &del('nohist_calculatedsheets',
 5940: 		 [$key.'studentcalc:'],
 5941: 		 $env{'course.'.$cid.'.domain'},
 5942: 		 $env{'course.'.$cid.'.num'})
 5943: 		.' '.
 5944: 	    &del('nohist_calculatedsheets_'.$cid,
 5945: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5946:         unless ($status eq 'ok ok') {
 5947:            &logthis('Could not devalidate spreadsheet '.
 5948:                     $uname.' at '.$udom.' for '.
 5949: 		    $symb.': '.$status);
 5950:         }
 5951: 	&delenv('user.state.'.$cid);
 5952:     }
 5953: }
 5954: 
 5955: sub get_scalar {
 5956:     my ($string,$end) = @_;
 5957:     my $value;
 5958:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5959: 	$value = $1;
 5960:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5961: 	$value = $1;
 5962:     }
 5963:     return &unescape($value);
 5964: }
 5965: 
 5966: sub array2str {
 5967:   my (@array) = @_;
 5968:   my $result=&arrayref2str(\@array);
 5969:   $result=~s/^__ARRAY_REF__//;
 5970:   $result=~s/__END_ARRAY_REF__$//;
 5971:   return $result;
 5972: }
 5973: 
 5974: sub arrayref2str {
 5975:   my ($arrayref) = @_;
 5976:   my $result='__ARRAY_REF__';
 5977:   foreach my $elem (@$arrayref) {
 5978:     if(ref($elem) eq 'ARRAY') {
 5979:       $result.=&arrayref2str($elem).'&';
 5980:     } elsif(ref($elem) eq 'HASH') {
 5981:       $result.=&hashref2str($elem).'&';
 5982:     } elsif(ref($elem)) {
 5983:       #print("Got a ref of ".(ref($elem))." skipping.");
 5984:     } else {
 5985:       $result.=&escape($elem).'&';
 5986:     }
 5987:   }
 5988:   $result=~s/\&$//;
 5989:   $result .= '__END_ARRAY_REF__';
 5990:   return $result;
 5991: }
 5992: 
 5993: sub hash2str {
 5994:   my (%hash) = @_;
 5995:   my $result=&hashref2str(\%hash);
 5996:   $result=~s/^__HASH_REF__//;
 5997:   $result=~s/__END_HASH_REF__$//;
 5998:   return $result;
 5999: }
 6000: 
 6001: sub hashref2str {
 6002:   my ($hashref)=@_;
 6003:   my $result='__HASH_REF__';
 6004:   foreach my $key (sort(keys(%$hashref))) {
 6005:     if (ref($key) eq 'ARRAY') {
 6006:       $result.=&arrayref2str($key).'=';
 6007:     } elsif (ref($key) eq 'HASH') {
 6008:       $result.=&hashref2str($key).'=';
 6009:     } elsif (ref($key)) {
 6010:       $result.='=';
 6011:       #print("Got a ref of ".(ref($key))." skipping.");
 6012:     } else {
 6013: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6014:     }
 6015: 
 6016:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6017:       $result.=&arrayref2str($hashref->{$key}).'&';
 6018:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6019:       $result.=&hashref2str($hashref->{$key}).'&';
 6020:     } elsif(ref($hashref->{$key})) {
 6021:        $result.='&';
 6022:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6023:     } else {
 6024:       $result.=&escape($hashref->{$key}).'&';
 6025:     }
 6026:   }
 6027:   $result=~s/\&$//;
 6028:   $result .= '__END_HASH_REF__';
 6029:   return $result;
 6030: }
 6031: 
 6032: sub str2hash {
 6033:     my ($string)=@_;
 6034:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6035:     return %$hash;
 6036: }
 6037: 
 6038: sub str2hashref {
 6039:   my ($string) = @_;
 6040: 
 6041:   my %hash;
 6042: 
 6043:   if($string !~ /^__HASH_REF__/) {
 6044:       if (! ($string eq '' || !defined($string))) {
 6045: 	  $hash{'error'}='Not hash reference';
 6046:       }
 6047:       return (\%hash, $string);
 6048:   }
 6049: 
 6050:   $string =~ s/^__HASH_REF__//;
 6051: 
 6052:   while($string !~ /^__END_HASH_REF__/) {
 6053:       #key
 6054:       my $key='';
 6055:       if($string =~ /^__HASH_REF__/) {
 6056:           ($key, $string)=&str2hashref($string);
 6057:           if(defined($key->{'error'})) {
 6058:               $hash{'error'}='Bad data';
 6059:               return (\%hash, $string);
 6060:           }
 6061:       } elsif($string =~ /^__ARRAY_REF__/) {
 6062:           ($key, $string)=&str2arrayref($string);
 6063:           if($key->[0] eq 'Array reference error') {
 6064:               $hash{'error'}='Bad data';
 6065:               return (\%hash, $string);
 6066:           }
 6067:       } else {
 6068:           $string =~ s/^(.*?)=//;
 6069: 	  $key=&unescape($1);
 6070:       }
 6071:       $string =~ s/^=//;
 6072: 
 6073:       #value
 6074:       my $value='';
 6075:       if($string =~ /^__HASH_REF__/) {
 6076:           ($value, $string)=&str2hashref($string);
 6077:           if(defined($value->{'error'})) {
 6078:               $hash{'error'}='Bad data';
 6079:               return (\%hash, $string);
 6080:           }
 6081:       } elsif($string =~ /^__ARRAY_REF__/) {
 6082:           ($value, $string)=&str2arrayref($string);
 6083:           if($value->[0] eq 'Array reference error') {
 6084:               $hash{'error'}='Bad data';
 6085:               return (\%hash, $string);
 6086:           }
 6087:       } else {
 6088: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6089:       }
 6090:       $string =~ s/^&//;
 6091: 
 6092:       $hash{$key}=$value;
 6093:   }
 6094: 
 6095:   $string =~ s/^__END_HASH_REF__//;
 6096: 
 6097:   return (\%hash, $string);
 6098: }
 6099: 
 6100: sub str2array {
 6101:     my ($string)=@_;
 6102:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6103:     return @$array;
 6104: }
 6105: 
 6106: sub str2arrayref {
 6107:   my ($string) = @_;
 6108:   my @array;
 6109: 
 6110:   if($string !~ /^__ARRAY_REF__/) {
 6111:       if (! ($string eq '' || !defined($string))) {
 6112: 	  $array[0]='Array reference error';
 6113:       }
 6114:       return (\@array, $string);
 6115:   }
 6116: 
 6117:   $string =~ s/^__ARRAY_REF__//;
 6118: 
 6119:   while($string !~ /^__END_ARRAY_REF__/) {
 6120:       my $value='';
 6121:       if($string =~ /^__HASH_REF__/) {
 6122:           ($value, $string)=&str2hashref($string);
 6123:           if(defined($value->{'error'})) {
 6124:               $array[0] ='Array reference error';
 6125:               return (\@array, $string);
 6126:           }
 6127:       } elsif($string =~ /^__ARRAY_REF__/) {
 6128:           ($value, $string)=&str2arrayref($string);
 6129:           if($value->[0] eq 'Array reference error') {
 6130:               $array[0] ='Array reference error';
 6131:               return (\@array, $string);
 6132:           }
 6133:       } else {
 6134: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6135:       }
 6136:       $string =~ s/^&//;
 6137: 
 6138:       push(@array, $value);
 6139:   }
 6140: 
 6141:   $string =~ s/^__END_ARRAY_REF__//;
 6142: 
 6143:   return (\@array, $string);
 6144: }
 6145: 
 6146: # -------------------------------------------------------------------Temp Store
 6147: 
 6148: sub tmpreset {
 6149:   my ($symb,$namespace,$domain,$stuname) = @_;
 6150:   if (!$symb) {
 6151:     $symb=&symbread();
 6152:     if (!$symb) { $symb= $env{'request.url'}; }
 6153:   }
 6154:   $symb=escape($symb);
 6155: 
 6156:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6157:   $namespace=~s/\//\_/g;
 6158:   $namespace=~s/\W//g;
 6159: 
 6160:   if (!$domain) { $domain=$env{'user.domain'}; }
 6161:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6162:   if ($domain eq 'public' && $stuname eq 'public') {
 6163:       $stuname=&get_requestor_ip();
 6164:   }
 6165:   my $path=LONCAPA::tempdir();
 6166:   my %hash;
 6167:   if (tie(%hash,'GDBM_File',
 6168: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6169: 	  &GDBM_WRCREAT(),0640)) {
 6170:     foreach my $key (keys(%hash)) {
 6171:       if ($key=~ /:$symb/) {
 6172: 	delete($hash{$key});
 6173:       }
 6174:     }
 6175:   }
 6176: }
 6177: 
 6178: sub tmpstore {
 6179:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6180: 
 6181:   if (!$symb) {
 6182:     $symb=&symbread();
 6183:     if (!$symb) { $symb= $env{'request.url'}; }
 6184:   }
 6185:   $symb=escape($symb);
 6186: 
 6187:   if (!$namespace) {
 6188:     # I don't think we would ever want to store this for a course.
 6189:     # it seems this will only be used if we don't have a course.
 6190:     #$namespace=$env{'request.course.id'};
 6191:     #if (!$namespace) {
 6192:       $namespace=$env{'request.state'};
 6193:     #}
 6194:   }
 6195:   $namespace=~s/\//\_/g;
 6196:   $namespace=~s/\W//g;
 6197:   if (!$domain) { $domain=$env{'user.domain'}; }
 6198:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6199:   if ($domain eq 'public' && $stuname eq 'public') {
 6200:       $stuname=&get_requestor_ip();
 6201:   }
 6202:   my $now=time;
 6203:   my %hash;
 6204:   my $path=LONCAPA::tempdir();
 6205:   if (tie(%hash,'GDBM_File',
 6206: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6207: 	  &GDBM_WRCREAT(),0640)) {
 6208:     $hash{"version:$symb"}++;
 6209:     my $version=$hash{"version:$symb"};
 6210:     my $allkeys=''; 
 6211:     foreach my $key (keys(%$storehash)) {
 6212:       $allkeys.=$key.':';
 6213:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6214:     }
 6215:     $hash{"$version:$symb:timestamp"}=$now;
 6216:     $allkeys.='timestamp';
 6217:     $hash{"$version:keys:$symb"}=$allkeys;
 6218:     if (untie(%hash)) {
 6219:       return 'ok';
 6220:     } else {
 6221:       return "error:$!";
 6222:     }
 6223:   } else {
 6224:     return "error:$!";
 6225:   }
 6226: }
 6227: 
 6228: # -----------------------------------------------------------------Temp Restore
 6229: 
 6230: sub tmprestore {
 6231:   my ($symb,$namespace,$domain,$stuname) = @_;
 6232: 
 6233:   if (!$symb) {
 6234:     $symb=&symbread();
 6235:     if (!$symb) { $symb= $env{'request.url'}; }
 6236:   }
 6237:   $symb=escape($symb);
 6238: 
 6239:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6240: 
 6241:   if (!$domain) { $domain=$env{'user.domain'}; }
 6242:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6243:   if ($domain eq 'public' && $stuname eq 'public') {
 6244:       $stuname=&get_requestor_ip();
 6245:   }
 6246:   my %returnhash;
 6247:   $namespace=~s/\//\_/g;
 6248:   $namespace=~s/\W//g;
 6249:   my %hash;
 6250:   my $path=LONCAPA::tempdir();
 6251:   if (tie(%hash,'GDBM_File',
 6252: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6253: 	  &GDBM_READER(),0640)) {
 6254:     my $version=$hash{"version:$symb"};
 6255:     $returnhash{'version'}=$version;
 6256:     my $scope;
 6257:     for ($scope=1;$scope<=$version;$scope++) {
 6258:       my $vkeys=$hash{"$scope:keys:$symb"};
 6259:       my @keys=split(/:/,$vkeys);
 6260:       my $key;
 6261:       $returnhash{"$scope:keys"}=$vkeys;
 6262:       foreach $key (@keys) {
 6263: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6264: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6265:       }
 6266:     }
 6267:     if (!(untie(%hash))) {
 6268:       return "error:$!";
 6269:     }
 6270:   } else {
 6271:     return "error:$!";
 6272:   }
 6273:   return %returnhash;
 6274: }
 6275: 
 6276: # ----------------------------------------------------------------------- Store
 6277: 
 6278: sub store {
 6279:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6280:     my $home='';
 6281: 
 6282:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6283: 
 6284:     $symb=&symbclean($symb);
 6285:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6286: 
 6287:     if (!$domain) { $domain=$env{'user.domain'}; }
 6288:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6289: 
 6290:     &devalidate($symb,$stuname,$domain);
 6291: 
 6292:     $symb=escape($symb);
 6293:     if (!$namespace) { 
 6294:        unless ($namespace=$env{'request.course.id'}) { 
 6295:           return ''; 
 6296:        } 
 6297:     }
 6298:     if (!$home) { $home=$env{'user.home'}; }
 6299: 
 6300:     $$storehash{'ip'}=&get_requestor_ip();
 6301:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6302: 
 6303:     my $namevalue='';
 6304:     foreach my $key (keys(%$storehash)) {
 6305:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6306:     }
 6307:     $namevalue=~s/\&$//;
 6308:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6309:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6310: }
 6311: 
 6312: # -------------------------------------------------------------- Critical Store
 6313: 
 6314: sub cstore {
 6315:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6316:     my $home='';
 6317: 
 6318:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6319: 
 6320:     $symb=&symbclean($symb);
 6321:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6322: 
 6323:     if (!$domain) { $domain=$env{'user.domain'}; }
 6324:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6325: 
 6326:     &devalidate($symb,$stuname,$domain);
 6327: 
 6328:     $symb=escape($symb);
 6329:     if (!$namespace) { 
 6330:        unless ($namespace=$env{'request.course.id'}) { 
 6331:           return ''; 
 6332:        } 
 6333:     }
 6334:     if (!$home) { $home=$env{'user.home'}; }
 6335: 
 6336:     $$storehash{'ip'}=&get_requestor_ip();
 6337:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6338: 
 6339:     my $namevalue='';
 6340:     foreach my $key (keys(%$storehash)) {
 6341:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6342:     }
 6343:     $namevalue=~s/\&$//;
 6344:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6345:     return critical
 6346:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6347: }
 6348: 
 6349: # --------------------------------------------------------------------- Restore
 6350: 
 6351: sub restore {
 6352:     my ($symb,$namespace,$domain,$stuname) = @_;
 6353:     my $home='';
 6354: 
 6355:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6356: 
 6357:     if (!$symb) {
 6358:         return if ($namespace eq 'courserequests');
 6359:         unless ($symb=escape(&symbread())) { return ''; }
 6360:     } else {
 6361:         unless ($namespace eq 'courserequests') {
 6362:             $symb=&escape(&symbclean($symb));
 6363:         }
 6364:     }
 6365:     if (!$namespace) { 
 6366:        unless ($namespace=$env{'request.course.id'}) { 
 6367:           return ''; 
 6368:        } 
 6369:     }
 6370:     if (!$domain) { $domain=$env{'user.domain'}; }
 6371:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6372:     if (!$home) { $home=$env{'user.home'}; }
 6373:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6374: 
 6375:     my %returnhash=();
 6376:     foreach my $line (split(/\&/,$answer)) {
 6377: 	my ($name,$value)=split(/\=/,$line);
 6378:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6379:     }
 6380:     my $version;
 6381:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6382:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6383:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6384:        }
 6385:     }
 6386:     return %returnhash;
 6387: }
 6388: 
 6389: # ---------------------------------------------------------- Course Description
 6390: #
 6391: #  
 6392: 
 6393: sub coursedescription {
 6394:     my ($courseid,$args)=@_;
 6395:     $courseid=~s/^\///;
 6396:     $courseid=~s/\_/\//g;
 6397:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6398:     my $chome=&homeserver($cnum,$cdomain);
 6399:     my $normalid=$cdomain.'_'.$cnum;
 6400:     # need to always cache even if we get errors otherwise we keep 
 6401:     # trying and trying and trying to get the course description.
 6402:     my %envhash=();
 6403:     my %returnhash=();
 6404:     
 6405:     my $expiretime=600;
 6406:     if ($env{'request.course.id'} eq $normalid) {
 6407: 	$expiretime=120;
 6408:     }
 6409: 
 6410:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6411:     if (!$args->{'freshen_cache'}
 6412: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6413: 	foreach my $key (keys(%env)) {
 6414: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6415: 	    my ($setting) = $1;
 6416: 	    $returnhash{$setting} = $env{$key};
 6417: 	}
 6418: 	return %returnhash;
 6419:     }
 6420: 
 6421:     # get the data again
 6422: 
 6423:     if (!$args->{'one_time'}) {
 6424: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6425:     }
 6426: 
 6427:     if ($chome ne 'no_host') {
 6428:        %returnhash=&dump('environment',$cdomain,$cnum);
 6429:        if (!exists($returnhash{'con_lost'})) {
 6430: 	   my $username = $env{'user.name'}; # Defult username
 6431: 	   if(defined $args->{'user'}) {
 6432: 	       $username = $args->{'user'};
 6433: 	   }
 6434:            $returnhash{'home'}= $chome;
 6435: 	   $returnhash{'domain'} = $cdomain;
 6436: 	   $returnhash{'num'} = $cnum;
 6437:            if (!defined($returnhash{'type'})) {
 6438:                $returnhash{'type'} = 'Course';
 6439:            }
 6440:            while (my ($name,$value) = each %returnhash) {
 6441:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6442:            }
 6443:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6444:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6445: 	       $username.'_'.$cdomain.'_'.$cnum;
 6446:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6447:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6448:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6449:        }
 6450:     }
 6451:     if (!$args->{'one_time'}) {
 6452: 	&appenv(\%envhash);
 6453:     }
 6454:     return %returnhash;
 6455: }
 6456: 
 6457: sub update_released_required {
 6458:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6459:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6460:         $cid = $env{'request.course.id'};
 6461:         $cdom = $env{'course.'.$cid.'.domain'};
 6462:         $cnum = $env{'course.'.$cid.'.num'};
 6463:         $chome = $env{'course.'.$cid.'.home'};
 6464:     }
 6465:     if ($needsrelease) {
 6466:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6467:         my $needsupdate;
 6468:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6469:             $needsupdate = 1;
 6470:         } else {
 6471:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6472:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6473:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6474:                 $needsupdate = 1;
 6475:             }
 6476:         }
 6477:         if ($needsupdate) {
 6478:             my %needshash = (
 6479:                              'internal.releaserequired' => $needsrelease,
 6480:                             );
 6481:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6482:             if ($putresult eq 'ok') {
 6483:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6484:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6485:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6486:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6487:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6488:                 }
 6489:             }
 6490:         }
 6491:     }
 6492:     return;
 6493: }
 6494: 
 6495: # -------------------------------------------------See if a user is privileged
 6496: 
 6497: sub privileged {
 6498:     my ($username,$domain,$possdomains,$possroles)=@_;
 6499:     my $now = time;
 6500:     my $roles;
 6501:     if (ref($possroles) eq 'ARRAY') {
 6502:         $roles = $possroles; 
 6503:     } else {
 6504:         $roles = ['dc','su'];
 6505:     }
 6506:     if (ref($possdomains) eq 'ARRAY') {
 6507:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6508:         foreach my $dom (@{$possdomains}) {
 6509:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6510:                 (ref($privileged{$dom}) eq 'HASH')) {
 6511:                 foreach my $role (@{$roles}) {
 6512:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6513:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6514:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6515:                             return 1 unless (($end && $end < $now) ||
 6516:                                              ($start && $start > $now));
 6517:                         }
 6518:                     }
 6519:                 }
 6520:             }
 6521:         }
 6522:     } else {
 6523:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6524:         my $now = time;
 6525: 
 6526:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6527:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6528:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6529:                 return 1 unless ($tend && $tend < $now) 
 6530:                         or ($tstart && $tstart > $now);
 6531:             }
 6532:         }
 6533:     }
 6534:     return 0;
 6535: }
 6536: 
 6537: sub privileged_by_domain {
 6538:     my ($domains,$roles) = @_;
 6539:     my %privileged = ();
 6540:     my $cachetime = 60*60*24;
 6541:     my $now = time;
 6542:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6543:         return %privileged;
 6544:     }
 6545:     foreach my $dom (@{$domains}) {
 6546:         next if (ref($privileged{$dom}) eq 'HASH');
 6547:         my $needroles;
 6548:         foreach my $role (@{$roles}) {
 6549:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6550:             if (defined($cached)) {
 6551:                 if (ref($result) eq 'HASH') {
 6552:                     $privileged{$dom}{$role} = $result;
 6553:                 }
 6554:             } else {
 6555:                 $needroles = 1;
 6556:             }
 6557:         }
 6558:         if ($needroles) {
 6559:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6560:             $privileged{$dom} = {};
 6561:             foreach my $server (keys(%dompersonnel)) {
 6562:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6563:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6564:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6565:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6566:                         next if ($end && $end < $now);
 6567:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6568:                             $dompersonnel{$server}{$item};
 6569:                     }
 6570:                 }
 6571:             }
 6572:             if (ref($privileged{$dom}) eq 'HASH') {
 6573:                 foreach my $role (@{$roles}) {
 6574:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6575:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6576:                     } else {
 6577:                         my %hash = ();
 6578:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6579:                     }
 6580:                 }
 6581:             }
 6582:         }
 6583:     }
 6584:     return %privileged;
 6585: }
 6586: 
 6587: # -------------------------------------------------------- Get user privileges
 6588: 
 6589: sub rolesinit {
 6590:     my ($domain, $username) = @_;
 6591:     my %userroles = ('user.login.time' => time);
 6592:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6593: 
 6594:     # firstaccess and timerinterval are related to timed maps/resources. 
 6595:     # also, blocking can be triggered by an activating timer
 6596:     # it's saved in the user's %env.
 6597:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6598:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6599:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6600:         %timerintchk, %timerintenv);
 6601: 
 6602:     foreach my $key (keys(%firstaccess)) {
 6603:         my ($cid, $rest) = split(/\0/, $key);
 6604:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6605:     }
 6606: 
 6607:     foreach my $key (keys(%timerinterval)) {
 6608:         my ($cid,$rest) = split(/\0/,$key);
 6609:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6610:     }
 6611: 
 6612:     my %allroles=();
 6613:     my %allgroups=();
 6614: 
 6615:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6616:         my $role = $rolesdump{$area};
 6617:         $area =~ s/\_\w\w$//;
 6618: 
 6619:         my ($trole, $tend, $tstart, $group_privs);
 6620: 
 6621:         if ($role =~ /^cr/) {
 6622:         # Custom role, defined by a user 
 6623:         # e.g., user.role.cr/msu/smith/mynewrole
 6624:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6625:                 $trole = $1;
 6626:                 ($tend, $tstart) = split('_', $2);
 6627:             } else {
 6628:                 $trole = $role;
 6629:             }
 6630:         } elsif ($role =~ m|^gr/|) {
 6631:         # Role of member in a group, defined within a course/community
 6632:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6633:             ($trole, $tend, $tstart) = split(/_/, $role);
 6634:             next if $tstart eq '-1';
 6635:             ($trole, $group_privs) = split(/\//, $trole);
 6636:             $group_privs = &unescape($group_privs);
 6637:         } else {
 6638:         # Just a normal role, defined in roles.tab
 6639:             ($trole, $tend, $tstart) = split(/_/,$role);
 6640:         }
 6641: 
 6642:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6643:                  $username);
 6644:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6645: 
 6646:         # role expired or not available yet?
 6647:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6648:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6649: 
 6650:         next if $area eq '' or $trole eq '';
 6651: 
 6652:         my $spec = "$trole.$area";
 6653:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6654: 
 6655:         if ($trole =~ /^cr\//) {
 6656:         # Custom role, defined by a user
 6657:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6658:         } elsif ($trole eq 'gr') {
 6659:         # Role of a member in a group, defined within a course/community
 6660:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6661:             next;
 6662:         } else {
 6663:         # Normal role, defined in roles.tab
 6664:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6665:         }
 6666: 
 6667:         my $cid = $tdomain.'_'.$trest;
 6668:         unless ($firstaccchk{$cid}) {
 6669:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6670:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6671:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6672:                         $coursetimerstarts{$cid}{$item}; 
 6673:                 }
 6674:             }
 6675:             $firstaccchk{$cid} = 1;
 6676:         }
 6677:         unless ($timerintchk{$cid}) {
 6678:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6679:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6680:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6681:                        $coursetimerintervals{$cid}{$item};
 6682:                 }
 6683:             }
 6684:             $timerintchk{$cid} = 1;
 6685:         }
 6686:     }
 6687: 
 6688:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6689:                                                           \%allroles, \%allgroups);
 6690:     $env{'user.adv'} = $userroles{'user.adv'};
 6691:     $env{'user.rar'} = $userroles{'user.rar'};
 6692: 
 6693:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6694: }
 6695: 
 6696: sub set_arearole {
 6697:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6698:     unless ($nolog) {
 6699: # log the associated role with the area
 6700:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6701:     }
 6702:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6703: }
 6704: 
 6705: sub custom_roleprivs {
 6706:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6707:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6708:     my $homsvr = &homeserver($rauthor,$rdomain);
 6709:     if (&hostname($homsvr) ne '') {
 6710:         my ($rdummy,$roledef)=
 6711:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6712:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6713:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6714:             if (defined($syspriv)) {
 6715:                 if ($trest =~ /^$match_community$/) {
 6716:                     $syspriv =~ s/bre\&S//; 
 6717:                 }
 6718:                 $$allroles{'cm./'}.=':'.$syspriv;
 6719:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6720:             }
 6721:             if ($tdomain ne '') {
 6722:                 if (defined($dompriv)) {
 6723:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6724:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6725:                 }
 6726:                 if (($trest ne '') && (defined($coursepriv))) {
 6727:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6728:                         my $rolename = $1;
 6729:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6730:                     }
 6731:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6732:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6733:                 }
 6734:             }
 6735:         }
 6736:     }
 6737: }
 6738: 
 6739: sub course_adhocrole_privs {
 6740:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6741:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6742:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6743:         my (%currprivs,%storeprivs);
 6744:         foreach my $item (split(/:/,$coursepriv)) {
 6745:             my ($priv,$restrict) = split(/\&/,$item);
 6746:             $currprivs{$priv} = $restrict;
 6747:         }
 6748:         my (%possadd,%possremove,%full);
 6749:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6750:             my ($priv,$restrict)=split(/\&/,$item);
 6751:             $full{$priv} = $restrict;
 6752:         }
 6753:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6754:              next if ($item eq '');
 6755:              my ($rule,$rest) = split(/=/,$item);
 6756:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6757:              foreach my $priv (split(/:/,$rest)) {
 6758:                  if ($priv ne '') {
 6759:                      if ($rule eq 'off') {
 6760:                          $possremove{$priv} = 1;
 6761:                      } else {
 6762:                          $possadd{$priv} = 1;
 6763:                      }
 6764:                  }
 6765:              }
 6766:          }
 6767:          foreach my $priv (sort(keys(%full))) {
 6768:              if (exists($currprivs{$priv})) {
 6769:                  unless (exists($possremove{$priv})) {
 6770:                      $storeprivs{$priv} = $currprivs{$priv};
 6771:                  }
 6772:              } elsif (exists($possadd{$priv})) {
 6773:                  $storeprivs{$priv} = $full{$priv};
 6774:              }
 6775:          }
 6776:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6777:      }
 6778:      return $coursepriv;
 6779: }
 6780: 
 6781: sub group_roleprivs {
 6782:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6783:     my $access = 1;
 6784:     my $now = time;
 6785:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6786:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6787:     if ($access) {
 6788:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6789:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6790:     }
 6791: }
 6792: 
 6793: sub standard_roleprivs {
 6794:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6795:     if (defined($pr{$trole.':s'})) {
 6796:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6797:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6798:     }
 6799:     if ($tdomain ne '') {
 6800:         if (defined($pr{$trole.':d'})) {
 6801:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6802:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6803:         }
 6804:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6805:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6806:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6807:         }
 6808:     }
 6809: }
 6810: 
 6811: sub set_userprivs {
 6812:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6813:     my $author=0;
 6814:     my $adv=0;
 6815:     my $rar=0;
 6816:     my %grouproles = ();
 6817:     if (keys(%{$allgroups}) > 0) {
 6818:         my @groupkeys; 
 6819:         foreach my $role (keys(%{$allroles})) {
 6820:             push(@groupkeys,$role);
 6821:         }
 6822:         if (ref($groups_roles) eq 'HASH') {
 6823:             foreach my $key (keys(%{$groups_roles})) {
 6824:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6825:                     push(@groupkeys,$key);
 6826:                 }
 6827:             }
 6828:         }
 6829:         if (@groupkeys > 0) {
 6830:             foreach my $role (@groupkeys) {
 6831:                 my ($trole,$area,$sec,$extendedarea);
 6832:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6833:                     $trole = $1;
 6834:                     $area = $2;
 6835:                     $sec = $3;
 6836:                     $extendedarea = $area.$sec;
 6837:                     if (exists($$allgroups{$area})) {
 6838:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6839:                             my $spec = $trole.'.'.$extendedarea;
 6840:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6841:                                                 $$allgroups{$area}{$group};
 6842:                         }
 6843:                     }
 6844:                 }
 6845:             }
 6846:         }
 6847:     }
 6848:     foreach my $group (keys(%grouproles)) {
 6849:         $$allroles{$group} = $grouproles{$group};
 6850:     }
 6851:     foreach my $role (keys(%{$allroles})) {
 6852:         my %thesepriv;
 6853:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6854:         foreach my $item (split(/:/,$$allroles{$role})) {
 6855:             if ($item ne '') {
 6856:                 my ($privilege,$restrictions)=split(/&/,$item);
 6857:                 if ($restrictions eq '') {
 6858:                     $thesepriv{$privilege}='F';
 6859:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6860:                     $thesepriv{$privilege}.=$restrictions;
 6861:                 }
 6862:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6863:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6864:             }
 6865:         }
 6866:         my $thesestr='';
 6867:         foreach my $priv (sort(keys(%thesepriv))) {
 6868: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6869: 	}
 6870:         $userroles->{'user.priv.'.$role} = $thesestr;
 6871:     }
 6872:     return ($author,$adv,$rar);
 6873: }
 6874: 
 6875: sub role_status {
 6876:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6877:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6878:         my ($one,$two) = split(m{\./},$rolekey,2);
 6879:         (undef,undef,$$role) = split(/\./,$one,3);
 6880:         unless (!defined($$role) || $$role eq '') {
 6881:             $$where = '/'.$two;
 6882:             $$trolecode=$$role.'.'.$$where;
 6883:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6884:             $$tstatus='is';
 6885:             if ($$tstart && $$tstart>$update) {
 6886:                 $$tstatus='future';
 6887:                 if ($$tstart<$now) {
 6888:                     if ($$tstart && $$tstart>$refresh) {
 6889:                         if (($$where ne '') && ($$role ne '')) {
 6890:                             my (%allroles,%allgroups,$group_privs,
 6891:                                 %groups_roles,@rolecodes);
 6892:                             my %userroles = (
 6893:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6894:                             );
 6895:                             @rolecodes = ('cm'); 
 6896:                             my $spec=$$role.'.'.$$where;
 6897:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6898:                             if ($$role =~ /^cr\//) {
 6899:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6900:                                 push(@rolecodes,'cr');
 6901:                             } elsif ($$role eq 'gr') {
 6902:                                 push(@rolecodes,$$role);
 6903:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6904:                                                     $env{'user.name'});
 6905:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6906:                                 (undef,my $group_privs) = split(/\//,$trole);
 6907:                                 $group_privs = &unescape($group_privs);
 6908:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6909:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6910:                                 &get_groups_roles($tdomain,$trest,
 6911:                                                   \%course_roles,\@rolecodes,
 6912:                                                   \%groups_roles);
 6913:                             } else {
 6914:                                 push(@rolecodes,$$role);
 6915:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6916:                             }
 6917:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6918:                                                                    \%groups_roles);
 6919:                             &appenv(\%userroles,\@rolecodes);
 6920:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6921:                         }
 6922:                     }
 6923:                     $$tstatus = 'is';
 6924:                 }
 6925:             }
 6926:             if ($$tend) {
 6927:                 if ($$tend<$update) {
 6928:                     $$tstatus='expired';
 6929:                 } elsif ($$tend<$now) {
 6930:                     $$tstatus='will_not';
 6931:                 }
 6932:             }
 6933:         }
 6934:     }
 6935: }
 6936: 
 6937: sub get_groups_roles {
 6938:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6939:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6940:                   (ref($rolecodes) eq 'ARRAY') && 
 6941:                   (ref($groups_roles) eq 'HASH')); 
 6942:     if (keys(%{$cdom_courseroles}) > 0) {
 6943:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6944:         if ($cdom ne '' && $cnum ne '') {
 6945:             foreach my $key (keys(%{$cdom_courseroles})) {
 6946:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6947:                     my $crsrole = $1;
 6948:                     my $crssec = $2;
 6949:                     if ($crsrole =~ /^cr/) {
 6950:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6951:                             push(@{$rolecodes},'cr');
 6952:                         }
 6953:                     } else {
 6954:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6955:                             push(@{$rolecodes},$crsrole);
 6956:                         }
 6957:                     }
 6958:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6959:                     if ($crssec ne '') {
 6960:                         $rolekey .= "/$crssec";
 6961:                     }
 6962:                     $rolekey .= './';
 6963:                     $groups_roles->{$rolekey} = $rolecodes;
 6964:                 }
 6965:             }
 6966:         }
 6967:     }
 6968:     return;
 6969: }
 6970: 
 6971: sub delete_env_groupprivs {
 6972:     my ($where,$courseroles,$possroles) = @_;
 6973:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6974:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6975:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6976:         %{$courseroles->{$udom}} =
 6977:             &get_my_roles('','','userroles',['active'],
 6978:                           $possroles,[$udom],1);
 6979:     }
 6980:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6981:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6982:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6983:             my $area = '/'.$cdom.'/'.$cnum;
 6984:             my $privkey = "user.priv.$crsrole.$area";
 6985:             if ($crssec ne '') {
 6986:                 $privkey .= '/'.$crssec;
 6987:             }
 6988:             $privkey .= ".$area/$group";
 6989:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6990:         }
 6991:     }
 6992:     return;
 6993: }
 6994: 
 6995: sub check_adhoc_privs {
 6996:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6997:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6998:     if ($sec) {
 6999:         $cckey .= '/'.$sec;
 7000:     } 
 7001:     my $setprivs;
 7002:     if ($env{$cckey}) {
 7003:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7004:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7005:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7006:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7007:             $setprivs = 1;
 7008:         }
 7009:     } else {
 7010:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7011:         $setprivs = 1;
 7012:     }
 7013:     return $setprivs;
 7014: }
 7015: 
 7016: sub set_adhoc_privileges {
 7017: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7018:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7019:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7020:     if ($sec ne '') {
 7021:         $area .= '/'.$sec;
 7022:     }
 7023:     my $spec = $role.'.'.$area;
 7024:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7025:                                   $env{'user.name'},1);
 7026:     my %rolehash = ();
 7027:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7028:         my $rolename = $1;
 7029:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7030:         my %domdef = &get_domain_defaults($dcdom);
 7031:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7032:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7033:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7034:             }
 7035:         }
 7036:     } else {
 7037:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7038:     }
 7039:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7040:     &appenv(\%userroles,[$role,'cm']);
 7041:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7042:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7043:             ($caller eq 'tiny')) {
 7044:         &appenv( {'request.role'        => $spec,
 7045:                   'request.role.domain' => $dcdom,
 7046:                   'request.course.sec'  => $sec,
 7047:                  }
 7048:                );
 7049:         my $tadv=0;
 7050:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7051:         &appenv({'request.role.adv'    => $tadv});
 7052:     }
 7053: }
 7054: 
 7055: # --------------------------------------------------------------- get interface
 7056: 
 7057: sub get {
 7058:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7059:    my $items='';
 7060:    foreach my $item (@$storearr) {
 7061:        $items.=&escape($item).'&';
 7062:    }
 7063:    $items=~s/\&$//;
 7064:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7065:    if (!$uname) { $uname=$env{'user.name'}; }
 7066:    my $uhome=&homeserver($uname,$udomain);
 7067: 
 7068:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7069:    my @pairs=split(/\&/,$rep);
 7070:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7071:      return @pairs;
 7072:    }
 7073:    my %returnhash=();
 7074:    my $i=0;
 7075:    foreach my $item (@$storearr) {
 7076:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7077:       $i++;
 7078:    }
 7079:    return %returnhash;
 7080: }
 7081: 
 7082: # --------------------------------------------------------------- del interface
 7083: 
 7084: sub del {
 7085:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7086:    my $items='';
 7087:    foreach my $item (@$storearr) {
 7088:        $items.=&escape($item).'&';
 7089:    }
 7090: 
 7091:    $items=~s/\&$//;
 7092:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7093:    if (!$uname) { $uname=$env{'user.name'}; }
 7094:    my $uhome=&homeserver($uname,$udomain);
 7095:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7096: }
 7097: 
 7098: # -------------------------------------------------------------- dump interface
 7099: 
 7100: sub unserialize {
 7101:     my ($rep, $escapedkeys) = @_;
 7102: 
 7103:     return {} if $rep =~ /^error/;
 7104: 
 7105:     my %returnhash=();
 7106: 	foreach my $item (split(/\&/,$rep)) {
 7107: 	    my ($key, $value) = split(/=/, $item, 2);
 7108: 	    $key = unescape($key) unless $escapedkeys;
 7109: 	    next if $key =~ /^error: 2 /;
 7110: 	    $returnhash{$key} = &thaw_unescape($value);
 7111: 	}
 7112:     #return %returnhash;
 7113:     return \%returnhash;
 7114: }        
 7115: 
 7116: # see Lond::dump_with_regexp
 7117: # if $escapedkeys hash keys won't get unescaped.
 7118: sub dump {
 7119:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 7120:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7121:     if (!$uname) { $uname=$env{'user.name'}; }
 7122:     my $uhome=&homeserver($uname,$udomain);
 7123: 
 7124:     if ($regexp) {
 7125:         $regexp=&escape($regexp);
 7126:     } else {
 7127:         $regexp='.';
 7128:     }
 7129:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7130:         # user is hosted on this machine
 7131:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7132:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7133:         return %{unserialize($reply, $escapedkeys)};
 7134:     }
 7135:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7136:     my @pairs=split(/\&/,$rep);
 7137:     my %returnhash=();
 7138:     if (!($rep =~ /^error/ )) {
 7139: 	foreach my $item (@pairs) {
 7140: 	    my ($key,$value)=split(/=/,$item,2);
 7141:         $key = unescape($key) unless $escapedkeys;
 7142:         #$key = &unescape($key);
 7143: 	    next if ($key =~ /^error: 2 /);
 7144: 	    $returnhash{$key}=&thaw_unescape($value);
 7145: 	}
 7146:     }
 7147:     return %returnhash;
 7148: }
 7149: 
 7150: 
 7151: # --------------------------------------------------------- dumpstore interface
 7152: 
 7153: sub dumpstore {
 7154:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7155:    # same as dump but keys must be escaped. They may contain colon separated
 7156:    # lists of values that may themself contain colons (e.g. symbs).
 7157:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7158: }
 7159: 
 7160: # -------------------------------------------------------------- keys interface
 7161: 
 7162: sub getkeys {
 7163:    my ($namespace,$udomain,$uname)=@_;
 7164:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7165:    if (!$uname) { $uname=$env{'user.name'}; }
 7166:    my $uhome=&homeserver($uname,$udomain);
 7167:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7168:    my @keyarray=();
 7169:    foreach my $key (split(/\&/,$rep)) {
 7170:       next if ($key =~ /^error: 2 /);
 7171:       push(@keyarray,&unescape($key));
 7172:    }
 7173:    return @keyarray;
 7174: }
 7175: 
 7176: # --------------------------------------------------------------- currentdump
 7177: sub currentdump {
 7178:    my ($courseid,$sdom,$sname)=@_;
 7179:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7180:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7181:    $sname    = $env{'user.name'}         if (! defined($sname));
 7182:    my $uhome = &homeserver($sname,$sdom);
 7183:    my $rep;
 7184: 
 7185:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7186:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7187:                    $courseid)));
 7188:    } else {
 7189:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7190:    }
 7191: 
 7192:    return if ($rep =~ /^(error:|no_such_host)/);
 7193:    #
 7194:    my %returnhash=();
 7195:    #
 7196:    if ($rep eq 'unknown_cmd') {
 7197:        # an old lond will not know currentdump
 7198:        # Do a dump and make it look like a currentdump
 7199:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7200:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7201:        my %hash = @tmp;
 7202:        @tmp=();
 7203:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7204:    } else {
 7205:        my @pairs=split(/\&/,$rep);
 7206:        foreach my $pair (@pairs) {
 7207:            my ($key,$value)=split(/=/,$pair,2);
 7208:            my ($symb,$param) = split(/:/,$key);
 7209:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7210:                                                         &thaw_unescape($value);
 7211:        }
 7212:    }
 7213:    return %returnhash;
 7214: }
 7215: 
 7216: sub convert_dump_to_currentdump{
 7217:     my %hash = %{shift()};
 7218:     my %returnhash;
 7219:     # Code ripped from lond, essentially.  The only difference
 7220:     # here is the unescaping done by lonnet::dump().  Conceivably
 7221:     # we might run in to problems with parameter names =~ /^v\./
 7222:     while (my ($key,$value) = each(%hash)) {
 7223:         my ($v,$symb,$param) = split(/:/,$key);
 7224: 	$symb  = &unescape($symb);
 7225: 	$param = &unescape($param);
 7226:         next if ($v eq 'version' || $symb eq 'keys');
 7227:         next if (exists($returnhash{$symb}) &&
 7228:                  exists($returnhash{$symb}->{$param}) &&
 7229:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7230:         $returnhash{$symb}->{$param}=$value;
 7231:         $returnhash{$symb}->{'v.'.$param}=$v;
 7232:     }
 7233:     #
 7234:     # Remove all of the keys in the hashes which keep track of
 7235:     # the version of the parameter.
 7236:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7237:         # use a foreach because we are going to delete from the hash.
 7238:         foreach my $key (keys(%$param_hash)) {
 7239:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7240:         }
 7241:     }
 7242:     return \%returnhash;
 7243: }
 7244: 
 7245: # ------------------------------------------------------ critical inc interface
 7246: 
 7247: sub cinc {
 7248:     return &inc(@_,'critical');
 7249: }
 7250: 
 7251: # --------------------------------------------------------------- inc interface
 7252: 
 7253: sub inc {
 7254:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7255:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7256:     if (!$uname) { $uname=$env{'user.name'}; }
 7257:     my $uhome=&homeserver($uname,$udomain);
 7258:     my $items='';
 7259:     if (! ref($store)) {
 7260:         # got a single value, so use that instead
 7261:         $items = &escape($store).'=&';
 7262:     } elsif (ref($store) eq 'SCALAR') {
 7263:         $items = &escape($$store).'=&';        
 7264:     } elsif (ref($store) eq 'ARRAY') {
 7265:         $items = join('=&',map {&escape($_);} @{$store});
 7266:     } elsif (ref($store) eq 'HASH') {
 7267:         while (my($key,$value) = each(%{$store})) {
 7268:             $items.= &escape($key).'='.&escape($value).'&';
 7269:         }
 7270:     }
 7271:     $items=~s/\&$//;
 7272:     if ($critical) {
 7273: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7274:     } else {
 7275: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7276:     }
 7277: }
 7278: 
 7279: # --------------------------------------------------------------- put interface
 7280: 
 7281: sub put {
 7282:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7283:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7284:    if (!$uname) { $uname=$env{'user.name'}; }
 7285:    my $uhome=&homeserver($uname,$udomain);
 7286:    my $items='';
 7287:    foreach my $item (keys(%$storehash)) {
 7288:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7289:    }
 7290:    $items=~s/\&$//;
 7291:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7292: }
 7293: 
 7294: # ------------------------------------------------------------ newput interface
 7295: 
 7296: sub newput {
 7297:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7298:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7299:    if (!$uname) { $uname=$env{'user.name'}; }
 7300:    my $uhome=&homeserver($uname,$udomain);
 7301:    my $items='';
 7302:    foreach my $key (keys(%$storehash)) {
 7303:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7304:    }
 7305:    $items=~s/\&$//;
 7306:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7307: }
 7308: 
 7309: # ---------------------------------------------------------  putstore interface
 7310: 
 7311: sub putstore {
 7312:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7313:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7314:    if (!$uname) { $uname=$env{'user.name'}; }
 7315:    my $uhome=&homeserver($uname,$udomain);
 7316:    my $items='';
 7317:    foreach my $key (keys(%$storehash)) {
 7318:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7319:    }
 7320:    $items=~s/\&$//;
 7321:    my $esc_symb=&escape($symb);
 7322:    my $esc_v=&escape($version);
 7323:    my $reply =
 7324:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7325: 	      $uhome);
 7326:    if (($tolog) && ($reply eq 'ok')) {
 7327:        my $namevalue='';
 7328:        foreach my $key (keys(%{$storehash})) {
 7329:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7330:        }
 7331:        my $ip = &get_requestor_ip();
 7332:        $namevalue .= 'ip='.&escape($ip).
 7333:                      '&host='.&escape($perlvar{'lonHostID'}).
 7334:                      '&version='.$esc_v.
 7335:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7336:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7337:    }
 7338:    if ($reply eq 'unknown_cmd') {
 7339:        # gfall back to way things use to be done
 7340:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7341: 			    $uname);
 7342:    }
 7343:    return $reply;
 7344: }
 7345: 
 7346: sub old_putstore {
 7347:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7348:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7349:     if (!$uname) { $uname=$env{'user.name'}; }
 7350:     my $uhome=&homeserver($uname,$udomain);
 7351:     my %newstorehash;
 7352:     foreach my $item (keys(%$storehash)) {
 7353: 	my $key = $version.':'.&escape($symb).':'.$item;
 7354: 	$newstorehash{$key} = $storehash->{$item};
 7355:     }
 7356:     my $items='';
 7357:     my %allitems = ();
 7358:     foreach my $item (keys(%newstorehash)) {
 7359: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7360: 	    my $key = $1.':keys:'.$2;
 7361: 	    $allitems{$key} .= $3.':';
 7362: 	}
 7363: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7364:     }
 7365:     foreach my $item (keys(%allitems)) {
 7366: 	$allitems{$item} =~ s/\:$//;
 7367: 	$items.= $item.'='.$allitems{$item}.'&';
 7368:     }
 7369:     $items=~s/\&$//;
 7370:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7371: }
 7372: 
 7373: # ------------------------------------------------------ critical put interface
 7374: 
 7375: sub cput {
 7376:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7377:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7378:    if (!$uname) { $uname=$env{'user.name'}; }
 7379:    my $uhome=&homeserver($uname,$udomain);
 7380:    my $items='';
 7381:    foreach my $item (keys(%$storehash)) {
 7382:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7383:    }
 7384:    $items=~s/\&$//;
 7385:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7386: }
 7387: 
 7388: # -------------------------------------------------------------- eget interface
 7389: 
 7390: sub eget {
 7391:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7392:    my $items='';
 7393:    foreach my $item (@$storearr) {
 7394:        $items.=&escape($item).'&';
 7395:    }
 7396:    $items=~s/\&$//;
 7397:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7398:    if (!$uname) { $uname=$env{'user.name'}; }
 7399:    my $uhome=&homeserver($uname,$udomain);
 7400:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7401:    my @pairs=split(/\&/,$rep);
 7402:    my %returnhash=();
 7403:    my $i=0;
 7404:    foreach my $item (@$storearr) {
 7405:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7406:       $i++;
 7407:    }
 7408:    return %returnhash;
 7409: }
 7410: 
 7411: # ------------------------------------------------------------ tmpput interface
 7412: sub tmpput {
 7413:     my ($storehash,$server,$context)=@_;
 7414:     my $items='';
 7415:     foreach my $item (keys(%$storehash)) {
 7416: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7417:     }
 7418:     $items=~s/\&$//;
 7419:     if (defined($context)) {
 7420:         $items .= ':'.&escape($context);
 7421:     }
 7422:     return &reply("tmpput:$items",$server);
 7423: }
 7424: 
 7425: # ------------------------------------------------------------ tmpget interface
 7426: sub tmpget {
 7427:     my ($token,$server)=@_;
 7428:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7429:     my $rep=&reply("tmpget:$token",$server);
 7430:     my %returnhash;
 7431:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7432:         return %returnhash;
 7433:     }
 7434:     foreach my $item (split(/\&/,$rep)) {
 7435: 	my ($key,$value)=split(/=/,$item);
 7436: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7437:     }
 7438:     return %returnhash;
 7439: }
 7440: 
 7441: # ------------------------------------------------------------ tmpdel interface
 7442: sub tmpdel {
 7443:     my ($token,$server)=@_;
 7444:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7445:     return &reply("tmpdel:$token",$server);
 7446: }
 7447: 
 7448: # ------------------------------------------------------------ get_timebased_id 
 7449: 
 7450: sub get_timebased_id {
 7451:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7452:         $maxtries) = @_;
 7453:     my ($newid,$error,$dellock);
 7454:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7455:         return ('','ok','invalid call to get suffix');
 7456:     }
 7457: 
 7458: # set defaults for any optional args for which values were not supplied
 7459:     if ($who eq '') {
 7460:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7461:     }
 7462:     if (!$locktries) {
 7463:         $locktries = 3;
 7464:     }
 7465:     if (!$maxtries) {
 7466:         $maxtries = 10;
 7467:     }
 7468:     
 7469:     if (($cdom eq '') || ($cnum eq '')) {
 7470:         if ($env{'request.course.id'}) {
 7471:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7472:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7473:         }
 7474:         if (($cdom eq '') || ($cnum eq '')) {
 7475:             return ('','ok','call to get suffix not in course context');
 7476:         }
 7477:     }
 7478: 
 7479: # construct locking item
 7480:     my $lockhash = {
 7481:                       $prefix."\0".'locked_'.$keyid => $who,
 7482:                    };
 7483:     my $tries = 0;
 7484: 
 7485: # attempt to get lock on nohist_$namespace file
 7486:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7487:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7488:         $tries ++;
 7489:         sleep 1;
 7490:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7491:     }
 7492: 
 7493: # attempt to get unique identifier, based on current timestamp
 7494:     if ($gotlock eq 'ok') {
 7495:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7496:         my $id = time;
 7497:         $newid = $id;
 7498:         if ($idtype eq 'addcode') {
 7499:             $newid .= &sixnum_code();
 7500:         }
 7501:         my $idtries = 0;
 7502:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7503:             if ($idtype eq 'concat') {
 7504:                 $newid = $id.$idtries;
 7505:             } elsif ($idtype eq 'addcode') {
 7506:                 $newid = $newid.&sixnum_code();
 7507:             } else {
 7508:                 $newid ++;
 7509:             }
 7510:             $idtries ++;
 7511:         }
 7512:         if (!exists($inuse{$prefix."\0".$newid})) {
 7513:             my %new_item =  (
 7514:                               $prefix."\0".$newid => $who,
 7515:                             );
 7516:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7517:                                                  $cdom,$cnum);
 7518:             if ($putresult ne 'ok') {
 7519:                 undef($newid);
 7520:                 $error = 'error saving new item: '.$putresult;
 7521:             }
 7522:         } else {
 7523:              undef($newid);
 7524:              $error = ('error: no unique suffix available for the new item ');
 7525:         }
 7526: #  remove lock
 7527:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7528:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7529:     } else {
 7530:         $error = "error: could not obtain lockfile\n";
 7531:         $dellock = 'ok';
 7532:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7533:             $dellock = 'nolock';
 7534:         }
 7535:     }
 7536:     return ($newid,$dellock,$error);
 7537: }
 7538: 
 7539: sub sixnum_code {
 7540:     my $code;
 7541:     for (0..6) {
 7542:         $code .= int( rand(9) );
 7543:     }
 7544:     return $code;
 7545: }
 7546: 
 7547: # -------------------------------------------------- portfolio access checking
 7548: 
 7549: sub portfolio_access {
 7550:     my ($requrl,$clientip) = @_;
 7551:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7552:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7553:     if ($result) {
 7554:         my %setters;
 7555:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7556:             my ($startblock,$endblock) =
 7557:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7558:             if ($startblock && $endblock) {
 7559:                 return 'B';
 7560:             }
 7561:         } else {
 7562:             my ($startblock,$endblock) =
 7563:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7564:             if ($startblock && $endblock) {
 7565:                 return 'B';
 7566:             }
 7567:         }
 7568:     }
 7569:     if ($result eq 'ok') {
 7570:        return 'F';
 7571:     } elsif ($result =~ /^[^:]+:guest_/) {
 7572:        return 'A';
 7573:     }
 7574:     return '';
 7575: }
 7576: 
 7577: sub get_portfolio_access {
 7578:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7579: 
 7580:     if (!ref($access_hash)) {
 7581: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7582: 	my %access_controls = &get_access_controls($current_perms,$group,
 7583: 						   $file_name);
 7584: 	$access_hash = $access_controls{$file_name};
 7585:     }
 7586: 
 7587:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7588:     my $now = time;
 7589:     if (ref($access_hash) eq 'HASH') {
 7590:         foreach my $key (keys(%{$access_hash})) {
 7591:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7592:             if ($start > $now) {
 7593:                 next;
 7594:             }
 7595:             if ($end && $end<$now) {
 7596:                 next;
 7597:             }
 7598:             if ($scope eq 'public') {
 7599:                 $public = $key;
 7600:                 last;
 7601:             } elsif ($scope eq 'guest') {
 7602:                 $guest = $key;
 7603:             } elsif ($scope eq 'domains') {
 7604:                 push(@domains,$key);
 7605:             } elsif ($scope eq 'users') {
 7606:                 push(@users,$key);
 7607:             } elsif ($scope eq 'course') {
 7608:                 push(@courses,$key);
 7609:             } elsif ($scope eq 'group') {
 7610:                 push(@groups,$key);
 7611:             } elsif ($scope eq 'ip') {
 7612:                 push(@ips,$key);
 7613:             }
 7614:         }
 7615:         if ($public) {
 7616:             return 'ok';
 7617:         } elsif (@ips > 0) {
 7618:             my $allowed;
 7619:             foreach my $ipkey (@ips) {
 7620:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7621:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7622:                         $allowed = 1;
 7623:                         last; 
 7624:                     }
 7625:                 }
 7626:             }
 7627:             if ($allowed) {
 7628:                 return 'ok';
 7629:             }
 7630:         }
 7631:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7632:             if ($guest) {
 7633:                 return $guest;
 7634:             }
 7635:         } else {
 7636:             if (@domains > 0) {
 7637:                 foreach my $domkey (@domains) {
 7638:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7639:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7640:                             return 'ok';
 7641:                         }
 7642:                     }
 7643:                 }
 7644:             }
 7645:             if (@users > 0) {
 7646:                 foreach my $userkey (@users) {
 7647:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7648:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7649:                             if (ref($item) eq 'HASH') {
 7650:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7651:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7652:                                     return 'ok';
 7653:                                 }
 7654:                             }
 7655:                         }
 7656:                     } 
 7657:                 }
 7658:             }
 7659:             my %roleshash;
 7660:             my @courses_and_groups = @courses;
 7661:             push(@courses_and_groups,@groups); 
 7662:             if (@courses_and_groups > 0) {
 7663:                 my (%allgroups,%allroles); 
 7664:                 my ($start,$end,$role,$sec,$group);
 7665:                 foreach my $envkey (%env) {
 7666:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7667:                         my $cid = $2.'_'.$3; 
 7668:                         if ($1 eq 'gr') {
 7669:                             $group = $4;
 7670:                             $allgroups{$cid}{$group} = $env{$envkey};
 7671:                         } else {
 7672:                             if ($4 eq '') {
 7673:                                 $sec = 'none';
 7674:                             } else {
 7675:                                 $sec = $4;
 7676:                             }
 7677:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7678:                         }
 7679:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7680:                         my $cid = $2.'_'.$3;
 7681:                         if ($4 eq '') {
 7682:                             $sec = 'none';
 7683:                         } else {
 7684:                             $sec = $4;
 7685:                         }
 7686:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7687:                     }
 7688:                 }
 7689:                 if (keys(%allroles) == 0) {
 7690:                     return;
 7691:                 }
 7692:                 foreach my $key (@courses_and_groups) {
 7693:                     my %content = %{$$access_hash{$key}};
 7694:                     my $cnum = $content{'number'};
 7695:                     my $cdom = $content{'domain'};
 7696:                     my $cid = $cdom.'_'.$cnum;
 7697:                     if (!exists($allroles{$cid})) {
 7698:                         next;
 7699:                     }    
 7700:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7701:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7702:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7703:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7704:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7705:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7706:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7707:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7708:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7709:                                         if (grep/^all$/,@sections) {
 7710:                                             return 'ok';
 7711:                                         } else {
 7712:                                             if (grep/^$sec$/,@sections) {
 7713:                                                 return 'ok';
 7714:                                             }
 7715:                                         }
 7716:                                     }
 7717:                                 }
 7718:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7719:                                     if (grep/^none$/,@groups) {
 7720:                                         return 'ok';
 7721:                                     }
 7722:                                 } else {
 7723:                                     if (grep/^all$/,@groups) {
 7724:                                         return 'ok';
 7725:                                     } 
 7726:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7727:                                         if (grep/^$group$/,@groups) {
 7728:                                             return 'ok';
 7729:                                         }
 7730:                                     }
 7731:                                 } 
 7732:                             }
 7733:                         }
 7734:                     }
 7735:                 }
 7736:             }
 7737:             if ($guest) {
 7738:                 return $guest;
 7739:             }
 7740:         }
 7741:     }
 7742:     return;
 7743: }
 7744: 
 7745: sub course_group_datechecker {
 7746:     my ($dates,$now,$status) = @_;
 7747:     my ($start,$end) = split(/\./,$dates);
 7748:     if (!$start && !$end) {
 7749:         return 'ok';
 7750:     }
 7751:     if (grep/^active$/,@{$status}) {
 7752:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7753:             return 'ok';
 7754:         }
 7755:     }
 7756:     if (grep/^previous$/,@{$status}) {
 7757:         if ($end > $now ) {
 7758:             return 'ok';
 7759:         }
 7760:     }
 7761:     if (grep/^future$/,@{$status}) {
 7762:         if ($start > $now) {
 7763:             return 'ok';
 7764:         }
 7765:     }
 7766:     return; 
 7767: }
 7768: 
 7769: sub parse_portfolio_url {
 7770:     my ($url) = @_;
 7771: 
 7772:     my ($type,$udom,$unum,$group,$file_name);
 7773:     
 7774:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7775: 	$type = 1;
 7776:         $udom = $1;
 7777:         $unum = $2;
 7778:         $file_name = $3;
 7779:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7780: 	$type = 2;
 7781:         $udom = $1;
 7782:         $unum = $2;
 7783:         $group = $3;
 7784:         $file_name = $3.'/'.$4;
 7785:     }
 7786:     if (wantarray) {
 7787: 	return ($type,$udom,$unum,$file_name,$group);
 7788:     }
 7789:     return $type;
 7790: }
 7791: 
 7792: sub is_portfolio_url {
 7793:     my ($url) = @_;
 7794:     return scalar(&parse_portfolio_url($url));
 7795: }
 7796: 
 7797: sub is_portfolio_file {
 7798:     my ($file) = @_;
 7799:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7800:         return 1;
 7801:     }
 7802:     return;
 7803: }
 7804: 
 7805: sub usertools_access {
 7806:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7807:     my ($access,%tools);
 7808:     if ($context eq '') {
 7809:         $context = 'tools';
 7810:     }
 7811:     if ($context eq 'requestcourses') {
 7812:         %tools = (
 7813:                       official   => 1,
 7814:                       unofficial => 1,
 7815:                       community  => 1,
 7816:                       textbook   => 1,
 7817:                       placement  => 1,
 7818:                       lti        => 1,
 7819:                  );
 7820:     } elsif ($context eq 'requestauthor') {
 7821:         %tools = (
 7822:                       requestauthor => 1,
 7823:                  );
 7824:     } else {
 7825:         %tools = (
 7826:                       aboutme   => 1,
 7827:                       blog      => 1,
 7828:                       webdav    => 1,
 7829:                       portfolio => 1,
 7830:                  );
 7831:     }
 7832:     return if (!defined($tools{$tool}));
 7833: 
 7834:     if (($udom eq '') || ($uname eq '')) {
 7835:         $udom = $env{'user.domain'};
 7836:         $uname = $env{'user.name'};
 7837:     }
 7838: 
 7839:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7840:         if ($action ne 'reload') {
 7841:             if ($context eq 'requestcourses') {
 7842:                 return $env{'environment.canrequest.'.$tool};
 7843:             } elsif ($context eq 'requestauthor') {
 7844:                 return $env{'environment.canrequest.author'};
 7845:             } else {
 7846:                 return $env{'environment.availabletools.'.$tool};
 7847:             }
 7848:         }
 7849:     }
 7850: 
 7851:     my ($toolstatus,$inststatus,$envkey);
 7852:     if ($context eq 'requestauthor') {
 7853:         $envkey = $context; 
 7854:     } else {
 7855:         $envkey = $context.'.'.$tool;
 7856:     }
 7857: 
 7858:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7859:          ($action ne 'reload')) {
 7860:         $toolstatus = $env{'environment.'.$envkey};
 7861:         $inststatus = $env{'environment.inststatus'};
 7862:     } else {
 7863:         if (ref($userenvref) eq 'HASH') {
 7864:             $toolstatus = $userenvref->{$envkey};
 7865:             $inststatus = $userenvref->{'inststatus'};
 7866:         } else {
 7867:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7868:             $toolstatus = $userenv{$envkey};
 7869:             $inststatus = $userenv{'inststatus'};
 7870:         }
 7871:     }
 7872: 
 7873:     if ($toolstatus ne '') {
 7874:         if ($toolstatus) {
 7875:             $access = 1;
 7876:         } else {
 7877:             $access = 0;
 7878:         }
 7879:         return $access;
 7880:     }
 7881: 
 7882:     my ($is_adv,%domdef);
 7883:     if (ref($is_advref) eq 'HASH') {
 7884:         $is_adv = $is_advref->{'is_adv'};
 7885:     } else {
 7886:         $is_adv = &is_advanced_user($udom,$uname);
 7887:     }
 7888:     if (ref($domdefref) eq 'HASH') {
 7889:         %domdef = %{$domdefref};
 7890:     } else {
 7891:         %domdef = &get_domain_defaults($udom);
 7892:     }
 7893:     if (ref($domdef{$tool}) eq 'HASH') {
 7894:         if ($is_adv) {
 7895:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7896:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7897:                     $access = 1;
 7898:                 } else {
 7899:                     $access = 0;
 7900:                 }
 7901:                 return $access;
 7902:             }
 7903:         }
 7904:         if ($inststatus ne '') {
 7905:             my ($hasaccess,$hasnoaccess);
 7906:             foreach my $affiliation (split(/:/,$inststatus)) {
 7907:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7908:                     if ($domdef{$tool}{$affiliation}) {
 7909:                         $hasaccess = 1;
 7910:                     } else {
 7911:                         $hasnoaccess = 1;
 7912:                     }
 7913:                 }
 7914:             }
 7915:             if ($hasaccess || $hasnoaccess) {
 7916:                 if ($hasaccess) {
 7917:                     $access = 1;
 7918:                 } elsif ($hasnoaccess) {
 7919:                     $access = 0; 
 7920:                 }
 7921:                 return $access;
 7922:             }
 7923:         } else {
 7924:             if ($domdef{$tool}{'default'} ne '') {
 7925:                 if ($domdef{$tool}{'default'}) {
 7926:                     $access = 1;
 7927:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7928:                     $access = 0;
 7929:                 }
 7930:                 return $access;
 7931:             }
 7932:         }
 7933:     } else {
 7934:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7935:             $access = 1;
 7936:         } else {
 7937:             $access = 0;
 7938:         }
 7939:         return $access;
 7940:     }
 7941: }
 7942: 
 7943: sub is_course_owner {
 7944:     my ($cdom,$cnum,$udom,$uname) = @_;
 7945:     if (($udom eq '') || ($uname eq '')) {
 7946:         $udom = $env{'user.domain'};
 7947:         $uname = $env{'user.name'};
 7948:     }
 7949:     unless (($udom eq '') || ($uname eq '')) {
 7950:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7951:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7952:                 return 1;
 7953:             } else {
 7954:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7955:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7956:                     return 1;
 7957:                 }
 7958:             }
 7959:         }
 7960:     }
 7961:     return;
 7962: }
 7963: 
 7964: sub is_advanced_user {
 7965:     my ($udom,$uname) = @_;
 7966:     if ($udom ne '' && $uname ne '') {
 7967:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7968:             if (wantarray) {
 7969:                 return ($env{'user.adv'},$env{'user.author'});
 7970:             } else {
 7971:                 return $env{'user.adv'};
 7972:             }
 7973:         }
 7974:     }
 7975:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7976:     my %allroles;
 7977:     my ($is_adv,$is_author);
 7978:     foreach my $role (keys(%roleshash)) {
 7979:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7980:         my $area = '/'.$tdomain.'/'.$trest;
 7981:         if ($sec ne '') {
 7982:             $area .= '/'.$sec;
 7983:         }
 7984:         if (($area ne '') && ($trole ne '')) {
 7985:             my $spec=$trole.'.'.$area;
 7986:             if ($trole =~ /^cr\//) {
 7987:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7988:             } elsif ($trole ne 'gr') {
 7989:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7990:             }
 7991:             if ($trole eq 'au') {
 7992:                 $is_author = 1;
 7993:             }
 7994:         }
 7995:     }
 7996:     foreach my $role (keys(%allroles)) {
 7997:         last if ($is_adv);
 7998:         foreach my $item (split(/:/,$allroles{$role})) {
 7999:             if ($item ne '') {
 8000:                 my ($privilege,$restrictions)=split(/&/,$item);
 8001:                 if ($privilege eq 'adv') {
 8002:                     $is_adv = 1;
 8003:                     last;
 8004:                 }
 8005:             }
 8006:         }
 8007:     }
 8008:     if (wantarray) {
 8009:         return ($is_adv,$is_author);
 8010:     }
 8011:     return $is_adv;
 8012: }
 8013: 
 8014: sub check_can_request {
 8015:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8016:     my $canreq = 0;
 8017:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8018:         $uname = $env{'user.name'};
 8019:         $udom = $env{'user.domain'};
 8020:     }
 8021:     my ($types,$typename) = &Apache::loncommon::course_types();
 8022:     my @options = ('approval','validate','autolimit');
 8023:     my $optregex = join('|',@options);
 8024:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8025:         foreach my $type (@{$types}) {
 8026:             if (&usertools_access($uname,$udom,$type,undef,
 8027:                                   'requestcourses')) {
 8028:                 $canreq ++;
 8029:                 if (ref($request_domains) eq 'HASH') {
 8030:                     push(@{$request_domains->{$type}},$udom);
 8031:                 }
 8032:                 if ($dom eq $udom) {
 8033:                     $can_request->{$type} = 1;
 8034:                 }
 8035:             }
 8036:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8037:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8038:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8039:                 if (@curr > 0) {
 8040:                     foreach my $item (@curr) {
 8041:                         if (ref($request_domains) eq 'HASH') {
 8042:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8043:                             if ($otherdom ne '') {
 8044:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 8045:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8046:                                         push(@{$request_domains->{$type}},$otherdom);
 8047:                                     }
 8048:                                 } else {
 8049:                                     push(@{$request_domains->{$type}},$otherdom);
 8050:                                 }
 8051:                             }
 8052:                         }
 8053:                     }
 8054:                     unless ($dom eq $env{'user.domain'}) {
 8055:                         $canreq ++;
 8056:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8057:                             $can_request->{$type} = 1;
 8058:                         }
 8059:                     }
 8060:                 }
 8061:             }
 8062:         }
 8063:     }
 8064:     return $canreq;
 8065: }
 8066: 
 8067: # ---------------------------------------------- Custom access rule evaluation
 8068: 
 8069: sub customaccess {
 8070:     my ($priv,$uri)=@_;
 8071:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8072:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8073:     $udom = &LONCAPA::clean_domain($udom);
 8074:     $ucrs = &LONCAPA::clean_username($ucrs);
 8075:     my $access=0;
 8076:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8077: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8078: 	if ($type eq 'user') {
 8079: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8080: 		my ($tdom,$tuname)=split(m{/},$scope);
 8081: 		if ($tdom) {
 8082: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8083: 		}
 8084: 		if ($tuname) {
 8085: 		    if ($tuname ne $env{'user.name'}) { next; }
 8086: 		}
 8087: 		$access=($effect eq 'allow');
 8088: 		last;
 8089: 	    }
 8090: 	} else {
 8091: 	    if ($role) {
 8092: 		if ($role ne $urole) { next; }
 8093: 	    }
 8094: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8095: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8096: 		if ($tdom) {
 8097: 		    if ($tdom ne $udom) { next; }
 8098: 		}
 8099: 		if ($tcrs) {
 8100: 		    if ($tcrs ne $ucrs) { next; }
 8101: 		}
 8102: 		if ($tsec) {
 8103: 		    if ($tsec ne $usec) { next; }
 8104: 		}
 8105: 		$access=($effect eq 'allow');
 8106: 		last;
 8107: 	    }
 8108: 	    if ($realm eq '' && $role eq '') {
 8109: 		$access=($effect eq 'allow');
 8110: 	    }
 8111: 	}
 8112:     }
 8113:     return $access;
 8114: }
 8115: 
 8116: # ------------------------------------------------- Check for a user privilege
 8117: 
 8118: sub allowed {
 8119:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
 8120:     my $ver_orguri=$uri;
 8121:     $uri=&deversion($uri);
 8122:     my $orguri=$uri;
 8123:     $uri=&declutter($uri);
 8124: 
 8125:     if ($priv eq 'evb') {
 8126: # Evade communication block restrictions for specified role in a course
 8127:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8128:             return $1;
 8129:         } else {
 8130:             return;
 8131:         }
 8132:     }
 8133: 
 8134:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8135: # Free bre access to adm and meta resources
 8136:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8137: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8138: 	&& ($priv eq 'bre')) {
 8139: 	return 'F';
 8140:     }
 8141: 
 8142: # Free bre access to user's own portfolio contents
 8143:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8144:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8145: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8146:         my %setters;
 8147:         my ($startblock,$endblock) = 
 8148:             &Apache::loncommon::blockcheck(\%setters,'port');
 8149:         if ($startblock && $endblock) {
 8150:             return 'B';
 8151:         } else {
 8152:             return 'F';
 8153:         }
 8154:     }
 8155: 
 8156: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8157:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8158:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8159:         if (exists($env{'request.course.id'})) {
 8160:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8161:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8162:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8163:                 my $courseprivid=$env{'request.course.id'};
 8164:                 $courseprivid=~s/\_/\//;
 8165:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8166:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8167:                     return $1; 
 8168:                 } else {
 8169:                     if ($env{'request.course.sec'}) {
 8170:                         $courseprivid.='/'.$env{'request.course.sec'};
 8171:                     }
 8172:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8173:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8174:                         return $2;
 8175:                     }
 8176:                 }
 8177:             }
 8178:         }
 8179:     }
 8180: 
 8181: # Free bre to public access
 8182: 
 8183:     if ($priv eq 'bre') {
 8184:         my $copyright;
 8185:         unless ($uri =~ /ext\.tool/) {
 8186:             $copyright=&metadata($uri,'copyright');
 8187:         }
 8188: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8189:            return 'F'; 
 8190:         }
 8191:         if ($copyright eq 'priv') {
 8192:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8193: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8194: 		return '';
 8195:             }
 8196:         }
 8197:         if ($copyright eq 'domain') {
 8198:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8199: 	    unless (($env{'user.domain'} eq $1) ||
 8200:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8201: 		return '';
 8202:             }
 8203:         }
 8204:         if ($env{'request.role'}=~ /li\.\//) {
 8205:             # Library role, so allow browsing of resources in this domain.
 8206:             return 'F';
 8207:         }
 8208:         if ($copyright eq 'custom') {
 8209: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8210:         }
 8211:     }
 8212:     # Domain coordinator is trying to create a course
 8213:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8214:         # uri is the requested domain in this case.
 8215:         # comparison to 'request.role.domain' shows if the user has selected
 8216:         # a role of dc for the domain in question.
 8217:         return 'F' if ($uri eq $env{'request.role.domain'});
 8218:     }
 8219: 
 8220:     my $thisallowed='';
 8221:     my $statecond=0;
 8222:     my $courseprivid='';
 8223: 
 8224:     my $ownaccess;
 8225:     # Community Coordinator or Assistant Co-author browsing resource space.
 8226:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8227:         if ($uri eq '') {
 8228:             $ownaccess = 1;
 8229:         } else {
 8230:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8231:                 my $udom = $env{'user.domain'};
 8232:                 my $uname = $env{'user.name'};
 8233:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8234:                     $ownaccess = 1;
 8235:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8236:                     unless ($uri =~ m{\.\./}) {
 8237:                         $ownaccess = 1;
 8238:                     }
 8239:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8240:                     my $now = time;
 8241:                     if ($uri =~ m{^([^/]+)/?$}) {
 8242:                         my $adom = $1;
 8243:                         foreach my $key (keys(%env)) {
 8244:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8245:                                 my ($start,$end) = split(/\./,$env{$key});
 8246:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8247:                                     $ownaccess = 1;
 8248:                                     last;
 8249:                                 }
 8250:                             }
 8251:                         }
 8252:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8253:                         my $adom = $1;
 8254:                         my $aname = $2;
 8255:                         foreach my $role ('ca','aa') { 
 8256:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8257:                                 my ($start,$end) =
 8258:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8259:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8260:                                     $ownaccess = 1;
 8261:                                     last;
 8262:                                 }
 8263:                             }
 8264:                         }
 8265:                     }
 8266:                 }
 8267:             }
 8268:         }
 8269:     }
 8270: 
 8271: # Course
 8272: 
 8273:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8274:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8275:             $thisallowed.=$1;
 8276:         }
 8277:     }
 8278: 
 8279: # Domain
 8280: 
 8281:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8282:        =~/\Q$priv\E\&([^\:]*)/) {
 8283:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8284:             $thisallowed.=$1;
 8285:         }
 8286:     }
 8287: 
 8288: # User who is not author or co-author might still be able to edit
 8289: # resource of an author in the domain (e.g., if Domain Coordinator).
 8290:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8291:         (&allowed('mdc',$env{'request.course.id'}))) {
 8292:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8293:             $thisallowed.=$1;
 8294:         }
 8295:     }
 8296: 
 8297: # Course: uri itself is a course
 8298:     my $courseuri=$uri;
 8299:     $courseuri=~s/\_(\d)/\/$1/;
 8300:     $courseuri=~s/^([^\/])/\/$1/;
 8301: 
 8302:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8303:        =~/\Q$priv\E\&([^\:]*)/) {
 8304:         if ($priv eq 'mip') {
 8305:             my $rem = $1;
 8306:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8307:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8308:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8309:                 if ($cdom ne '') {
 8310:                     my %passwdconf = &get_passwdconf($cdom);
 8311:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8312:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8313:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8314:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8315:                                 unless (@inststatuses) {
 8316:                                     @inststatuses = ('default');
 8317:                                 }
 8318:                                 foreach my $status (@inststatuses) {
 8319:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8320:                                         $thisallowed.=$rem;
 8321:                                     }
 8322:                                 }
 8323:                             }
 8324:                         }
 8325:                     }
 8326:                 }
 8327:             }
 8328:         } else {
 8329:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8330:                 $thisallowed.=$1;
 8331:             }
 8332:         }
 8333:     }
 8334: 
 8335: # URI is an uploaded document for this course, default permissions don't matter
 8336: # not allowing 'edit' access (editupload) to uploaded course docs
 8337:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8338: 	$thisallowed='';
 8339:         my ($match)=&is_on_map($uri);
 8340:         if ($match) {
 8341:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8342:                   =~/\Q$priv\E\&([^\:]*)/) {
 8343:                 my $value = $1;
 8344:                 my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8345:                 if ($deeplinkblock) {
 8346:                     $thisallowed='D';
 8347:                 } elsif ($noblockcheck) {
 8348:                     $thisallowed.=$value;
 8349:                 } else {
 8350:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8351:                     if (@blockers > 0) {
 8352:                         $thisallowed = 'B';
 8353:                     } else {
 8354:                         $thisallowed.=$value;
 8355:                     }
 8356:                 }
 8357:             }
 8358:         } else {
 8359:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8360:             if ($refuri) {
 8361:                 if ($refuri =~ m|^/adm/|) {
 8362:                     $thisallowed='F';
 8363:                 } else {
 8364:                     $refuri=&declutter($refuri);
 8365:                     my ($match) = &is_on_map($refuri);
 8366:                     if ($match) {
 8367:                         my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8368:                         if ($deeplinkblock) {
 8369:                             $thisallowed='D';
 8370:                         } elsif ($noblockcheck) {
 8371:                             $thisallowed='F';
 8372:                         } else {
 8373:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8374:                             if (@blockers > 0) {
 8375:                                 $thisallowed = 'B';
 8376:                             } else {
 8377:                                 $thisallowed='F';
 8378:                             }
 8379:                         }
 8380:                     }
 8381:                 }
 8382:             }
 8383:         }
 8384:     }
 8385: 
 8386:     if ($priv eq 'bre'
 8387: 	&& $thisallowed ne 'F' 
 8388: 	&& $thisallowed ne '2'
 8389: 	&& &is_portfolio_url($uri)) {
 8390: 	$thisallowed = &portfolio_access($uri,$clientip);
 8391:     }
 8392: 
 8393: # Full access at system, domain or course-wide level? Exit.
 8394:     if ($thisallowed=~/F/) {
 8395: 	return 'F';
 8396:     }
 8397: 
 8398: # If this is generating or modifying users, exit with special codes
 8399: 
 8400:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8401: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8402: 	    my ($audom,$auname)=split('/',$uri);
 8403: # no author name given, so this just checks on the general right to make a co-author in this domain
 8404: 	    unless ($auname) { return $thisallowed; }
 8405: # an author name is given, so we are about to actually make a co-author for a certain account
 8406: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8407: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8408: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8409: 	}
 8410: 	return $thisallowed;
 8411:     }
 8412: #
 8413: # Gathered so far: system, domain and course wide privileges
 8414: #
 8415: # Course: See if uri or referer is an individual resource that is part of 
 8416: # the course
 8417: 
 8418:     if ($env{'request.course.id'}) {
 8419: 
 8420: # If this is modifying password (internal auth) domains must match for user and user's role.
 8421: 
 8422:         if ($priv eq 'mip') {
 8423:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8424:                 return $thisallowed;
 8425:             } else {
 8426:                 return '';
 8427:             }
 8428:         }
 8429: 
 8430:        $courseprivid=$env{'request.course.id'};
 8431:        if ($env{'request.course.sec'}) {
 8432:           $courseprivid.='/'.$env{'request.course.sec'};
 8433:        }
 8434:        $courseprivid=~s/\_/\//;
 8435:        my $checkreferer=1;
 8436:        my ($match,$cond)=&is_on_map($uri);
 8437:        if ($match) {
 8438:            $statecond=$cond;
 8439:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8440:                =~/\Q$priv\E\&([^\:]*)/) {
 8441:                my $value = $1;
 8442:                if ($priv eq 'bre') {
 8443:                    if ($noblockcheck) {
 8444:                        $thisallowed.=$value;
 8445:                    } else {
 8446:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8447:                        if (@blockers > 0) {
 8448:                            $thisallowed = 'B';
 8449:                        } else {
 8450:                            $thisallowed.=$value;
 8451:                        }
 8452:                    }
 8453:                } else {
 8454:                    $thisallowed.=$value;
 8455:                }
 8456:                $checkreferer=0;
 8457:            }
 8458:        }
 8459: 
 8460:        if ($checkreferer) {
 8461: 	  my $refuri=$env{'httpref.'.$orguri};
 8462:             unless ($refuri) {
 8463:                 foreach my $key (keys(%env)) {
 8464: 		    if ($key=~/^httpref\..*\*/) {
 8465: 			my $pattern=$key;
 8466:                         $pattern=~s/^httpref\.\/res\///;
 8467:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8468:                         $pattern=~s/\//\\\//g;
 8469:                         if ($orguri=~/$pattern/) {
 8470: 			    $refuri=$env{$key};
 8471:                         }
 8472:                     }
 8473:                 }
 8474:             }
 8475: 
 8476:          if ($refuri) { 
 8477: 	  $refuri=&declutter($refuri);
 8478:           my ($match,$cond)=&is_on_map($refuri);
 8479:             if ($match) {
 8480:               my $refstatecond=$cond;
 8481:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8482:                   =~/\Q$priv\E\&([^\:]*)/) {
 8483:                   my $value = $1;
 8484:                   if ($priv eq 'bre') {
 8485:                       my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8486:                       if ($deeplinkblock) {
 8487:                           $thisallowed = 'D';
 8488:                       } elsif ($noblockcheck) {
 8489:                           $thisallowed.=$value;
 8490:                       } else {
 8491:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8492:                           if (@blockers > 0) {
 8493:                               $thisallowed = 'B';
 8494:                           } else {
 8495:                               $thisallowed.=$value;
 8496:                           }
 8497:                       }
 8498:                   } else {
 8499:                       $thisallowed.=$value;
 8500:                   }
 8501:                   $uri=$refuri;
 8502:                   $statecond=$refstatecond;
 8503:               }
 8504:           }
 8505:         }
 8506:        }
 8507:    }
 8508: 
 8509: #
 8510: # Gathered now: all privileges that could apply, and condition number
 8511: # 
 8512: #
 8513: # Full or no access?
 8514: #
 8515: 
 8516:     if ($thisallowed=~/F/) {
 8517: 	return 'F';
 8518:     }
 8519: 
 8520:     unless ($thisallowed) {
 8521:         return '';
 8522:     }
 8523: 
 8524: # Restrictions exist, deal with them
 8525: #
 8526: #   C:according to course preferences
 8527: #   R:according to resource settings
 8528: #   L:unless locked
 8529: #   X:according to user session state
 8530: #
 8531: 
 8532: # Possibly locked functionality, check all courses
 8533: # Locks might take effect only after 10 minutes cache expiration for other
 8534: # courses, and 2 minutes for current course
 8535: 
 8536:     if ($thisallowed=~/L/) {
 8537:         my $now = time;
 8538:         foreach my $envkey (keys(%env)) {
 8539:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8540:                my $courseid=$2;
 8541:                my $roleid=$1.'.'.$2;
 8542:                $courseid=~s/^\///;
 8543:                unless ($env{'request.role'} eq $roleid) {
 8544:                    my ($start,$end) = split(/\./,$env{$envkey});
 8545:                    next unless (($now >= $start) && (!$end || $end > $now));
 8546:                }
 8547:                my $expiretime=600;
 8548:                if ($env{'request.role'} eq $roleid) {
 8549: 		  $expiretime=120;
 8550:                }
 8551: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8552:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8553:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8554: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8555:                }
 8556:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8557:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8558: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8559:                        &log($env{'user.domain'},$env{'user.name'},
 8560:                             $env{'user.home'},
 8561:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8562:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8563:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8564: 		       return '';
 8565:                    }
 8566:                }
 8567:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8568:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8569: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8570:                        &log($env{'user.domain'},$env{'user.name'},
 8571:                             $env{'user.home'},
 8572:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8573:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8574:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8575: 		       return '';
 8576:                    }
 8577:                }
 8578: 	   }
 8579:        }
 8580:     }
 8581: 
 8582: #
 8583: # Rest of the restrictions depend on selected course
 8584: #
 8585: 
 8586:     unless ($env{'request.course.id'}) {
 8587: 	if ($thisallowed eq 'A') {
 8588: 	    return 'A';
 8589:         } elsif ($thisallowed eq 'B') {
 8590:             return 'B';
 8591: 	} else {
 8592: 	    return '1';
 8593: 	}
 8594:     }
 8595: 
 8596: #
 8597: # Now user is definitely in a course
 8598: #
 8599: 
 8600: 
 8601: # Course preferences
 8602: 
 8603:    if ($thisallowed=~/C/) {
 8604:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8605:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8606:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8607: 	   =~/\Q$rolecode\E/) {
 8608: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8609: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8610: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8611: 			$env{'request.course.id'});
 8612: 	   }
 8613:            return '';
 8614:        }
 8615: 
 8616:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8617: 	   =~/\Q$unamedom\E/) {
 8618: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8619: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8620: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8621: 			$env{'request.course.id'});
 8622: 	   }
 8623:            return '';
 8624:        }
 8625:    }
 8626: 
 8627: # Resource preferences
 8628: 
 8629:    if ($thisallowed=~/R/) {
 8630:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8631:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8632: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8633: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8634: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8635: 	   }
 8636: 	   return '';
 8637:        }
 8638:    }
 8639: 
 8640: # Restricted by state or randomout?
 8641: 
 8642:    if ($thisallowed=~/X/) {
 8643:       if ($env{'acc.randomout'}) {
 8644: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8645:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8646:             return ''; 
 8647:          }
 8648:       }
 8649:       if (&condval($statecond)) {
 8650: 	 return '2';
 8651:       } else {
 8652:          return '';
 8653:       }
 8654:    }
 8655: 
 8656:     if ($thisallowed eq 'A') {
 8657: 	return 'A';
 8658:     } elsif ($thisallowed eq 'B') {
 8659:         return 'B';
 8660:     } elsif ($thisallowed eq 'D') {
 8661:         return 'D';
 8662:     }
 8663:    return 'F';
 8664: }
 8665: 
 8666: # ------------------------------------------- Check construction space access
 8667: 
 8668: sub constructaccess {
 8669:     my ($url,$setpriv)=@_;
 8670: 
 8671: # We do not allow editing of previous versions of files
 8672:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8673: 
 8674: # Get username and domain from URL
 8675:     my ($ownername,$ownerdomain,$ownerhome);
 8676: 
 8677:     ($ownerdomain,$ownername) =
 8678:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8679: 
 8680: # The URL does not really point to any authorspace, forget it
 8681:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8682: 
 8683: # Now we need to see if the user has access to the authorspace of
 8684: # $ownername at $ownerdomain
 8685: 
 8686:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8687: # Real author for this?
 8688:        $ownerhome = $env{'user.home'};
 8689:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8690:           return ($ownername,$ownerdomain,$ownerhome);
 8691:        }
 8692:     } else {
 8693: # Co-author for this?
 8694:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8695:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8696:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8697:             return ($ownername,$ownerdomain,$ownerhome);
 8698:         }
 8699:         if ($env{'request.course.id'}) {
 8700:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8701:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8702:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8703:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8704:                     return ($ownername,$ownerdomain,$ownerhome);
 8705:                 }
 8706:             }
 8707:         }
 8708:     }
 8709: 
 8710: # We don't have any access right now. If we are not possibly going to do anything about this,
 8711: # we might as well leave
 8712:    unless ($setpriv) { return ''; }
 8713: 
 8714: # Backdoor access?
 8715:     my $allowed=&allowed('eco',$ownerdomain);
 8716: # Nope
 8717:     unless ($allowed) { return ''; }
 8718: # Looks like we may have access, but could be locked by the owner of the construction space
 8719:     if ($allowed eq 'U') {
 8720:         my %blocked=&get('environment',['domcoord.author'],
 8721:                          $ownerdomain,$ownername);
 8722: # Is blocked by owner
 8723:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8724:     }
 8725:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8726: # Grant temporary access
 8727:         my $then=$env{'user.login.time'};
 8728:         my $update=$env{'user.update.time'};
 8729:         if (!$update) { $update = $then; }
 8730:         my $refresh=$env{'user.refresh.time'};
 8731:         if (!$refresh) { $refresh = $update; }
 8732:         my $now = time;
 8733:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8734:                            $now,'ca','constructaccess');
 8735:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8736:         return($ownername,$ownerdomain,$ownerhome);
 8737:     }
 8738: # No business here
 8739:     return '';
 8740: }
 8741: 
 8742: # ----------------------------------------------------------- Content Blocking
 8743: 
 8744: {
 8745: # Caches for faster Course Contents display where content blocking
 8746: # is in operation (i.e., interval param set) for timed quiz.
 8747: #
 8748: # User for whom data are being temporarily cached.
 8749: my $cacheduser='';
 8750: # Course for which data are being temporarily cached.
 8751: my $cachedcid='';
 8752: # Cached blockers for this user (a hash of blocking items). 
 8753: my %cachedblockers=();
 8754: # When the data were last cached.
 8755: my $cachedlast='';
 8756: 
 8757: sub load_all_blockers {
 8758:     my ($uname,$udom)=@_;
 8759:     if (($uname ne '') && ($udom ne '')) { 
 8760:         if (($cacheduser eq $uname.':'.$udom) &&
 8761:             ($cachedcid eq $env{'request.course.id'}) &&
 8762:             (abs($cachedlast-time)<5)) {
 8763:             return;
 8764:         }
 8765:     }
 8766:     $cachedlast=time;
 8767:     $cacheduser=$uname.':'.$udom;
 8768:     $cachedcid=$env{'request.course.id'};
 8769:     %cachedblockers = &get_commblock_resources();
 8770:     return;
 8771: }
 8772: 
 8773: sub get_comm_blocks {
 8774:     my ($cdom,$cnum) = @_;
 8775:     if ($cdom eq '' || $cnum eq '') {
 8776:         return unless ($env{'request.course.id'});
 8777:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8778:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8779:     }
 8780:     my %commblocks;
 8781:     my $hashid=$cdom.'_'.$cnum;
 8782:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8783:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8784:         %commblocks = %{$blocksref};
 8785:     } else {
 8786:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8787:         my $cachetime = 600;
 8788:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8789:     }
 8790:     return %commblocks;
 8791: }
 8792: 
 8793: sub get_commblock_resources {
 8794:     my ($blocks) = @_;
 8795:     my %blockers = ();
 8796:     return %blockers unless ($env{'request.course.id'});
 8797:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8798:     my %commblocks;
 8799:     if (ref($blocks) eq 'HASH') {
 8800:         %commblocks = %{$blocks};
 8801:     } else {
 8802:         %commblocks = &get_comm_blocks();
 8803:     }
 8804:     return %blockers unless (keys(%commblocks) > 0); 
 8805:     my $navmap = Apache::lonnavmaps::navmap->new();
 8806:     return %blockers unless (ref($navmap));
 8807:     my $now = time;
 8808:     foreach my $block (keys(%commblocks)) {
 8809:         if ($block =~ /^(\d+)____(\d+)$/) {
 8810:             my ($start,$end) = ($1,$2);
 8811:             if ($start <= $now && $end >= $now) {
 8812:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8813:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8814:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8815:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8816:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8817:                             }
 8818:                         }
 8819:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8820:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8821:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8822:                             }
 8823:                         }
 8824:                     }
 8825:                 }
 8826:             }
 8827:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8828:             my $item = $1;
 8829:             my @to_test;
 8830:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8831:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8832:                     my @interval;
 8833:                     my $type = 'map';
 8834:                     if ($item eq 'course') {
 8835:                         $type = 'course';
 8836:                         @interval=&EXT("resource.0.interval");
 8837:                     } else {
 8838:                         if ($item =~ /___\d+___/) {
 8839:                             $type = 'resource';
 8840:                             @interval=&EXT("resource.0.interval",$item);
 8841:                             if (ref($navmap)) {                        
 8842:                                 my $res = $navmap->getBySymb($item); 
 8843:                                 push(@to_test,$res);
 8844:                             }
 8845:                         } else {
 8846:                             my $mapsymb = &symbread($item,1);
 8847:                             if ($mapsymb) {
 8848:                                 if (ref($navmap)) {
 8849:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8850:                                     if (ref($mapres)) {
 8851:                                         my $first = $mapres->map_start();
 8852:                                         my $finish = $mapres->map_finish();
 8853:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
 8854:                                         if (ref($it)) {
 8855:                                             my $res;
 8856:                                             while ($res = $it->next(undef,1)) {
 8857:                                                 next unless (ref($res));
 8858:                                                 my $symb = $res->symb();
 8859:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
 8860:                                                 @interval=&EXT("resource.0.interval",$symb);
 8861:                                                 if ($interval[1] eq 'map') {
 8862:                                                     if ($res->answerable()) {
 8863:                                                         push(@to_test,$res);
 8864:                                                         last;
 8865:                                                     }
 8866:                                                 }
 8867:                                             }
 8868:                                         }
 8869:                                     }
 8870:                                 }
 8871:                             }
 8872:                         }
 8873:                     }
 8874:                     if ($interval[0] =~ /^(\d+)/) {
 8875:                         my $timelimit = $1; 
 8876:                         my $first_access;
 8877:                         if ($type eq 'resource') {
 8878:                             $first_access=&get_first_access($interval[1],$item);
 8879:                         } elsif ($type eq 'map') {
 8880:                             $first_access=&get_first_access($interval[1],undef,$item);
 8881:                         } else {
 8882:                             $first_access=&get_first_access($interval[1]);
 8883:                         }
 8884:                         if ($first_access) {
 8885:                             my $timesup = $first_access+$timelimit;
 8886:                             if ($timesup > $now) {
 8887:                                 my $activeblock;
 8888:                                 foreach my $res (@to_test) {
 8889:                                     if ($res->answerable()) {
 8890:                                         $activeblock = 1;
 8891:                                         last;
 8892:                                     }
 8893:                                 }
 8894:                                 if ($activeblock) {
 8895:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8896:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8897:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8898:                                          }
 8899:                                     }
 8900:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8901:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8902:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8903:                                         }
 8904:                                     }
 8905:                                 }
 8906:                             }
 8907:                         }
 8908:                     }
 8909:                 }
 8910:             }
 8911:         }
 8912:     }
 8913:     return %blockers;
 8914: }
 8915: 
 8916: sub has_comm_blocking {
 8917:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 8918:     my @blockers;
 8919:     return unless ($env{'request.course.id'});
 8920:     return unless ($priv eq 'bre');
 8921:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8922:     return if ($env{'request.state'} eq 'construct');
 8923:     my %blockinfo;
 8924:     if (ref($blocks) eq 'HASH') {
 8925:         %blockinfo = &get_commblock_resources($blocks);
 8926:     } else {
 8927:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 8928:         %blockinfo = %cachedblockers;
 8929:     }
 8930:     return unless (keys(%blockinfo) > 0);
 8931:     my (%possibles,@symbs);
 8932:     if (!$symb) {
 8933:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 8934:     }
 8935:     if ($symb) {
 8936:         @symbs = ($symb);
 8937:     } elsif (keys(%possibles)) { 
 8938:         @symbs = keys(%possibles);
 8939:     }
 8940:     my $noblock;
 8941:     foreach my $symb (@symbs) {
 8942:         last if ($noblock);
 8943:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8944:         foreach my $block (keys(%blockinfo)) {
 8945:             if ($block =~ /^firstaccess____(.+)$/) {
 8946:                 my $item = $1;
 8947:                 unless ($blocked) {
 8948:                     if (($item eq $map) || ($item eq $symb)) {
 8949:                         $noblock = 1;
 8950:                         last;
 8951:                     }
 8952:                 }
 8953:             }
 8954:             if (ref($blockinfo{$block}) eq 'HASH') {
 8955:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 8956:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 8957:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8958:                             push(@blockers,$block);
 8959:                         }
 8960:                     }
 8961:                 }
 8962:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 8963:                     if ($blockinfo{$block}{'maps'}{$map}) {
 8964:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8965:                             push(@blockers,$block);
 8966:                         }
 8967:                     }
 8968:                 }
 8969:             }
 8970:         }
 8971:     }
 8972:     unless ($noblock) { 
 8973:         return @blockers;
 8974:     }
 8975:     return;
 8976: }
 8977: }
 8978: 
 8979: sub deeplink_check {
 8980:     my ($priv,$symb,$uri) = @_;
 8981:     return unless ($env{'request.course.id'});
 8982:     return unless ($priv eq 'bre');
 8983:     return if ($env{'request.state'} eq 'construct');
 8984:     return if ($env{'request.role.adv'});
 8985:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8986:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8987:     my (%possibles,@symbs);
 8988:     if (!$symb) {
 8989:         $symb = &symbread($uri,1,1,1,\%possibles);
 8990:     }
 8991:     if ($symb) {
 8992:         @symbs = ($symb);
 8993:     } elsif (keys(%possibles)) {
 8994:         @symbs = keys(%possibles);
 8995:     }
 8996: 
 8997:     my ($login,$switchrole,$allow);
 8998:     if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 8999:         my $key = $1;
 9000:         my $tinyurl;
 9001:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9002:         if (defined($cached)) {
 9003:              $tinyurl = $result;
 9004:         } else {
 9005:              my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9006:              my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9007:              if ($currtiny{$key} ne '') {
 9008:                  $tinyurl = $currtiny{$key};
 9009:                  &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9010:              }
 9011:         }
 9012:         if ($tinyurl ne '') {
 9013:             my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
 9014:             if ($cnumreq eq $cnum) {
 9015:                 $login = $posslogin;
 9016:             } else {
 9017:                 $switchrole = 1;
 9018:             }
 9019:         }
 9020:     }
 9021:     foreach my $symb (@symbs) {
 9022:         last if ($allow);
 9023:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9024:         if ($deeplink eq '') {
 9025:             $allow = 1;
 9026:         } else {
 9027:             my ($listed,$scope,$access) = split(/,/,$deeplink);
 9028:             if ($access eq 'any') {
 9029:                 $allow = 1;
 9030:             } elsif ($login) {
 9031:                 if ($access eq 'only') {
 9032:                     if ($scope eq 'res') {
 9033:                         if ($symb eq $login) {
 9034:                             $allow = 1;
 9035:                         }
 9036:                     } elsif ($scope eq 'map') {
 9037: #FIXME Compare map for $env{'request.deeplink.login'} with map for $symb
 9038:                     } elsif ($scope eq 'rec') {
 9039: #FIXME Recurse up for $env{'request.deeplink.login'} with map for $symb
 9040:                     }
 9041:                 } else {
 9042:                     my ($acctype,$item) = split(/:/,$access);
 9043:                     if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
 9044:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
 9045:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 9046:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
 9047:                                 $allow = 1;
 9048:                             }
 9049:                         }
 9050:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9051:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9052:                             my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
 9053:                             if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
 9054:                                 $allow = 1;
 9055:                             }
 9056:                         }
 9057:                     }
 9058:                 }
 9059:             }
 9060:         }
 9061:     }
 9062:     return if ($allow);
 9063:     return 1;
 9064: }
 9065: 
 9066: # -------------------------------- Deversion and split uri into path an filename   
 9067: 
 9068: #
 9069: #   Removes the version from a URI and
 9070: #   splits it in to its filename and path to the filename.
 9071: #   Seems like File::Basename could have done this more clearly.
 9072: #   Parameters:
 9073: #      $uri   - input URI
 9074: #   Returns:
 9075: #     Two element list consisting of 
 9076: #     $pathname  - the URI up to and excluding the trailing /
 9077: #     $filename  - The part of the URI following the last /
 9078: #  NOTE:
 9079: #    Another realization of this is simply:
 9080: #    use File::Basename;
 9081: #    ...
 9082: #    $uri = shift;
 9083: #    $filename = basename($uri);
 9084: #    $path     = dirname($uri);
 9085: #    return ($filename, $path);
 9086: #
 9087: #     The implementation below is probably faster however.
 9088: #
 9089: sub split_uri_for_cond {
 9090:     my $uri=&deversion(&declutter(shift));
 9091:     my @uriparts=split(/\//,$uri);
 9092:     my $filename=pop(@uriparts);
 9093:     my $pathname=join('/',@uriparts);
 9094:     return ($pathname,$filename);
 9095: }
 9096: # --------------------------------------------------- Is a resource on the map?
 9097: 
 9098: sub is_on_map {
 9099:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9100:     #Trying to find the conditional for the file
 9101:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9102: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9103:     if ($match) {
 9104: 	return (1,$1);
 9105:     } else {
 9106: 	return (0,0);
 9107:     }
 9108: }
 9109: 
 9110: # --------------------------------------------------------- Get symb from alias
 9111: 
 9112: sub get_symb_from_alias {
 9113:     my $symb=shift;
 9114:     my ($map,$resid,$url)=&decode_symb($symb);
 9115: # Already is a symb
 9116:     if ($url) { return $symb; }
 9117: # Must be an alias
 9118:     my $aliassymb='';
 9119:     my %bighash;
 9120:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9121:                             &GDBM_READER(),0640)) {
 9122:         my $rid=$bighash{'mapalias_'.$symb};
 9123: 	if ($rid) {
 9124: 	    my ($mapid,$resid)=split(/\./,$rid);
 9125: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9126: 				    $resid,$bighash{'src_'.$rid});
 9127: 	}
 9128:         untie %bighash;
 9129:     }
 9130:     return $aliassymb;
 9131: }
 9132: 
 9133: # ----------------------------------------------------------------- Define Role
 9134: 
 9135: sub definerole {
 9136:   if (allowed('mcr','/')) {
 9137:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9138:     foreach my $role (split(':',$sysrole)) {
 9139: 	my ($crole,$cqual)=split(/\&/,$role);
 9140:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9141:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9142: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9143:                return "refused:s:$crole&$cqual"; 
 9144:             }
 9145:         }
 9146:     }
 9147:     foreach my $role (split(':',$domrole)) {
 9148: 	my ($crole,$cqual)=split(/\&/,$role);
 9149:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9150:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9151: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9152:                return "refused:d:$crole&$cqual"; 
 9153:             }
 9154:         }
 9155:     }
 9156:     foreach my $role (split(':',$courole)) {
 9157: 	my ($crole,$cqual)=split(/\&/,$role);
 9158:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9159:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9160: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9161:                return "refused:c:$crole&$cqual"; 
 9162:             }
 9163:         }
 9164:     }
 9165:     my $uhome;
 9166:     if (($uname ne '') && ($udom ne '')) {
 9167:         $uhome = &homeserver($uname,$udom);
 9168:         return $uhome if ($uhome eq 'no_host');
 9169:     } else {
 9170:         $uname = $env{'user.name'};
 9171:         $udom = $env{'user.domain'};
 9172:         $uhome = $env{'user.home'};
 9173:     }
 9174:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9175:                 "$udom:$uname:rolesdef_$rolename=".
 9176:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9177:     return reply($command,$uhome);
 9178:   } else {
 9179:     return 'refused';
 9180:   }
 9181: }
 9182: 
 9183: # ---------------- Make a metadata query against the network of library servers
 9184: 
 9185: sub metadata_query {
 9186:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9187:     my %rhash;
 9188:     my %libserv = &all_library();
 9189:     my @server_list = (defined($server_array) ? @$server_array
 9190:                                               : keys(%libserv) );
 9191:     for my $server (@server_list) {
 9192:         my $domains = ''; 
 9193:         if (ref($domains_hash) eq 'HASH') {
 9194:             $domains = $domains_hash->{$server}; 
 9195:         }
 9196: 	unless ($custom or $customshow) {
 9197: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9198: 	    $rhash{$server}=$reply;
 9199: 	}
 9200: 	else {
 9201: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9202: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9203: 			     $server);
 9204: 	    $rhash{$server}=$reply;
 9205: 	}
 9206:     }
 9207:     return \%rhash;
 9208: }
 9209: 
 9210: # ----------------------------------------- Send log queries and wait for reply
 9211: 
 9212: sub log_query {
 9213:     my ($uname,$udom,$query,%filters)=@_;
 9214:     my $uhome=&homeserver($uname,$udom);
 9215:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9216:     my $uhost=&hostname($uhome);
 9217:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9218:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9219:                        $uhome);
 9220:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9221:     return get_query_reply($queryid);
 9222: }
 9223: 
 9224: # -------------------------- Update MySQL table for portfolio file
 9225: 
 9226: sub update_portfolio_table {
 9227:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9228:     if ($group ne '') {
 9229:         $file_name =~s /^\Q$group\E//;
 9230:     }
 9231:     my $homeserver = &homeserver($uname,$udom);
 9232:     my $queryid=
 9233:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9234:                ':'.&escape($file_name).':'.$action,$homeserver);
 9235:     my $reply = &get_query_reply($queryid);
 9236:     return $reply;
 9237: }
 9238: 
 9239: # -------------------------- Update MySQL allusers table
 9240: 
 9241: sub update_allusers_table {
 9242:     my ($uname,$udom,$names) = @_;
 9243:     my $homeserver = &homeserver($uname,$udom);
 9244:     my $queryid=
 9245:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9246:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9247:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9248:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9249:                'generation='.&escape($names->{'generation'}).'%%'.
 9250:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9251:                'id='.&escape($names->{'id'}),$homeserver);
 9252:     return;
 9253: }
 9254: 
 9255: # ------- Request retrieval of institutional classlists for course(s)
 9256: 
 9257: sub fetch_enrollment_query {
 9258:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9259:     my ($homeserver,$sleep,$loopmax);
 9260:     my $maxtries = 1;
 9261:     if ($context eq 'automated') {
 9262:         $homeserver = $perlvar{'lonHostID'};
 9263:         $sleep = 2;
 9264:         $loopmax = 100;
 9265:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9266:     } else {
 9267:         $homeserver = &homeserver($cnum,$dom);
 9268:     }
 9269:     my $host=&hostname($homeserver);
 9270:     my $cmd = '';
 9271:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9272:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9273:     }
 9274:     $cmd =~ s/%%$//;
 9275:     $cmd = &escape($cmd);
 9276:     my $query = 'fetchenrollment';
 9277:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9278:     unless ($queryid=~/^\Q$host\E\_/) { 
 9279:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9280:         return 'error: '.$queryid;
 9281:     }
 9282:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9283:     my $tries = 1;
 9284:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9285:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9286:         $tries ++;
 9287:     }
 9288:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9289:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9290:     } else {
 9291:         my @responses = split(/:/,$reply);
 9292:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9293:             foreach my $line (@responses) {
 9294:                 my ($key,$value) = split(/=/,$line,2);
 9295:                 $$replyref{$key} = $value;
 9296:             }
 9297:         } else {
 9298:             my $pathname = LONCAPA::tempdir();
 9299:             foreach my $line (@responses) {
 9300:                 my ($key,$value) = split(/=/,$line);
 9301:                 $$replyref{$key} = $value;
 9302:                 if ($value > 0) {
 9303:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9304:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9305:                         my $destname = $pathname.'/'.$filename;
 9306:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9307:                         if ($xml_classlist =~ /^error/) {
 9308:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9309:                         } else {
 9310:                             if ( open(FILE,">",$destname) ) {
 9311:                                 print FILE &unescape($xml_classlist);
 9312:                                 close(FILE);
 9313:                             } else {
 9314:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9315:                             }
 9316:                         }
 9317:                     }
 9318:                 }
 9319:             }
 9320:         }
 9321:         return 'ok';
 9322:     }
 9323:     return 'error';
 9324: }
 9325: 
 9326: sub get_query_reply {
 9327:     my ($queryid,$sleep,$loopmax) = @_;;
 9328:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9329:         $sleep = 0.2;
 9330:     }
 9331:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9332:         $loopmax = 100;
 9333:     }
 9334:     my $replyfile=LONCAPA::tempdir().$queryid;
 9335:     my $reply='';
 9336:     for (1..$loopmax) {
 9337: 	sleep($sleep);
 9338:         if (-e $replyfile.'.end') {
 9339: 	    if (open(my $fh,"<",$replyfile)) {
 9340: 		$reply = join('',<$fh>);
 9341: 		close($fh);
 9342: 	   } else { return 'error: reply_file_error'; }
 9343:            return &unescape($reply);
 9344: 	}
 9345:     }
 9346:     return 'timeout:'.$queryid;
 9347: }
 9348: 
 9349: sub courselog_query {
 9350: #
 9351: # possible filters:
 9352: # url: url or symb
 9353: # username
 9354: # domain
 9355: # action: view, submit, grade
 9356: # start: timestamp
 9357: # end: timestamp
 9358: #
 9359:     my (%filters)=@_;
 9360:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9361:     if ($filters{'url'}) {
 9362: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9363:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9364:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9365:     }
 9366:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9367:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9368:     return &log_query($cname,$cdom,'courselog',%filters);
 9369: }
 9370: 
 9371: sub userlog_query {
 9372: #
 9373: # possible filters:
 9374: # action: log check role
 9375: # start: timestamp
 9376: # end: timestamp
 9377: #
 9378:     my ($uname,$udom,%filters)=@_;
 9379:     return &log_query($uname,$udom,'userlog',%filters);
 9380: }
 9381: 
 9382: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9383: 
 9384: sub auto_run {
 9385:     my ($cnum,$cdom) = @_;
 9386:     my $response = 0;
 9387:     my $settings;
 9388:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9389:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9390:         $settings = $domconfig{'autoenroll'};
 9391:         if ($settings->{'run'} eq '1') {
 9392:             $response = 1;
 9393:         }
 9394:     } else {
 9395:         my $homeserver;
 9396:         if (&is_course($cdom,$cnum)) {
 9397:             $homeserver = &homeserver($cnum,$cdom);
 9398:         } else {
 9399:             $homeserver = &domain($cdom,'primary');
 9400:         }
 9401:         if ($homeserver ne 'no_host') {
 9402:             $response = &reply('autorun:'.$cdom,$homeserver);
 9403:         }
 9404:     }
 9405:     return $response;
 9406: }
 9407: 
 9408: sub auto_get_sections {
 9409:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9410:     my $homeserver;
 9411:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9412:         $homeserver = &homeserver($cnum,$cdom);
 9413:     }
 9414:     if (!defined($homeserver)) { 
 9415:         if ($cdom =~ /^$match_domain$/) {
 9416:             $homeserver = &domain($cdom,'primary');
 9417:         }
 9418:     }
 9419:     my @secs;
 9420:     if (defined($homeserver)) {
 9421:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9422:         unless ($response eq 'refused') {
 9423:             @secs = split(/:/,$response);
 9424:         }
 9425:     }
 9426:     return @secs;
 9427: }
 9428: 
 9429: sub auto_new_course {
 9430:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9431:     my $homeserver = &homeserver($cnum,$cdom);
 9432:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9433:     return $response;
 9434: }
 9435: 
 9436: sub auto_validate_courseID {
 9437:     my ($cnum,$cdom,$inst_course_id) = @_;
 9438:     my $homeserver = &homeserver($cnum,$cdom);
 9439:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9440:     return $response;
 9441: }
 9442: 
 9443: sub auto_validate_instcode {
 9444:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9445:     my ($homeserver,$response);
 9446:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9447:         $homeserver = &homeserver($cnum,$cdom);
 9448:     }
 9449:     if (!defined($homeserver)) {
 9450:         if ($cdom =~ /^$match_domain$/) {
 9451:             $homeserver = &domain($cdom,'primary');
 9452:         }
 9453:     }
 9454:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9455:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9456:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9457:     return ($outcome,$description,$defaultcredits);
 9458: }
 9459: 
 9460: sub auto_validate_inst_crosslist {
 9461:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9462:     my ($homeserver,$response);
 9463:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9464:         $homeserver = &homeserver($cnum,$cdom);
 9465:     }
 9466:     if (!defined($homeserver)) {
 9467:         if ($cdom =~ /^$match_domain$/) {
 9468:             $homeserver = &domain($cdom,'primary');
 9469:         }
 9470:     }
 9471:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9472:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9473:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9474:                          &escape($coowner),$homeserver);
 9475:     }
 9476:     return $response;
 9477: }
 9478: 
 9479: sub auto_create_password {
 9480:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9481:     my ($homeserver,$response);
 9482:     my $create_passwd = 0;
 9483:     my $authchk = '';
 9484:     if ($udom =~ /^$match_domain$/) {
 9485:         $homeserver = &domain($udom,'primary');
 9486:     }
 9487:     if ($homeserver eq '') {
 9488:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9489:             $homeserver = &homeserver($cnum,$cdom);
 9490:         }
 9491:     }
 9492:     if ($homeserver eq '') {
 9493:         $authchk = 'nodomain';
 9494:     } else {
 9495:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9496:         if ($response eq 'refused') {
 9497:             $authchk = 'refused';
 9498:         } else {
 9499:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9500:         }
 9501:     }
 9502:     return ($authparam,$create_passwd,$authchk);
 9503: }
 9504: 
 9505: sub auto_photo_permission {
 9506:     my ($cnum,$cdom,$students) = @_;
 9507:     my $homeserver = &homeserver($cnum,$cdom);
 9508:     my ($outcome,$perm_reqd,$conditions) = 
 9509: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9510:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9511: 	return (undef,undef);
 9512:     }
 9513:     return ($outcome,$perm_reqd,$conditions);
 9514: }
 9515: 
 9516: sub auto_checkphotos {
 9517:     my ($uname,$udom,$pid) = @_;
 9518:     my $homeserver = &homeserver($uname,$udom);
 9519:     my ($result,$resulttype);
 9520:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9521: 				   &escape($uname).':'.&escape($pid),
 9522: 				   $homeserver));
 9523:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9524: 	return (undef,undef);
 9525:     }
 9526:     if ($outcome) {
 9527:         ($result,$resulttype) = split(/:/,$outcome);
 9528:     } 
 9529:     return ($result,$resulttype);
 9530: }
 9531: 
 9532: sub auto_photochoice {
 9533:     my ($cnum,$cdom) = @_;
 9534:     my $homeserver = &homeserver($cnum,$cdom);
 9535:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9536: 						       &escape($cdom),
 9537: 						       $homeserver)));
 9538:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9539: 	return (undef,undef);
 9540:     }
 9541:     return ($update,$comment);
 9542: }
 9543: 
 9544: sub auto_photoupdate {
 9545:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9546:     my $homeserver = &homeserver($cnum,$dom);
 9547:     my $host=&hostname($homeserver);
 9548:     my $cmd = '';
 9549:     my $maxtries = 1;
 9550:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9551:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9552:     }
 9553:     $cmd =~ s/%%$//;
 9554:     $cmd = &escape($cmd);
 9555:     my $query = 'institutionalphotos';
 9556:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9557:     unless ($queryid=~/^\Q$host\E\_/) {
 9558:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9559:         return 'error: '.$queryid;
 9560:     }
 9561:     my $reply = &get_query_reply($queryid);
 9562:     my $tries = 1;
 9563:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9564:         $reply = &get_query_reply($queryid);
 9565:         $tries ++;
 9566:     }
 9567:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9568:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9569:     } else {
 9570:         my @responses = split(/:/,$reply);
 9571:         my $outcome = shift(@responses); 
 9572:         foreach my $item (@responses) {
 9573:             my ($key,$value) = split(/=/,$item);
 9574:             $$photo{$key} = $value;
 9575:         }
 9576:         return $outcome;
 9577:     }
 9578:     return 'error';
 9579: }
 9580: 
 9581: sub auto_instcode_format {
 9582:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9583: 	$cat_order) = @_;
 9584:     my $courses = '';
 9585:     my @homeservers;
 9586:     if ($caller eq 'global') {
 9587: 	my %servers = &get_servers($codedom,'library');
 9588: 	foreach my $tryserver (keys(%servers)) {
 9589: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9590: 		push(@homeservers,$tryserver);
 9591: 	    }
 9592:         }
 9593:     } elsif ($caller eq 'requests') {
 9594:         if ($codedom =~ /^$match_domain$/) {
 9595:             my $chome = &domain($codedom,'primary');
 9596:             unless ($chome eq 'no_host') {
 9597:                 push(@homeservers,$chome);
 9598:             }
 9599:         }
 9600:     } else {
 9601:         push(@homeservers,&homeserver($caller,$codedom));
 9602:     }
 9603:     foreach my $code (keys(%{$instcodes})) {
 9604:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9605:     }
 9606:     chop($courses);
 9607:     my $ok_response = 0;
 9608:     my $response;
 9609:     while (@homeservers > 0 && $ok_response == 0) {
 9610:         my $server = shift(@homeservers); 
 9611:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9612:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9613:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9614: 		split(/:/,$response);
 9615:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9616:             push(@{$codetitles},&str2array($codetitles_str));
 9617:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9618:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9619:             $ok_response = 1;
 9620:         }
 9621:     }
 9622:     if ($ok_response) {
 9623:         return 'ok';
 9624:     } else {
 9625:         return $response;
 9626:     }
 9627: }
 9628: 
 9629: sub auto_instcode_defaults {
 9630:     my ($domain,$returnhash,$code_order) = @_;
 9631:     my @homeservers;
 9632: 
 9633:     my %servers = &get_servers($domain,'library');
 9634:     foreach my $tryserver (keys(%servers)) {
 9635: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9636: 	    push(@homeservers,$tryserver);
 9637: 	}
 9638:     }
 9639: 
 9640:     my $response;
 9641:     foreach my $server (@homeservers) {
 9642:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9643:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9644: 	
 9645: 	foreach my $pair (split(/\&/,$response)) {
 9646: 	    my ($name,$value)=split(/\=/,$pair);
 9647: 	    if ($name eq 'code_order') {
 9648: 		@{$code_order} = split(/\&/,&unescape($value));
 9649: 	    } else {
 9650: 		$returnhash->{&unescape($name)}=&unescape($value);
 9651: 	    }
 9652: 	}
 9653: 	return 'ok';
 9654:     }
 9655: 
 9656:     return $response;
 9657: }
 9658: 
 9659: sub auto_possible_instcodes {
 9660:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9661:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9662:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9663:         return;
 9664:     }
 9665:     my (@homeservers,$uhome);
 9666:     if (defined(&domain($domain,'primary'))) {
 9667:         $uhome=&domain($domain,'primary');
 9668:         push(@homeservers,&domain($domain,'primary'));
 9669:     } else {
 9670:         my %servers = &get_servers($domain,'library');
 9671:         foreach my $tryserver (keys(%servers)) {
 9672:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9673:                 push(@homeservers,$tryserver);
 9674:             }
 9675:         }
 9676:     }
 9677:     my $response;
 9678:     foreach my $server (@homeservers) {
 9679:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9680:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9681:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9682:             split(':',$response);
 9683:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9684:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9685:         foreach my $item (split('&',$cat_title)) {   
 9686:             my ($name,$value)=split('=',$item);
 9687:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9688:         }
 9689:         foreach my $item (split('&',$cat_order)) {
 9690:             my ($name,$value)=split('=',$item);
 9691:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9692:         }
 9693:         return 'ok';
 9694:     }
 9695:     return $response;
 9696: }
 9697: 
 9698: sub auto_courserequest_checks {
 9699:     my ($dom) = @_;
 9700:     my ($homeserver,%validations);
 9701:     if ($dom =~ /^$match_domain$/) {
 9702:         $homeserver = &domain($dom,'primary');
 9703:     }
 9704:     unless ($homeserver eq 'no_host') {
 9705:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9706:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9707:             my @items = split(/&/,$response);
 9708:             foreach my $item (@items) {
 9709:                 my ($key,$value) = split('=',$item);
 9710:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9711:             }
 9712:         }
 9713:     }
 9714:     return %validations; 
 9715: }
 9716: 
 9717: sub auto_courserequest_validation {
 9718:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9719:     my ($homeserver,$response);
 9720:     if ($dom =~ /^$match_domain$/) {
 9721:         $homeserver = &domain($dom,'primary');
 9722:     }
 9723:     unless ($homeserver eq 'no_host') {
 9724:         my $customdata;
 9725:         if (ref($custominfo) eq 'HASH') {
 9726:             $customdata = &freeze_escape($custominfo);
 9727:         }
 9728:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9729:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9730:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9731:                                     $customdata,$homeserver));
 9732:     }
 9733:     return $response;
 9734: }
 9735: 
 9736: sub auto_validate_class_sec {
 9737:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9738:     my $homeserver = &homeserver($cnum,$cdom);
 9739:     my $ownerlist;
 9740:     if (ref($owners) eq 'ARRAY') {
 9741:         $ownerlist = join(',',@{$owners});
 9742:     } else {
 9743:         $ownerlist = $owners;
 9744:     }
 9745:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9746:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9747:     return $response;
 9748: }
 9749: 
 9750: sub auto_validate_instclasses {
 9751:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9752:     my ($homeserver,%validations);
 9753:     $homeserver = &homeserver($cnum,$cdom);
 9754:     unless ($homeserver eq 'no_host') {
 9755:         my $ownerlist;
 9756:         if (ref($owners) eq 'ARRAY') {
 9757:             $ownerlist = join(',',@{$owners});
 9758:         } else {
 9759:             $ownerlist = $owners;
 9760:         }
 9761:         if (ref($classesref) eq 'HASH') {
 9762:             my $classes = &freeze_escape($classesref);
 9763:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9764:                                 ':'.$cdom.':'.$classes,$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:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9770:                 }
 9771:             }
 9772:         }
 9773:     }
 9774:     return %validations;
 9775: }
 9776: 
 9777: sub auto_crsreq_update {
 9778:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9779:         $code,$accessstart,$accessend,$inbound) = @_;
 9780:     my ($homeserver,%crsreqresponse);
 9781:     if ($cdom =~ /^$match_domain$/) {
 9782:         $homeserver = &domain($cdom,'primary');
 9783:     }
 9784:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9785:         my $info;
 9786:         if (ref($inbound) eq 'HASH') {
 9787:             $info = &freeze_escape($inbound);
 9788:         }
 9789:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9790:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9791:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9792:                             &escape($title).':'.&escape($code).':'.
 9793:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9794:                             $homeserver);
 9795:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9796:             my @items = split(/&/,$response);
 9797:             foreach my $item (@items) {
 9798:                 my ($key,$value) = split('=',$item);
 9799:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9800:             }
 9801:         }
 9802:     }
 9803:     return \%crsreqresponse;
 9804: }
 9805: 
 9806: sub auto_export_grades {
 9807:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9808:     my ($homeserver,%exportresponse);
 9809:     if ($cdom =~ /^$match_domain$/) {
 9810:         $homeserver = &domain($cdom,'primary');
 9811:     }
 9812:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9813:         my $info;
 9814:         if (ref($inforef) eq 'HASH') {
 9815:             $info = &freeze_escape($inforef);
 9816:         }
 9817:         if (ref($gradesref) eq 'HASH') {
 9818:             my $grades = &freeze_escape($gradesref);
 9819:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9820:                                 $info.':'.$grades,$homeserver);
 9821:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9822:                 my @items = split(/&/,$response);
 9823:                 foreach my $item (@items) {
 9824:                     my ($key,$value) = split('=',$item);
 9825:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9826:                 }
 9827:             }
 9828:         }
 9829:     }
 9830:     return \%exportresponse;
 9831: }
 9832: 
 9833: sub check_instcode_cloning {
 9834:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9835:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9836:         return;
 9837:     }
 9838:     my $canclone;
 9839:     if (@{$code_order} > 0) {
 9840:         my $instcoderegexp ='^';
 9841:         my @clonecodes = split(/\&/,$cloner);
 9842:         foreach my $item (@{$code_order}) {
 9843:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9844:                 foreach my $pair (@clonecodes) {
 9845:                     my ($key,$val) = split(/\=/,$pair,2);
 9846:                     $val = &unescape($val);
 9847:                     if ($key eq $item) {
 9848:                         $instcoderegexp .= '('.$val.')';
 9849:                         last;
 9850:                     }
 9851:                 }
 9852:             } else {
 9853:                 $instcoderegexp .= $codedefaults->{$item};
 9854:             }
 9855:         }
 9856:         $instcoderegexp .= '$';
 9857:         my (@from,@to);
 9858:         eval {
 9859:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9860:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9861:         };
 9862:         if ((@from > 0) && (@to > 0)) {
 9863:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9864:             if (!@diffs) {
 9865:                 $canclone = 1;
 9866:             }
 9867:         }
 9868:     }
 9869:     return $canclone;
 9870: }
 9871: 
 9872: sub default_instcode_cloning {
 9873:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9874:     my (%codedefaults,@code_order,$canclone);
 9875:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9876:         %codedefaults = %{$codedefaultsref};
 9877:         @code_order = @{$codeorderref};
 9878:     } elsif ($clonedom) {
 9879:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9880:     }
 9881:     if (($domdefclone) && (@code_order)) {
 9882:         my @clonecodes = split(/\+/,$domdefclone);
 9883:         my $instcoderegexp ='^';
 9884:         foreach my $item (@code_order) {
 9885:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9886:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9887:             } else {
 9888:                 $instcoderegexp .= $codedefaults{$item};
 9889:             }
 9890:         }
 9891:         $instcoderegexp .= '$';
 9892:         my (@from,@to);
 9893:         eval {
 9894:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9895:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9896:         };
 9897:         if ((@from > 0) && (@to > 0)) {
 9898:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9899:             if (!@diffs) {
 9900:                 $canclone = 1;
 9901:             }
 9902:         }
 9903:     }
 9904:     return $canclone;
 9905: }
 9906: 
 9907: # ------------------------------------------------------- Course Group routines
 9908: 
 9909: sub get_coursegroups {
 9910:     my ($cdom,$cnum,$group,$namespace) = @_;
 9911:     return(&dump($namespace,$cdom,$cnum,$group));
 9912: }
 9913: 
 9914: sub modify_coursegroup {
 9915:     my ($cdom,$cnum,$groupsettings) = @_;
 9916:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9917: }
 9918: 
 9919: sub toggle_coursegroup_status {
 9920:     my ($cdom,$cnum,$group,$action) = @_;
 9921:     my ($from_namespace,$to_namespace);
 9922:     if ($action eq 'delete') {
 9923:         $from_namespace = 'coursegroups';
 9924:         $to_namespace = 'deleted_groups';
 9925:     } else {
 9926:         $from_namespace = 'deleted_groups';
 9927:         $to_namespace = 'coursegroups';
 9928:     }
 9929:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9930:     if (my $tmp = &error(%curr_group)) {
 9931:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9932:         return ('read error',$tmp);
 9933:     } else {
 9934:         my %savedsettings = %curr_group; 
 9935:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9936:         my $deloutcome;
 9937:         if ($result eq 'ok') {
 9938:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9939:         } else {
 9940:             return ('write error',$result);
 9941:         }
 9942:         if ($deloutcome eq 'ok') {
 9943:             return 'ok';
 9944:         } else {
 9945:             return ('delete error',$deloutcome);
 9946:         }
 9947:     }
 9948: }
 9949: 
 9950: sub modify_group_roles {
 9951:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9952:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9953:     my $role = 'gr/'.&escape($userprivs);
 9954:     my ($uname,$udom) = split(/:/,$user);
 9955:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9956:     if ($result eq 'ok') {
 9957:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9958:     }
 9959:     return $result;
 9960: }
 9961: 
 9962: sub modify_coursegroup_membership {
 9963:     my ($cdom,$cnum,$membership) = @_;
 9964:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9965:     return $result;
 9966: }
 9967: 
 9968: sub get_active_groups {
 9969:     my ($udom,$uname,$cdom,$cnum) = @_;
 9970:     my $now = time;
 9971:     my %groups = ();
 9972:     foreach my $key (keys(%env)) {
 9973:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9974:             my ($start,$end) = split(/\./,$env{$key});
 9975:             if (($end!=0) && ($end<$now)) { next; }
 9976:             if (($start!=0) && ($start>$now)) { next; }
 9977:             if ($1 eq $cdom && $2 eq $cnum) {
 9978:                 $groups{$3} = $env{$key} ;
 9979:             }
 9980:         }
 9981:     }
 9982:     return %groups;
 9983: }
 9984: 
 9985: sub get_group_membership {
 9986:     my ($cdom,$cnum,$group) = @_;
 9987:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9988: }
 9989: 
 9990: sub get_users_groups {
 9991:     my ($udom,$uname,$courseid) = @_;
 9992:     my @usersgroups;
 9993:     my $cachetime=1800;
 9994: 
 9995:     my $hashid="$udom:$uname:$courseid";
 9996:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9997:     if (defined($cached)) {
 9998:         @usersgroups = split(/:/,$grouplist);
 9999:     } else {  
10000:         $grouplist = '';
10001:         my $courseurl = &courseid_to_courseurl($courseid);
10002:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10003:         my $access_end = $env{'course.'.$courseid.
10004:                               '.default_enrollment_end_date'};
10005:         my $now = time;
10006:         foreach my $key (keys(%roleshash)) {
10007:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10008:                 my $group = $1;
10009:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10010:                     my $start = $2;
10011:                     my $end = $1;
10012:                     if ($start == -1) { next; } # deleted from group
10013:                     if (($start!=0) && ($start>$now)) { next; }
10014:                     if (($end!=0) && ($end<$now)) {
10015:                         if ($access_end && $access_end < $now) {
10016:                             if ($access_end - $end < 86400) {
10017:                                 push(@usersgroups,$group);
10018:                             }
10019:                         }
10020:                         next;
10021:                     }
10022:                     push(@usersgroups,$group);
10023:                 }
10024:             }
10025:         }
10026:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10027:         $grouplist = join(':',@usersgroups);
10028:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10029:     }
10030:     return @usersgroups;
10031: }
10032: 
10033: sub devalidate_getgroups_cache {
10034:     my ($udom,$uname,$cdom,$cnum)=@_;
10035:     my $courseid = $cdom.'_'.$cnum;
10036: 
10037:     my $hashid="$udom:$uname:$courseid";
10038:     &devalidate_cache_new('getgroups',$hashid);
10039: }
10040: 
10041: # ------------------------------------------------------------------ Plain Text
10042: 
10043: sub plaintext {
10044:     my ($short,$type,$cid,$forcedefault) = @_;
10045:     if ($short =~ m{^cr/}) {
10046: 	return (split('/',$short))[-1];
10047:     }
10048:     if (!defined($cid)) {
10049:         $cid = $env{'request.course.id'};
10050:     }
10051:     my %rolenames = (
10052:                       Course    => 'std',
10053:                       Community => 'alt1',
10054:                       Placement => 'std',
10055:                     );
10056:     if ($cid ne '') {
10057:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10058:             unless ($forcedefault) {
10059:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10060:                 &Apache::lonlocal::mt_escape(\$roletext);
10061:                 return &Apache::lonlocal::mt($roletext);
10062:             }
10063:         }
10064:     }
10065:     if ((defined($type)) && (defined($rolenames{$type})) &&
10066:         (defined($rolenames{$type})) && 
10067:         (defined($prp{$short}{$rolenames{$type}}))) {
10068:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10069:     } elsif ($cid ne '') {
10070:         my $crstype = $env{'course.'.$cid.'.type'};
10071:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10072:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10073:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10074:         }
10075:     }
10076:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10077: }
10078: 
10079: # ----------------------------------------------------------------- Assign Role
10080: 
10081: sub assignrole {
10082:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10083:         $context)=@_;
10084:     my $mrole;
10085:     if ($role =~ /^cr\//) {
10086:         my $cwosec=$url;
10087:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10088: 	unless (&allowed('ccr',$cwosec)) {
10089:            my $refused = 1;
10090:            if ($context eq 'requestcourses') {
10091:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10092:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10093:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10094:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10095:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10096:                            if ($crsenv{'internal.courseowner'} eq
10097:                                $env{'user.name'}.':'.$env{'user.domain'}) {
10098:                                $refused = '';
10099:                            }
10100:                        }
10101:                    }
10102:                }
10103:            }
10104:            if ($refused) {
10105:                &logthis('Refused custom assignrole: '.
10106:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10107:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10108:                return 'refused';
10109:            }
10110:         }
10111:         $mrole='cr';
10112:     } elsif ($role =~ /^gr\//) {
10113:         my $cwogrp=$url;
10114:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10115:         unless (&allowed('mdg',$cwogrp)) {
10116:             &logthis('Refused group assignrole: '.
10117:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10118:                     $env{'user.name'}.' at '.$env{'user.domain'});
10119:             return 'refused';
10120:         }
10121:         $mrole='gr';
10122:     } else {
10123:         my $cwosec=$url;
10124:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10125:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10126:             my $refused;
10127:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10128:                 if (!(&allowed('c'.$role,$url))) {
10129:                     $refused = 1;
10130:                 }
10131:             } else {
10132:                 $refused = 1;
10133:             }
10134:             if ($refused) {
10135:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10136:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10137:                     my %crsenv;
10138:                     if ($role eq 'cc' || $role eq 'co') {
10139:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10140:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10141:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10142:                                 if ($crsenv{'internal.courseowner'} eq 
10143:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10144:                                     $refused = '';
10145:                                 }
10146:                             }
10147:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10148:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10149:                                 if ($crsenv{'internal.courseowner'} eq 
10150:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10151:                                     $refused = '';
10152:                                 }
10153:                             }
10154:                         }
10155:                     }
10156:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10157:                     if ($role eq 'st') {
10158:                         $refused = '';
10159:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10160:                         $refused = '';
10161:                     }
10162:                 } elsif ($context eq 'requestcourses') {
10163:                     my @possroles = ('st','ta','ep','in','cc','co');
10164:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10165:                         my $wrongcc;
10166:                         if ($cnum =~ /^$match_community$/) {
10167:                             $wrongcc = 1 if ($role eq 'cc');
10168:                         } else {
10169:                             $wrongcc = 1 if ($role eq 'co');
10170:                         }
10171:                         unless ($wrongcc) {
10172:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10173:                             if ($crsenv{'internal.courseowner'} eq 
10174:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10175:                                 $refused = '';
10176:                             }
10177:                         }
10178:                     }
10179:                 } elsif ($context eq 'requestauthor') {
10180:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10181:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10182:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10183:                             $refused = '';
10184:                         } else {
10185:                             my %domdefaults = &get_domain_defaults($udom);
10186:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10187:                                 my $checkbystatus;
10188:                                 if ($env{'user.adv'}) { 
10189:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10190:                                     if ($disposition eq 'automatic') {
10191:                                         $refused = '';
10192:                                     } elsif ($disposition eq '') {
10193:                                         $checkbystatus = 1;
10194:                                     } 
10195:                                 } else {
10196:                                     $checkbystatus = 1;
10197:                                 }
10198:                                 if ($checkbystatus) {
10199:                                     if ($env{'environment.inststatus'}) {
10200:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10201:                                         foreach my $type (@inststatuses) {
10202:                                             if (($type ne '') &&
10203:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10204:                                                 $refused = '';
10205:                                             }
10206:                                         }
10207:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10208:                                         $refused = '';
10209:                                     }
10210:                                 }
10211:                             }
10212:                         }
10213:                     }
10214:                 }
10215:                 if ($refused) {
10216:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10217:                              ' '.$role.' '.$end.' '.$start.' by '.
10218: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10219:                     return 'refused';
10220:                 }
10221:             }
10222:         } elsif ($role eq 'au') {
10223:             if ($url ne '/'.$udom.'/') {
10224:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10225:                          ' to assign author role for '.$uname.':'.$udom.
10226:                          ' in domain: '.$url.' refused (wrong domain).');
10227:                 return 'refused';
10228:             }
10229:         }
10230:         $mrole=$role;
10231:     }
10232:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10233:                 "$udom:$uname:$url".'_'."$mrole=$role";
10234:     if ($end) { $command.='_'.$end; }
10235:     if ($start) {
10236: 	if ($end) { 
10237:            $command.='_'.$start; 
10238:         } else {
10239:            $command.='_0_'.$start;
10240:         }
10241:     }
10242:     my $origstart = $start;
10243:     my $origend = $end;
10244:     my $delflag;
10245: # actually delete
10246:     if ($deleteflag) {
10247: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10248: # modify command to delete the role
10249:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10250:                 "$udom:$uname:$url".'_'."$mrole";
10251: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10252: # set start and finish to negative values for userrolelog
10253:            $start=-1;
10254:            $end=-1;
10255:            $delflag = 1;
10256:         }
10257:     }
10258: # send command
10259:     my $answer=&reply($command,&homeserver($uname,$udom));
10260: # log new user role if status is ok
10261:     if ($answer eq 'ok') {
10262: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10263:         if (($role eq 'cc') || ($role eq 'in') ||
10264:             ($role eq 'ep') || ($role eq 'ad') ||
10265:             ($role eq 'ta') || ($role eq 'st') ||
10266:             ($role=~/^cr/) || ($role eq 'gr') ||
10267:             ($role eq 'co')) {
10268: # for course roles, perform group memberships changes triggered by role change.
10269:             unless ($role =~ /^gr/) {
10270:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10271:                                                  $origstart,$selfenroll,$context);
10272:             }
10273:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10274:                            $selfenroll,$context);
10275:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10276:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10277:                  ($role eq 'da')) {
10278:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10279:                            $context);
10280:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10281:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10282:                              $context); 
10283:         }
10284:         if ($role eq 'cc') {
10285:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10286:         }
10287:     }
10288:     return $answer;
10289: }
10290: 
10291: sub autoupdate_coowners {
10292:     my ($url,$end,$start,$uname,$udom) = @_;
10293:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10294:     if (($cdom ne '') && ($cnum ne '')) {
10295:         my $now = time;
10296:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10297:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10298:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10299:             my $instcode = $coursehash{'internal.coursecode'};
10300:             my $xlists = $coursehash{'internal.crosslistings'};
10301:             if ($instcode ne '') {
10302:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10303:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10304:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10305:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10306:                         unless ($result eq 'valid') {
10307:                             if ($xlists ne '') {
10308:                                 foreach my $xlist (split(',',$xlists)) {
10309:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10310:                                     $result =
10311:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10312:                                                                       $inst_crosslist,$uname.':'.$udom);
10313:                                     last if ($result eq 'valid');
10314:                                 }
10315:                             }
10316:                         }
10317:                         if ($result eq 'valid') {
10318:                             if ($coursehash{'internal.co-owners'}) {
10319:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10320:                                     push(@newcoowners,$coowner);
10321:                                 }
10322:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10323:                                     push(@newcoowners,$uname.':'.$udom);
10324:                                 }
10325:                                 @newcoowners = sort(@newcoowners);
10326:                             } else {
10327:                                 push(@newcoowners,$uname.':'.$udom);
10328:                             }
10329:                         } elsif ($coursehash{'internal.co-owners'}) {
10330:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10331:                                 unless ($coowner eq $uname.':'.$udom) {
10332:                                     push(@newcoowners,$coowner);
10333:                                 }
10334:                             }
10335:                             unless (@newcoowners > 0) {
10336:                                 $delcoowners = 1;
10337:                                 $coowners = '';
10338:                             }
10339:                         }
10340:                         if (@newcoowners || $delcoowners) {
10341:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10342:                                             $delcoowners,@newcoowners);
10343:                         }
10344:                     }
10345:                 }
10346:             }
10347:         }
10348:     }
10349: }
10350: 
10351: sub store_coowners {
10352:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10353:     my $cid = $cdom.'_'.$cnum;
10354:     my ($coowners,$delresult,$putresult);
10355:     if (@newcoowners) {
10356:         $coowners = join(',',@newcoowners);
10357:         my %coownershash = (
10358:                             'internal.co-owners' => $coowners,
10359:                            );
10360:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10361:         if ($putresult eq 'ok') {
10362:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10363:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10364:             }
10365:         }
10366:     }
10367:     if ($delcoowners) {
10368:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10369:         if ($delresult eq 'ok') {
10370:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10371:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10372:             }
10373:         }
10374:     }
10375:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10376:         my %crsinfo =
10377:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10378:         if (ref($crsinfo{$cid}) eq 'HASH') {
10379:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10380:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10381:         }
10382:     }
10383: }
10384: 
10385: # -------------------------------------------------- Modify user authentication
10386: # Overrides without validation
10387: 
10388: sub modifyuserauth {
10389:     my ($udom,$uname,$umode,$upass)=@_;
10390:     my $uhome=&homeserver($uname,$udom);
10391:     my $allowed;
10392:     if (&allowed('mau',$udom)) {
10393:         $allowed = 1;
10394:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10395:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10396:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10397:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10398:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10399:         if (($cdom ne '') && ($cnum ne '')) {
10400:             my $is_owner = &is_course_owner($cdom,$cnum);
10401:             if ($is_owner) {
10402:                 $allowed = 1;
10403:             }
10404:         }
10405:     }
10406:     unless ($allowed) { return 'refused'; }
10407:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10408:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10409:              ' in domain '.$env{'request.role.domain'});  
10410:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10411: 		     &escape($upass),$uhome);
10412:     my $ip = &get_requestor_ip();
10413:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10414:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10415:          '(Remote '.$ip.'): '.$reply);
10416:     &log($udom,,$uname,$uhome,
10417:         'Authentication changed by '.$env{'user.domain'}.', '.
10418:                                      $env{'user.name'}.', '.$umode.
10419:          '(Remote '.$ip.'): '.$reply);
10420:     unless ($reply eq 'ok') {
10421:         &logthis('Authentication mode error: '.$reply);
10422: 	return 'error: '.$reply;
10423:     }   
10424:     return 'ok';
10425: }
10426: 
10427: # --------------------------------------------------------------- Modify a user
10428: 
10429: sub modifyuser {
10430:     my ($udom,    $uname, $uid,
10431:         $umode,   $upass, $first,
10432:         $middle,  $last,  $gene,
10433:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10434:     $udom= &LONCAPA::clean_domain($udom);
10435:     $uname=&LONCAPA::clean_username($uname);
10436:     my $showcandelete = 'none';
10437:     if (ref($candelete) eq 'ARRAY') {
10438:         if (@{$candelete} > 0) {
10439:             $showcandelete = join(', ',@{$candelete});
10440:         }
10441:     }
10442:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10443:              $umode.', '.$first.', '.$middle.', '.
10444: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10445:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10446:                                      ' desiredhome not specified'). 
10447:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10448:              ' in domain '.$env{'request.role.domain'});
10449:     my $uhome=&homeserver($uname,$udom,'true');
10450:     my $newuser;
10451:     if ($uhome eq 'no_host') {
10452:         $newuser = 1;
10453:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10454:                 ($umode eq 'lti')) {
10455:             return 'error: more information needed to create new user';
10456:         }
10457:     }
10458: # ----------------------------------------------------------------- Create User
10459:     if (($uhome eq 'no_host') && 
10460: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10461:         my $unhome='';
10462:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10463:             $unhome = $desiredhome;
10464: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10465: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10466:         } else { # load balancing routine for determining $unhome
10467:             my $loadm=10000000;
10468: 	    my %servers = &get_servers($udom,'library');
10469: 	    foreach my $tryserver (keys(%servers)) {
10470: 		my $answer=reply('load',$tryserver);
10471: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10472: 		    $loadm=$answer;
10473: 		    $unhome=$tryserver;
10474: 		}
10475: 	    }
10476:         }
10477:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10478: 	    return 'error: unable to find a home server for '.$uname.
10479:                    ' in domain '.$udom;
10480:         }
10481:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10482:                          &escape($upass),$unhome);
10483: 	unless ($reply eq 'ok') {
10484:             return 'error: '.$reply;
10485:         }   
10486:         $uhome=&homeserver($uname,$udom,'true');
10487:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10488: 	    return 'error: unable verify users home machine.';
10489:         }
10490:     }   # End of creation of new user
10491: # ---------------------------------------------------------------------- Add ID
10492:     if ($uid) {
10493:        $uid=~tr/A-Z/a-z/;
10494:        my %uidhash=&idrget($udom,$uname);
10495:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10496:          && (!$forceid)) {
10497: 	  unless ($uid eq $uidhash{$uname}) {
10498: 	      return 'error: user id "'.$uid.'" does not match '.
10499:                   'current user id "'.$uidhash{$uname}.'".';
10500:           }
10501:        } else {
10502: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
10503:        }
10504:     }
10505: # -------------------------------------------------------------- Add names, etc
10506:     my @tmp=&get('environment',
10507: 		   ['firstname','middlename','lastname','generation','id',
10508:                     'permanentemail','inststatus'],
10509: 		   $udom,$uname);
10510:     my (%names,%oldnames);
10511:     if ($tmp[0] =~ m/^error:.*/) { 
10512:         %names=(); 
10513:     } else {
10514:         %names = @tmp;
10515:         %oldnames = %names;
10516:     }
10517: #
10518: # If name, email and/or uid are blank (e.g., because an uploaded file
10519: # of users did not contain them), do not overwrite existing values
10520: # unless field is in $candelete array ref.  
10521: #
10522: 
10523:     my @fields = ('firstname','middlename','lastname','generation',
10524:                   'permanentemail','id');
10525:     my %newvalues;
10526:     if (ref($candelete) eq 'ARRAY') {
10527:         foreach my $field (@fields) {
10528:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10529:                 if ($field eq 'firstname') {
10530:                     $names{$field} = $first;
10531:                 } elsif ($field eq 'middlename') {
10532:                     $names{$field} = $middle;
10533:                 } elsif ($field eq 'lastname') {
10534:                     $names{$field} = $last;
10535:                 } elsif ($field eq 'generation') { 
10536:                     $names{$field} = $gene;
10537:                 } elsif ($field eq 'permanentemail') {
10538:                     $names{$field} = $email;
10539:                 } elsif ($field eq 'id') {
10540:                     $names{$field}  = $uid;
10541:                 }
10542:             }
10543:         }
10544:     }
10545:     if ($first)  { $names{'firstname'}  = $first; }
10546:     if (defined($middle)) { $names{'middlename'} = $middle; }
10547:     if ($last)   { $names{'lastname'}   = $last; }
10548:     if (defined($gene))   { $names{'generation'} = $gene; }
10549:     if ($email) {
10550:        $email=~s/[^\w\@\.\-\,]//gs;
10551:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10552:     }
10553:     if ($uid) { $names{'id'}  = $uid; }
10554:     if (defined($inststatus)) {
10555:         $names{'inststatus'} = '';
10556:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10557:         if (ref($usertypes) eq 'HASH') {
10558:             my @okstatuses; 
10559:             foreach my $item (split(/:/,$inststatus)) {
10560:                 if (defined($usertypes->{$item})) {
10561:                     push(@okstatuses,$item);  
10562:                 }
10563:             }
10564:             if (@okstatuses) {
10565:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10566:             }
10567:         }
10568:     }
10569:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10570:                  $umode.', '.$first.', '.$middle.', '.
10571:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10572:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10573:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10574:     } else {
10575:         $logmsg .= ' during self creation';
10576:     }
10577:     my $changed;
10578:     if ($newuser) {
10579:         $changed = 1;
10580:     } else {
10581:         foreach my $field (@fields) {
10582:             if ($names{$field} ne $oldnames{$field}) {
10583:                 $changed = 1;
10584:                 last;
10585:             }
10586:         }
10587:     }
10588:     unless ($changed) {
10589:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10590:         &logthis($logmsg);
10591:         return 'ok';
10592:     }
10593:     my $reply = &put('environment', \%names, $udom,$uname);
10594:     if ($reply ne 'ok') { 
10595:         return 'error: '.$reply;
10596:     }
10597:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10598:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10599:     }
10600:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10601:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10602:     $logmsg = 'Success modifying user '.$logmsg;
10603:     &logthis($logmsg);
10604:     return 'ok';
10605: }
10606: 
10607: # -------------------------------------------------------------- Modify student
10608: 
10609: sub modifystudent {
10610:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10611:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10612:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10613:     if (!$cid) {
10614: 	unless ($cid=$env{'request.course.id'}) {
10615: 	    return 'not_in_class';
10616: 	}
10617:     }
10618: # --------------------------------------------------------------- Make the user
10619:     my $reply=&modifyuser
10620: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10621:          $desiredhome,$email,$inststatus);
10622:     unless ($reply eq 'ok') { return $reply; }
10623:     # This will cause &modify_student_enrollment to get the uid from the
10624:     # student's environment
10625:     $uid = undef if (!$forceid);
10626:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10627:                                         $gene,$usec,$end,$start,$type,$locktype,
10628:                                         $cid,$selfenroll,$context,$credits,$instsec);
10629:     return $reply;
10630: }
10631: 
10632: sub modify_student_enrollment {
10633:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10634:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10635:     my ($cdom,$cnum,$chome);
10636:     if (!$cid) {
10637: 	unless ($cid=$env{'request.course.id'}) {
10638: 	    return 'not_in_class';
10639: 	}
10640: 	$cdom=$env{'course.'.$cid.'.domain'};
10641: 	$cnum=$env{'course.'.$cid.'.num'};
10642:     } else {
10643: 	($cdom,$cnum)=split(/_/,$cid);
10644:     }
10645:     $chome=$env{'course.'.$cid.'.home'};
10646:     if (!$chome) {
10647: 	$chome=&homeserver($cnum,$cdom);
10648:     }
10649:     if (!$chome) { return 'unknown_course'; }
10650:     # Make sure the user exists
10651:     my $uhome=&homeserver($uname,$udom);
10652:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10653: 	return 'error: no such user';
10654:     }
10655:     # Get student data if we were not given enough information
10656:     if (!defined($first)  || $first  eq '' || 
10657:         !defined($last)   || $last   eq '' || 
10658:         !defined($uid)    || $uid    eq '' || 
10659:         !defined($middle) || $middle eq '' || 
10660:         !defined($gene)   || $gene   eq '') {
10661:         # They did not supply us with enough data to enroll the student, so
10662:         # we need to pick up more information.
10663:         my %tmp = &get('environment',
10664:                        ['firstname','middlename','lastname', 'generation','id']
10665:                        ,$udom,$uname);
10666: 
10667:         #foreach my $key (keys(%tmp)) {
10668:         #    &logthis("key $key = ".$tmp{$key});
10669:         #}
10670:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10671:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10672:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10673:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10674:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10675:     }
10676:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10677:     my $user = "$uname:$udom";
10678:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10679:     my $reply=cput('classlist',
10680: 		   {$user => 
10681: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10682: 		   $cdom,$cnum);
10683:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10684:         &devalidate_getsection_cache($udom,$uname,$cid);
10685:     } else { 
10686: 	return 'error: '.$reply;
10687:     }
10688:     # Add student role to user
10689:     my $uurl='/'.$cid;
10690:     $uurl=~s/\_/\//g;
10691:     if ($usec) {
10692: 	$uurl.='/'.$usec;
10693:     }
10694:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10695:                              $selfenroll,$context);
10696:     if ($result ne 'ok') {
10697:         if ($old_entry{$user} ne '') {
10698:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10699:         } else {
10700:             $reply = &del('classlist',[$user],$cdom,$cnum);
10701:         }
10702:     }
10703:     return $result; 
10704: }
10705: 
10706: sub format_name {
10707:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10708:     my $name;
10709:     if ($first ne 'lastname') {
10710: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10711:     } else {
10712: 	if ($lastname=~/\S/) {
10713: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10714: 	    $name=~s/\s+,/,/;
10715: 	} else {
10716: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10717: 	}
10718:     }
10719:     $name=~s/^\s+//;
10720:     $name=~s/\s+$//;
10721:     $name=~s/\s+/ /g;
10722:     return $name;
10723: }
10724: 
10725: # ------------------------------------------------- Write to course preferences
10726: 
10727: sub writecoursepref {
10728:     my ($courseid,%prefs)=@_;
10729:     $courseid=~s/^\///;
10730:     $courseid=~s/\_/\//g;
10731:     my ($cdomain,$cnum)=split(/\//,$courseid);
10732:     my $chome=homeserver($cnum,$cdomain);
10733:     if (($chome eq '') || ($chome eq 'no_host')) { 
10734: 	return 'error: no such course';
10735:     }
10736:     my $cstring='';
10737:     foreach my $pref (keys(%prefs)) {
10738: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10739:     }
10740:     $cstring=~s/\&$//;
10741:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10742: }
10743: 
10744: # ---------------------------------------------------------- Make/modify course
10745: 
10746: sub createcourse {
10747:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10748:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
10749:     $url=&declutter($url);
10750:     my $cid='';
10751:     if ($context eq 'requestcourses') {
10752:         my $can_create = 0;
10753:         my ($ownername,$ownerdom) = split(':',$course_owner);
10754:         if ($udom eq $ownerdom) {
10755:             my $reload;
10756:             if (($callercontext eq 'auto') &&
10757:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10758:                 $reload = 'reload';
10759:             }
10760:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
10761:                                   $context)) {
10762:                 $can_create = 1;
10763:             }
10764:         } else {
10765:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10766:                                            $category);
10767:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10768:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10769:                 if (@curr > 0) {
10770:                     my @options = qw(approval validate autolimit);
10771:                     my $optregex = join('|',@options);
10772:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10773:                         $can_create = 1;
10774:                     }
10775:                 }
10776:             }
10777:         }
10778:         if ($can_create) {
10779:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10780:                 unless (&allowed('ccc',$udom)) {
10781:                     return 'refused'; 
10782:                 }
10783:             }
10784:         } else {
10785:             return 'refused';
10786:         }
10787:     } elsif (!&allowed('ccc',$udom)) {
10788:         return 'refused';
10789:     }
10790: # --------------------------------------------------------------- Get Unique ID
10791:     my $uname;
10792:     if ($cnum =~ /^$match_courseid$/) {
10793:         my $chome=&homeserver($cnum,$udom,'true');
10794:         if (($chome eq '') || ($chome eq 'no_host')) {
10795:             $uname = $cnum;
10796:         } else {
10797:             $uname = &generate_coursenum($udom,$crstype);
10798:         }
10799:     } else {
10800:         $uname = &generate_coursenum($udom,$crstype);
10801:     }
10802:     return $uname if ($uname =~ /^error/);
10803: # -------------------------------------------------- Check supplied server name
10804:     if (!defined($course_server)) {
10805:         if (defined(&domain($udom,'primary'))) {
10806:             $course_server = &domain($udom,'primary');
10807:         } else {
10808:             $course_server = $env{'user.home'}; 
10809:         }
10810:     }
10811:     my %host_servers =
10812:         &Apache::lonnet::get_servers($udom,'library');
10813:     unless ($host_servers{$course_server}) {
10814:         return 'error: invalid home server for course: '.$course_server;
10815:     }
10816: # ------------------------------------------------------------- Make the course
10817:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10818:                       $course_server);
10819:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10820:     my $uhome=&homeserver($uname,$udom,'true');
10821:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10822: 	return 'error: no such course';
10823:     }
10824: # ----------------------------------------------------------------- Course made
10825: # log existence
10826:     my $now = time;
10827:     my $newcourse = {
10828:                     $udom.'_'.$uname => {
10829:                                      description => $description,
10830:                                      inst_code   => $inst_code,
10831:                                      owner       => $course_owner,
10832:                                      type        => $crstype,
10833:                                      creator     => $env{'user.name'}.':'.
10834:                                                     $env{'user.domain'},
10835:                                      created     => $now,
10836:                                      context     => $context,
10837:                                                 },
10838:                     };
10839:     &courseidput($udom,$newcourse,$uhome,'notime');
10840: # set toplevel url
10841:     my $topurl=$url;
10842:     unless ($nonstandard) {
10843: # ------------------------------------------ For standard courses, make top url
10844:         my $mapurl=&clutter($url);
10845:         if ($mapurl eq '/res/') { $mapurl=''; }
10846:         $env{'form.initmap'}=(<<ENDINITMAP);
10847: <map>
10848: <resource id="1" type="start"></resource>
10849: <resource id="2" src="$mapurl"></resource>
10850: <resource id="3" type="finish"></resource>
10851: <link index="1" from="1" to="2"></link>
10852: <link index="2" from="2" to="3"></link>
10853: </map>
10854: ENDINITMAP
10855:         $topurl=&declutter(
10856:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10857:                           );
10858:     }
10859: # ----------------------------------------------------------- Write preferences
10860:     &writecoursepref($udom.'_'.$uname,
10861:                      ('description'              => $description,
10862:                       'url'                      => $topurl,
10863:                       'internal.creator'         => $env{'user.name'}.':'.
10864:                                                     $env{'user.domain'},
10865:                       'internal.created'         => $now,
10866:                       'internal.creationcontext' => $context)
10867:                     );
10868:     return '/'.$udom.'/'.$uname;
10869: }
10870: 
10871: # ------------------------------------------------------------------- Create ID
10872: sub generate_coursenum {
10873:     my ($udom,$crstype) = @_;
10874:     my $domdesc = &domain($udom);
10875:     return 'error: invalid domain' if ($domdesc eq '');
10876:     my $first;
10877:     if ($crstype eq 'Community') {
10878:         $first = '0';
10879:     } else {
10880:         $first = int(1+rand(9)); 
10881:     } 
10882:     my $uname=$first.
10883:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10884:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10885:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10886: # ----------------------------------------------- Make sure that does not exist
10887:     my $uhome=&homeserver($uname,$udom,'true');
10888:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10889:         if ($crstype eq 'Community') {
10890:             $first = '0';
10891:         } else {
10892:             $first = int(1+rand(9));
10893:         }
10894:         $uname=$first.
10895:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10896:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10897:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10898:         $uhome=&homeserver($uname,$udom,'true');
10899:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10900:             return 'error: unable to generate unique course-ID';
10901:         }
10902:     }
10903:     return $uname;
10904: }
10905: 
10906: sub is_course {
10907:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10908:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10909: 
10910:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10911:     my $uhome=&homeserver($cnum,$cdom);
10912:     my $iscourse;
10913:     if (grep { $_ eq $uhome } current_machine_ids()) {
10914:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10915:     } else {
10916:         my $hashid = $cdom.':'.$cnum;
10917:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10918:         unless (defined($cached)) {
10919:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10920:                                         $cnum,undef,undef,'.');
10921:             $iscourse = 0;
10922:             if (exists($courses{$cdom.'_'.$cnum})) {
10923:                 $iscourse = 1;
10924:             }
10925:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10926:         }
10927:     }
10928:     return unless ($iscourse);
10929:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10930: }
10931: 
10932: sub store_userdata {
10933:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10934:     my $result;
10935:     if ($datakey ne '') {
10936:         if (ref($storehash) eq 'HASH') {
10937:             if ($udom eq '' || $uname eq '') {
10938:                 $udom = $env{'user.domain'};
10939:                 $uname = $env{'user.name'};
10940:             }
10941:             my $uhome=&homeserver($uname,$udom);
10942:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10943:                 $result = 'error: no_host';
10944:             } else {
10945:                 $storehash->{'ip'} = &get_requestor_ip();
10946:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10947: 
10948:                 my $namevalue='';
10949:                 foreach my $key (keys(%{$storehash})) {
10950:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10951:                 }
10952:                 $namevalue=~s/\&$//;
10953:                 unless ($namespace eq 'courserequests') {
10954:                     $datakey = &escape($datakey);
10955:                 }
10956:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10957:                                   $namevalue,$uhome);
10958:             }
10959:         } else {
10960:             $result = 'error: data to store was not a hash reference'; 
10961:         }
10962:     } else {
10963:         $result= 'error: invalid requestkey'; 
10964:     }
10965:     return $result;
10966: }
10967: 
10968: # ---------------------------------------------------------- Assign Custom Role
10969: 
10970: sub assigncustomrole {
10971:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10972:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10973:                        $end,$start,$deleteflag,$selfenroll,$context);
10974: }
10975: 
10976: # ----------------------------------------------------------------- Revoke Role
10977: 
10978: sub revokerole {
10979:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10980:     my $now=time;
10981:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10982: }
10983: 
10984: # ---------------------------------------------------------- Revoke Custom Role
10985: 
10986: sub revokecustomrole {
10987:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10988:     my $now=time;
10989:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10990:            $deleteflag,$selfenroll,$context);
10991: }
10992: 
10993: # ------------------------------------------------------------ Disk usage
10994: sub diskusage {
10995:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10996:     $directorypath =~ s/\/$//;
10997:     my $listing=&reply('du2:'.&escape($directorypath).':'
10998:                        .&escape($getpropath).':'.&escape($uname).':'
10999:                        .&escape($udom),homeserver($uname,$udom));
11000:     if ($listing eq 'unknown_cmd') {
11001:         if ($getpropath) {
11002:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11003:         }
11004:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11005:     }
11006:     return $listing;
11007: }
11008: 
11009: sub is_locked {
11010:     my ($file_name, $domain, $user, $which) = @_;
11011:     my @check;
11012:     my $is_locked;
11013:     push (@check,$file_name);
11014:     my %locked = &get('file_permissions',\@check,
11015: 		      $env{'user.domain'},$env{'user.name'});
11016:     my ($tmp)=keys(%locked);
11017:     if ($tmp=~/^error:/) { undef(%locked); }
11018:     
11019:     if (ref($locked{$file_name}) eq 'ARRAY') {
11020:         $is_locked = 'false';
11021:         foreach my $entry (@{$locked{$file_name}}) {
11022:            if (ref($entry) eq 'ARRAY') {
11023:                $is_locked = 'true';
11024:                if (ref($which) eq 'ARRAY') {
11025:                    push(@{$which},$entry);
11026:                } else {
11027:                    last;
11028:                }
11029:            }
11030:        }
11031:     } else {
11032:         $is_locked = 'false';
11033:     }
11034:     return $is_locked;
11035: }
11036: 
11037: sub declutter_portfile {
11038:     my ($file) = @_;
11039:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11040:     return $file;
11041: }
11042: 
11043: # ------------------------------------------------------------- Mark as Read Only
11044: 
11045: sub mark_as_readonly {
11046:     my ($domain,$user,$files,$what) = @_;
11047:     my %current_permissions = &dump('file_permissions',$domain,$user);
11048:     my ($tmp)=keys(%current_permissions);
11049:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11050:     foreach my $file (@{$files}) {
11051: 	$file = &declutter_portfile($file);
11052:         push(@{$current_permissions{$file}},$what);
11053:     }
11054:     &put('file_permissions',\%current_permissions,$domain,$user);
11055:     return;
11056: }
11057: 
11058: # ------------------------------------------------------------Save Selected Files
11059: 
11060: sub save_selected_files {
11061:     my ($user, $path, @files) = @_;
11062:     my $filename = $user."savedfiles";
11063:     my @other_files = &files_not_in_path($user, $path);
11064:     open (OUT,'>',LONCAPA::tempdir().$filename);
11065:     foreach my $file (@files) {
11066:         print (OUT $env{'form.currentpath'}.$file."\n");
11067:     }
11068:     foreach my $file (@other_files) {
11069:         print (OUT $file."\n");
11070:     }
11071:     close (OUT);
11072:     return 'ok';
11073: }
11074: 
11075: sub clear_selected_files {
11076:     my ($user) = @_;
11077:     my $filename = $user."savedfiles";
11078:     open (OUT,'>',LONCAPA::tempdir().$filename);
11079:     print (OUT undef);
11080:     close (OUT);
11081:     return ("ok");    
11082: }
11083: 
11084: sub files_in_path {
11085:     my ($user, $path) = @_;
11086:     my $filename = $user."savedfiles";
11087:     my %return_files;
11088:     open (IN,'<',LONCAPA::tempdir().$filename);
11089:     while (my $line_in = <IN>) {
11090:         chomp ($line_in);
11091:         my @paths_and_file = split (m!/!, $line_in);
11092:         my $file_part = pop (@paths_and_file);
11093:         my $path_part = join ('/', @paths_and_file);
11094:         $path_part.='/';
11095:         my $path_and_file = $path_part.$file_part;
11096:         if ($path_part eq $path) {
11097:             $return_files{$file_part}= 'selected';
11098:         }
11099:     }
11100:     close (IN);
11101:     return (\%return_files);
11102: }
11103: 
11104: # called in portfolio select mode, to show files selected NOT in current directory
11105: sub files_not_in_path {
11106:     my ($user, $path) = @_;
11107:     my $filename = $user."savedfiles";
11108:     my @return_files;
11109:     my $path_part;
11110:     open(IN, '<',LONCAPA::tempdir().$filename);
11111:     while (my $line = <IN>) {
11112:         #ok, I know it's clunky, but I want it to work
11113:         my @paths_and_file = split(m|/|, $line);
11114:         my $file_part = pop(@paths_and_file);
11115:         chomp($file_part);
11116:         my $path_part = join('/', @paths_and_file);
11117:         $path_part .= '/';
11118:         my $path_and_file = $path_part.$file_part;
11119:         if ($path_part ne $path) {
11120:             push(@return_files, ($path_and_file));
11121:         }
11122:     }
11123:     close(OUT);
11124:     return (@return_files);
11125: }
11126: 
11127: #------------------------------Submitted/Handedback Portfolio Files Versioning
11128:  
11129: sub portfiles_versioning {
11130:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11131:     my $portfolio_root = '/userfiles/portfolio';
11132:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11133:     foreach my $file (@{$portfiles}) {
11134:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11135:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11136:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11137:         my $getpropath = 1;
11138:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11139:                                              $stu_name,$getpropath);
11140:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11141:         my $new_answer = 
11142:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11143:         if ($new_answer ne 'problem getting file') {
11144:             push(@{$versioned_portfiles}, $directory.$new_answer);
11145:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11146:                               [$symb,$env{'request.course.id'},'graded']);
11147:         }
11148:     }
11149: }
11150: 
11151: sub get_next_version {
11152:     my ($answer_name, $answer_ext, $dir_list) = @_;
11153:     my $version;
11154:     if (ref($dir_list) eq 'ARRAY') {
11155:         foreach my $row (@{$dir_list}) {
11156:             my ($file) = split(/\&/,$row,2);
11157:             my ($file_name,$file_version,$file_ext) =
11158:                 &file_name_version_ext($file);
11159:             if (($file_name eq $answer_name) &&
11160:                 ($file_ext eq $answer_ext)) {
11161:                      # gets here if filename and extension match,
11162:                      # regardless of version
11163:                 if ($file_version ne '') {
11164:                     # a versioned file is found  so save it for later
11165:                     if ($file_version > $version) {
11166:                         $version = $file_version;
11167:                     }
11168:                 }
11169:             }
11170:         }
11171:     }
11172:     $version ++;
11173:     return($version);
11174: }
11175: 
11176: sub version_selected_portfile {
11177:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11178:     my ($answer_name,$answer_ver,$answer_ext) =
11179:         &file_name_version_ext($file_name);
11180:     my $new_answer;
11181:     $env{'form.copy'} =
11182:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11183:     if($env{'form.copy'} eq '-1') {
11184:         $new_answer = 'problem getting file';
11185:     } else {
11186:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11187:         my $copy_result = 
11188:             &finishuserfileupload($stu_name,$domain,'copy',
11189:                                   '/portfolio'.$directory.$new_answer);
11190:     }
11191:     undef($env{'form.copy'});
11192:     return ($new_answer);
11193: }
11194: 
11195: sub file_name_version_ext {
11196:     my ($file)=@_;
11197:     my @file_parts = split(/\./, $file);
11198:     my ($name,$version,$ext);
11199:     if (@file_parts > 1) {
11200:         $ext=pop(@file_parts);
11201:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11202:             $version=pop(@file_parts);
11203:         }
11204:         $name=join('.',@file_parts);
11205:     } else {
11206:         $name=join('.',@file_parts);
11207:     }
11208:     return($name,$version,$ext);
11209: }
11210: 
11211: #----------------------------------------------Get portfolio file permissions
11212: 
11213: sub get_portfile_permissions {
11214:     my ($domain,$user) = @_;
11215:     my %current_permissions = &dump('file_permissions',$domain,$user);
11216:     my ($tmp)=keys(%current_permissions);
11217:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11218:     return \%current_permissions;
11219: }
11220: 
11221: #---------------------------------------------Get portfolio file access controls
11222: 
11223: sub get_access_controls {
11224:     my ($current_permissions,$group,$file) = @_;
11225:     my %access;
11226:     my $real_file = $file;
11227:     $file =~ s/\.meta$//;
11228:     if (defined($file)) {
11229:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11230:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11231:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11232:             }
11233:         }
11234:     } else {
11235:         foreach my $key (keys(%{$current_permissions})) {
11236:             if ($key =~ /\0accesscontrol$/) {
11237:                 if (defined($group)) {
11238:                     if ($key !~ m-^\Q$group\E/-) {
11239:                         next;
11240:                     }
11241:                 }
11242:                 my ($fullpath) = split(/\0/,$key);
11243:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11244:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11245:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11246:                     }
11247:                 }
11248:             }
11249:         }
11250:     }
11251:     return %access;
11252: }
11253: 
11254: sub modify_access_controls {
11255:     my ($file_name,$changes,$domain,$user)=@_;
11256:     my ($outcome,$deloutcome);
11257:     my %store_permissions;
11258:     my %new_values;
11259:     my %new_control;
11260:     my %translation;
11261:     my @deletions = ();
11262:     my $now = time;
11263:     if (exists($$changes{'activate'})) {
11264:         if (ref($$changes{'activate'}) eq 'HASH') {
11265:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11266:             my $numnew = scalar(@newitems);
11267:             for (my $i=0; $i<$numnew; $i++) {
11268:                 my $newkey = $newitems[$i];
11269:                 my $newid = &Apache::loncommon::get_cgi_id();
11270:                 if ($newkey =~ /^\d+:/) { 
11271:                     $newkey =~ s/^(\d+)/$newid/;
11272:                     $translation{$1} = $newid;
11273:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11274:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11275:                     $translation{$1} = $newid;
11276:                 }
11277:                 $new_values{$file_name."\0".$newkey} = 
11278:                                           $$changes{'activate'}{$newitems[$i]};
11279:                 $new_control{$newkey} = $now;
11280:             }
11281:         }
11282:     }
11283:     my %todelete;
11284:     my %changed_items;
11285:     foreach my $action ('delete','update') {
11286:         if (exists($$changes{$action})) {
11287:             if (ref($$changes{$action}) eq 'HASH') {
11288:                 foreach my $key (keys(%{$$changes{$action}})) {
11289:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11290:                     if ($action eq 'delete') { 
11291:                         $todelete{$itemnum} = 1;
11292:                     } else {
11293:                         $changed_items{$itemnum} = $key;
11294:                     }
11295:                 }
11296:             }
11297:         }
11298:     }
11299:     # get lock on access controls for file.
11300:     my $lockhash = {
11301:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11302:                                                        ':'.$env{'user.domain'},
11303:                    }; 
11304:     my $tries = 0;
11305:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11306:    
11307:     while (($gotlock ne 'ok') && $tries < 10) {
11308:         $tries ++;
11309:         sleep(0.1);
11310:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11311:     }
11312:     if ($gotlock eq 'ok') {
11313:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11314:         my ($tmp)=keys(%curr_permissions);
11315:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11316:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11317:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11318:             if (ref($curr_controls) eq 'HASH') {
11319:                 foreach my $control_item (keys(%{$curr_controls})) {
11320:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11321:                     if (defined($todelete{$itemnum})) {
11322:                         push(@deletions,$file_name."\0".$control_item);
11323:                     } else {
11324:                         if (defined($changed_items{$itemnum})) {
11325:                             $new_control{$changed_items{$itemnum}} = $now;
11326:                             push(@deletions,$file_name."\0".$control_item);
11327:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11328:                         } else {
11329:                             $new_control{$control_item} = $$curr_controls{$control_item};
11330:                         }
11331:                     }
11332:                 }
11333:             }
11334:         }
11335:         my ($group);
11336:         if (&is_course($domain,$user)) {
11337:             ($group,my $file) = split(/\//,$file_name,2);
11338:         }
11339:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11340:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11341:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11342:         #  remove lock
11343:         my @del_lock = ($file_name."\0".'locked_access_records');
11344:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11345:         my $sqlresult =
11346:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11347:                                     $group);
11348:     } else {
11349:         $outcome = "error: could not obtain lockfile\n";  
11350:     }
11351:     return ($outcome,$deloutcome,\%new_values,\%translation);
11352: }
11353: 
11354: sub make_public_indefinitely {
11355:     my (@requrl) = @_;
11356:     return &automated_portfile_access('public',\@requrl);
11357: }
11358: 
11359: sub automated_portfile_access {
11360:     my ($accesstype,$addsref,$delsref,$info) = @_;
11361:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11362:         return 'invalid';
11363:     }
11364:     my %urls;
11365:     if (ref($addsref) eq 'ARRAY') {
11366:         foreach my $requrl (@{$addsref}) {
11367:             if (&is_portfolio_url($requrl)) {
11368:                 unless (exists($urls{$requrl})) {
11369:                     $urls{$requrl} = 'add';
11370:                 }
11371:             }
11372:         }
11373:     }
11374:     if (ref($delsref) eq 'ARRAY') {
11375:         foreach my $requrl (@{$delsref}) { 
11376:             if (&is_portfolio_url($requrl)) {
11377:                 unless (exists($urls{$requrl})) {
11378:                     $urls{$requrl} = 'delete'; 
11379:                 }
11380:             }
11381:         }
11382:     }
11383:     unless (keys(%urls)) {
11384:         return 'invalid';
11385:     }
11386:     my $ip;
11387:     if ($accesstype eq 'ip') {
11388:         if (ref($info) eq 'HASH') {
11389:             if ($info->{'ip'} ne '') {
11390:                 $ip = $info->{'ip'};
11391:             }
11392:         }
11393:         if ($ip eq '') {
11394:             return 'invalid';
11395:         }
11396:     }
11397:     my $errors;
11398:     my $now = time;
11399:     my %current_perms;
11400:     foreach my $requrl (sort(keys(%urls))) {
11401:         my $action;
11402:         if ($urls{$requrl} eq 'add') {
11403:             $action = 'activate';
11404:         } else {
11405:             $action = 'none';
11406:         }
11407:         my $aclnum = 0;
11408:         my (undef,$udom,$unum,$file_name,$group) =
11409:             &parse_portfolio_url($requrl);
11410:         unless (exists($current_perms{$unum.':'.$udom})) {
11411:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11412:         }
11413:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11414:                                                    $group,$file_name);
11415:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11416:             my ($num,$scope,$end,$start) = 
11417:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11418:             if ($scope eq $accesstype) {
11419:                 if (($start <= $now) && ($end == 0)) {
11420:                     if ($accesstype eq 'ip') {
11421:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11422:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11423:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11424:                                     if ($urls{$requrl} eq 'add') {
11425:                                         $action = 'none';
11426:                                         last;
11427:                                     } else {
11428:                                         $action = 'delete';
11429:                                         $aclnum = $num;
11430:                                         last;
11431:                                     }
11432:                                 }
11433:                             }
11434:                         }
11435:                     } elsif ($accesstype eq 'public') {
11436:                         if ($urls{$requrl} eq 'add') {
11437:                             $action = 'none';
11438:                             last;
11439:                         } else {
11440:                             $action = 'delete';
11441:                             $aclnum = $num;
11442:                             last;
11443:                         }
11444:                     }
11445:                 } elsif ($accesstype eq 'public') {
11446:                     $action = 'update';
11447:                     $aclnum = $num;
11448:                     last;
11449:                 }
11450:             }
11451:         }
11452:         if ($action eq 'none') {
11453:             next;
11454:         } else {
11455:             my %changes;
11456:             my $newend = 0;
11457:             my $newstart = $now;
11458:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11459:             $changes{$action}{$newkey} = {
11460:                 type => $accesstype,
11461:                 time => {
11462:                     start => $newstart,
11463:                     end   => $newend,
11464:                 },
11465:             };
11466:             if ($accesstype eq 'ip') {
11467:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11468:             }
11469:             my ($outcome,$deloutcome,$new_values,$translation) =
11470:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11471:             unless ($outcome eq 'ok') {
11472:                 $errors .= $outcome.' ';
11473:             }
11474:         }
11475:     }
11476:     if ($errors) {
11477:         $errors =~ s/\s$//;
11478:         return $errors;
11479:     } else {
11480:         return 'ok';
11481:     }
11482: }
11483: 
11484: #------------------------------------------------------Get Marked as Read Only
11485: 
11486: sub get_marked_as_readonly {
11487:     my ($domain,$user,$what,$group) = @_;
11488:     my $current_permissions = &get_portfile_permissions($domain,$user);
11489:     my @readonly_files;
11490:     my $cmp1=$what;
11491:     if (ref($what)) { $cmp1=join('',@{$what}) };
11492:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11493:         if (defined($group)) {
11494:             if ($file_name !~ m-^\Q$group\E/-) {
11495:                 next;
11496:             }
11497:         }
11498:         if (ref($value) eq "ARRAY"){
11499:             foreach my $stored_what (@{$value}) {
11500:                 my $cmp2=$stored_what;
11501:                 if (ref($stored_what) eq 'ARRAY') {
11502:                     $cmp2=join('',@{$stored_what});
11503:                 }
11504:                 if ($cmp1 eq $cmp2) {
11505:                     push(@readonly_files, $file_name);
11506:                     last;
11507:                 } elsif (!defined($what)) {
11508:                     push(@readonly_files, $file_name);
11509:                     last;
11510:                 }
11511:             }
11512:         }
11513:     }
11514:     return @readonly_files;
11515: }
11516: #-----------------------------------------------------------Get Marked as Read Only Hash
11517: 
11518: sub get_marked_as_readonly_hash {
11519:     my ($current_permissions,$group,$what) = @_;
11520:     my %readonly_files;
11521:     while (my ($file_name,$value) = each(%{$current_permissions})) {
11522:         if (defined($group)) {
11523:             if ($file_name !~ m-^\Q$group\E/-) {
11524:                 next;
11525:             }
11526:         }
11527:         if (ref($value) eq "ARRAY"){
11528:             foreach my $stored_what (@{$value}) {
11529:                 if (ref($stored_what) eq 'ARRAY') {
11530:                     foreach my $lock_descriptor(@{$stored_what}) {
11531:                         if ($lock_descriptor eq 'graded') {
11532:                             $readonly_files{$file_name} = 'graded';
11533:                         } elsif ($lock_descriptor eq 'handback') {
11534:                             $readonly_files{$file_name} = 'handback';
11535:                         } else {
11536:                             if (!exists($readonly_files{$file_name})) {
11537:                                 $readonly_files{$file_name} = 'locked';
11538:                             }
11539:                         }
11540:                     }
11541:                 } 
11542:             }
11543:         } 
11544:     }
11545:     return %readonly_files;
11546: }
11547: # ------------------------------------------------------------ Unmark as Read Only
11548: 
11549: sub unmark_as_readonly {
11550:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
11551:     # for portfolio submissions, $what contains [$symb,$crsid] 
11552:     my ($domain,$user,$what,$file_name,$group) = @_;
11553:     $file_name = &declutter_portfile($file_name);
11554:     my $symb_crs = $what;
11555:     if (ref($what)) { $symb_crs=join('',@$what); }
11556:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
11557:     my ($tmp)=keys(%current_permissions);
11558:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11559:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
11560:     foreach my $file (@readonly_files) {
11561: 	my $clean_file = &declutter_portfile($file);
11562: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
11563: 	my $current_locks = $current_permissions{$file};
11564:         my @new_locks;
11565:         my @del_keys;
11566:         if (ref($current_locks) eq "ARRAY"){
11567:             foreach my $locker (@{$current_locks}) {
11568:                 my $compare=$locker;
11569:                 if (ref($locker) eq 'ARRAY') {
11570:                     $compare=join('',@{$locker});
11571:                     if ($compare ne $symb_crs) {
11572:                         push(@new_locks, $locker);
11573:                     }
11574:                 }
11575:             }
11576:             if (scalar(@new_locks) > 0) {
11577:                 $current_permissions{$file} = \@new_locks;
11578:             } else {
11579:                 push(@del_keys, $file);
11580:                 &del('file_permissions',\@del_keys, $domain, $user);
11581:                 delete($current_permissions{$file});
11582:             }
11583:         }
11584:     }
11585:     &put('file_permissions',\%current_permissions,$domain,$user);
11586:     return;
11587: }
11588: 
11589: # ------------------------------------------------------------ Directory lister
11590: 
11591: sub dirlist {
11592:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
11593:     $uri=~s/^\///;
11594:     $uri=~s/\/$//;
11595:     my ($udom, $uname);
11596:     if ($getuserdir) {
11597:         $udom = $userdomain;
11598:         $uname = $username;
11599:     } else {
11600:         (undef,$udom,$uname)=split(/\//,$uri);
11601:         if(defined($userdomain)) {
11602:             $udom = $userdomain;
11603:         }
11604:         if(defined($username)) {
11605:             $uname = $username;
11606:         }
11607:     }
11608:     my ($dirRoot,$listing,@listing_results);
11609: 
11610:     $dirRoot = $perlvar{'lonDocRoot'};
11611:     if (defined($getpropath)) {
11612:         $dirRoot = &propath($udom,$uname);
11613:         $dirRoot =~ s/\/$//;
11614:     } elsif (defined($getuserdir)) {
11615:         my $subdir=$uname.'__';
11616:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11617:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11618:                    ."/$udom/$subdir/$uname";
11619:     } elsif (defined($alternateRoot)) {
11620:         $dirRoot = $alternateRoot;
11621:     }
11622: 
11623:     if($udom) {
11624:         if($uname) {
11625:             my $uhome = &homeserver($uname,$udom);
11626:             if ($uhome eq 'no_host') {
11627:                 return ([],'no_host');
11628:             }
11629:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11630:                               .$getuserdir.':'.&escape($dirRoot)
11631:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11632:             if ($listing eq 'unknown_cmd') {
11633:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11634:             } else {
11635:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11636:             }
11637:             if ($listing eq 'unknown_cmd') {
11638:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11639:                 @listing_results = split(/:/,$listing);
11640:             } else {
11641:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11642:             }
11643:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11644:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11645:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11646:                 return ([],$listing);
11647:             } else {
11648:                 return (\@listing_results);
11649:             }
11650:         } elsif(!$alternateRoot) {
11651:             my (%allusers,%listerror);
11652: 	    my %servers = &get_servers($udom,'library');
11653:  	    foreach my $tryserver (keys(%servers)) {
11654:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11655:                                   &escape($udom),$tryserver);
11656:                 if ($listing eq 'unknown_cmd') {
11657: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11658: 				      $udom, $tryserver);
11659:                 } else {
11660:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11661:                 }
11662: 		if ($listing eq 'unknown_cmd') {
11663: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11664: 				      $udom, $tryserver);
11665: 		    @listing_results = split(/:/,$listing);
11666: 		} else {
11667: 		    @listing_results =
11668: 			map { &unescape($_); } split(/:/,$listing);
11669: 		}
11670:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11671:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11672:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11673:                     $listerror{$tryserver} = $listing;
11674:                 } else {
11675: 		    foreach my $line (@listing_results) {
11676: 			my ($entry) = split(/&/,$line,2);
11677: 			$allusers{$entry} = 1;
11678: 		    }
11679: 		}
11680:             }
11681:             my @alluserslist=();
11682:             foreach my $user (sort(keys(%allusers))) {
11683:                 push(@alluserslist,$user.'&user');
11684:             }
11685: 
11686:             if (!%listerror) {
11687:                 # no errors
11688:                 return (\@alluserslist);
11689:             } elsif (scalar(keys(%servers)) == 1) {
11690:                 # one library server, one error 
11691:                 my ($key) = keys(%listerror);
11692:                 return (\@alluserslist, $listerror{$key});
11693:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11694:                 # con_lost indicates that we might miss data from at least one
11695:                 # library server
11696:                 return (\@alluserslist, 'con_lost');
11697:             } else {
11698:                 # multiple library servers and no con_lost -> data should be
11699:                 # complete. 
11700:                 return (\@alluserslist);
11701:             }
11702: 
11703:         } else {
11704:             return ([],'missing username');
11705:         }
11706:     } elsif(!defined($getpropath)) {
11707:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11708:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11709:         return (\@all_domains);
11710:     } else {
11711:         return ([],'missing domain');
11712:     }
11713: }
11714: 
11715: # --------------------------------------------- GetFileTimestamp
11716: # This function utilizes dirlist and returns the date stamp for
11717: # when it was last modified.  It will also return an error of -1
11718: # if an error occurs
11719: 
11720: sub GetFileTimestamp {
11721:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11722:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11723:     $studentName   = &LONCAPA::clean_username($studentName);
11724:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11725:                                     undef,$getuserdir);
11726:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11727:         return -1;
11728:     }
11729:     if (ref($fileref) eq 'ARRAY') {
11730:         my @stats = split('&',$fileref->[0]);
11731:         # @stats contains first the filename, then the stat output
11732:         return $stats[10]; # so this is 10 instead of 9.
11733:     } else {
11734:         return -1;
11735:     }
11736: }
11737: 
11738: sub stat_file {
11739:     my ($uri) = @_;
11740:     $uri = &clutter_with_no_wrapper($uri);
11741: 
11742:     my ($udom,$uname,$file);
11743:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11744: 	($udom,$uname,$file) =
11745: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11746: 	$file = 'userfiles/'.$file;
11747:     }
11748:     if ($uri =~ m-^/res/-) {
11749: 	($udom,$uname) = 
11750: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11751: 	$file = $uri;
11752:     }
11753: 
11754:     if (!$udom || !$uname || !$file) {
11755: 	# unable to handle the uri
11756: 	return ();
11757:     }
11758:     my $getpropath;
11759:     if ($file =~ /^userfiles\//) {
11760:         $getpropath = 1;
11761:     }
11762:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11763:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11764:         return ();
11765:     } else {
11766:         if (ref($listref) eq 'ARRAY') {
11767:             my @stats = split('&',$listref->[0]);
11768: 	    shift(@stats); #filename is first
11769: 	    return @stats;
11770:         }
11771:     }
11772:     return ();
11773: }
11774: 
11775: # --------------------------------------------------------- recursedirs
11776: # Recursive function to traverse either a specific user's Authoring Space
11777: # or corresponding Published Resource Space, and populate the hash ref:
11778: # $dirhashref with URLs of all directories, and if $filehashref hash
11779: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11780: # or .rights files in resource space, and .meta, .save, .log, and .bak
11781: # files in Authoring Space.
11782: #
11783: # Inputs:
11784: #
11785: # $is_home - true if current server is home server for user's space
11786: # $context - either: priv, or res respectively for Authoring or Resource Space.
11787: # $docroot - Document root (i.e., /home/httpd/html
11788: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11789: # $relpath - Current path (relative to top level).
11790: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11791: # $filehashref - reference to hash to populate with URLs of files (Optional)
11792: #
11793: # Returns: nothing
11794: #
11795: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11796: #
11797: # Currently used by interface/londocs.pm to create linked select boxes for
11798: # directory and filename to import a Course "Author" resource into a course, and
11799: # also to create linked select boxes for Authoring Space and Directory to choose
11800: # save location for creation of a new "standard" problem from the Course Editor.
11801: #
11802: 
11803: sub recursedirs {
11804:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11805:     return unless (ref($dirhashref) eq 'HASH');
11806:     my $currpath = $docroot.$toppath;
11807:     if ($relpath) {
11808:         $currpath .= "/$relpath";
11809:     }
11810:     my $savefile;
11811:     if (ref($filehashref)) {
11812:         $savefile = 1;
11813:     }
11814:     if ($is_home) {
11815:         if (opendir(my $dirh,$currpath)) {
11816:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11817:                 next if ($item eq '');
11818:                 if (-d "$currpath/$item") {
11819:                     my $newpath;
11820:                     if ($relpath) {
11821:                         $newpath = "$relpath/$item";
11822:                     } else {
11823:                         $newpath = $item;
11824:                     }
11825:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11826:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11827:                 } elsif ($savefile) {
11828:                     if ($context eq 'priv') {
11829:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11830:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11831:                         }
11832:                     } else {
11833:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11834:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11835:                         }
11836:                     }
11837:                 }
11838:             }
11839:             closedir($dirh);
11840:         }
11841:     } else {
11842:         my ($dirlistref,$listerror) =
11843:             &dirlist($toppath.$relpath);
11844:         my @dir_lines;
11845:         my $dirptr=16384;
11846:         if (ref($dirlistref) eq 'ARRAY') {
11847:             foreach my $dir_line (sort
11848:                               {
11849:                                   my ($afile)=split('&',$a,2);
11850:                                   my ($bfile)=split('&',$b,2);
11851:                                   return (lc($afile) cmp lc($bfile));
11852:                               } (@{$dirlistref})) {
11853:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11854:                     split(/\&/,$dir_line,16);
11855:                 $item =~ s/\s+$//;
11856:                 next if (($item =~ /^\.\.?$/) || ($obs));
11857:                 if ($dirptr&$testdir) {
11858:                     my $newpath;
11859:                     if ($relpath) {
11860:                         $newpath = "$relpath/$item";
11861:                     } else {
11862:                         $relpath = '/';
11863:                         $newpath = $item;
11864:                     }
11865:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11866:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11867:                 } elsif ($savefile) {
11868:                     if ($context eq 'priv') {
11869:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11870:                             $filehashref->{$relpath}{$item} = 1;
11871:                         }
11872:                     } else {
11873:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11874:                             $filehashref->{$relpath}{$item} = 1;
11875:                         }
11876:                     }
11877:                 }
11878:             }
11879:         }
11880:     }
11881:     return;
11882: }
11883: 
11884: # -------------------------------------------------------- Value of a Condition
11885: 
11886: # gets the value of a specific preevaluated condition
11887: #    stored in the string  $env{user.state.<cid>}
11888: # or looks up a condition reference in the bighash and if if hasn't
11889: # already been evaluated recurses into docondval to get the value of
11890: # the condition, then memoizing it to 
11891: #   $env{user.state.<cid>.<condition>}
11892: sub directcondval {
11893:     my $number=shift;
11894:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11895: 	&Apache::lonuserstate::evalstate();
11896:     }
11897:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11898: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11899:     } elsif ($number =~ /^_/) {
11900: 	my $sub_condition;
11901: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11902: 		&GDBM_READER(),0640)) {
11903: 	    $sub_condition=$bighash{'conditions'.$number};
11904: 	    untie(%bighash);
11905: 	}
11906: 	my $value = &docondval($sub_condition);
11907: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11908: 	return $value;
11909:     }
11910:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11911:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11912:     } else {
11913:        return 2;
11914:     }
11915: }
11916: 
11917: # get the collection of conditions for this resource
11918: sub condval {
11919:     my $condidx=shift;
11920:     my $allpathcond='';
11921:     foreach my $cond (split(/\|/,$condidx)) {
11922: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11923: 	    $allpathcond.=
11924: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11925: 	}
11926:     }
11927:     $allpathcond=~s/\|$//;
11928:     return &docondval($allpathcond);
11929: }
11930: 
11931: #evaluates an expression of conditions
11932: sub docondval {
11933:     my ($allpathcond) = @_;
11934:     my $result=0;
11935:     if ($env{'request.course.id'}
11936: 	&& defined($allpathcond)) {
11937: 	my $operand='|';
11938: 	my @stack;
11939: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11940: 	    if ($chunk eq '(') {
11941: 		push @stack,($operand,$result);
11942: 	    } elsif ($chunk eq ')') {
11943: 		my $before=pop @stack;
11944: 		if (pop @stack eq '&') {
11945: 		    $result=$result>$before?$before:$result;
11946: 		} else {
11947: 		    $result=$result>$before?$result:$before;
11948: 		}
11949: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11950: 		$operand=$chunk;
11951: 	    } else {
11952: 		my $new=directcondval($chunk);
11953: 		if ($operand eq '&') {
11954: 		    $result=$result>$new?$new:$result;
11955: 		} else {
11956: 		    $result=$result>$new?$result:$new;
11957: 		}
11958: 	    }
11959: 	}
11960:     }
11961:     return $result;
11962: }
11963: 
11964: # ---------------------------------------------------- Devalidate courseresdata
11965: 
11966: sub devalidatecourseresdata {
11967:     my ($coursenum,$coursedomain)=@_;
11968:     my $hashid=$coursenum.':'.$coursedomain;
11969:     &devalidate_cache_new('courseres',$hashid);
11970: }
11971: 
11972: 
11973: # --------------------------------------------------- Course Resourcedata Query
11974: #
11975: #  Parameters:
11976: #      $coursenum    - Number of the course.
11977: #      $coursedomain - Domain at which the course was created.
11978: #  Returns:
11979: #     A hash of the course parameters along (I think) with timestamps
11980: #     and version info.
11981: 
11982: sub get_courseresdata {
11983:     my ($coursenum,$coursedomain)=@_;
11984:     my $coursehom=&homeserver($coursenum,$coursedomain);
11985:     my $hashid=$coursenum.':'.$coursedomain;
11986:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11987:     my %dumpreply;
11988:     unless (defined($cached)) {
11989: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11990: 	$result=\%dumpreply;
11991: 	my ($tmp) = keys(%dumpreply);
11992: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11993: 	    &do_cache_new('courseres',$hashid,$result,600);
11994: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11995: 	    return $tmp;
11996: 	} elsif ($tmp =~ /^(error)/) {
11997: 	    $result=undef;
11998: 	    &do_cache_new('courseres',$hashid,$result,600);
11999: 	}
12000:     }
12001:     return $result;
12002: }
12003: 
12004: sub devalidateuserresdata {
12005:     my ($uname,$udom)=@_;
12006:     my $hashid="$udom:$uname";
12007:     &devalidate_cache_new('userres',$hashid);
12008: }
12009: 
12010: sub get_userresdata {
12011:     my ($uname,$udom)=@_;
12012:     #most student don\'t have any data set, check if there is some data
12013:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12014: 
12015:     my $hashid="$udom:$uname";
12016:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12017:     if (!defined($cached)) {
12018: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12019: 	$result=\%resourcedata;
12020: 	&do_cache_new('userres',$hashid,$result,600);
12021:     }
12022:     my ($tmp)=keys(%$result);
12023:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12024: 	return $result;
12025:     }
12026:     #error 2 occurs when the .db doesn't exist
12027:     if ($tmp!~/error: 2 /) {
12028:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12029: 	    &logthis("<font color=\"blue\">WARNING:".
12030: 		     " Trying to get resource data for ".
12031: 		     $uname." at ".$udom.": ".
12032: 		     $tmp."</font>");
12033:         }
12034:     } elsif ($tmp=~/error: 2 /) {
12035: 	#&EXT_cache_set($udom,$uname);
12036: 	&do_cache_new('userres',$hashid,undef,600);
12037: 	undef($tmp); # not really an error so don't send it back
12038:     }
12039:     return $tmp;
12040: }
12041: #----------------------------------------------- resdata - return resource data
12042: #  Purpose:
12043: #    Return resource data for either users or for a course.
12044: #  Parameters:
12045: #     $name      - Course/user name.
12046: #     $domain    - Name of the domain the user/course is registered on.
12047: #     $type      - Type of thing $name is (must be 'course' or 'user')
12048: #     $mapp      - decluttered URL of enclosing map  
12049: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12050: #     $recurseup - Ref to array of map URLs, starting with map containing
12051: #                  $mapp up through hierarchy of nested maps to top level map.  
12052: #     $courseid  - CourseID (first part of param identifier).
12053: #     $modifier  - Middle part of param identifier.
12054: #     $what      - Last part of param identifier.
12055: #     @which     - Array of names of resources desired.
12056: #  Returns:
12057: #     The value of the first reasource in @which that is found in the
12058: #     resource hash.
12059: #  Exceptional Conditions:
12060: #     If the $type passed in is not valid (not the string 'course' or 
12061: #     'user', an undefined  reference is returned.
12062: #     If none of the resources are found, an undef is returned
12063: sub resdata {
12064:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12065:         $modifier,$what,@which)=@_;
12066:     my $result;
12067:     if ($type eq 'course') {
12068: 	$result=&get_courseresdata($name,$domain);
12069:     } elsif ($type eq 'user') {
12070: 	$result=&get_userresdata($name,$domain);
12071:     }
12072:     if (!ref($result)) { return $result; }    
12073:     foreach my $item (@which) {
12074:         if ($item->[1] eq 'course') {
12075:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12076:                 unless ($$recursed) {
12077:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12078:                     $$recursed = 1;
12079:                 }
12080:                 foreach my $item (@${recurseup}) {
12081:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12082:                     last if (defined($result->{$norecursechk}));
12083:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12084:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12085:                 }
12086:             }
12087:         }
12088:         if (defined($result->{$item->[0]})) {
12089: 	    return [$result->{$item->[0]},$item->[1]];
12090: 	}
12091:     }
12092:     return undef;
12093: }
12094: 
12095: sub get_domain_lti {
12096:     my ($cdom,$context) = @_;
12097:     my ($name,%lti);
12098:     if ($context eq 'consumer') {
12099:         $name = 'ltitools';
12100:     } elsif ($context eq 'provider') {
12101:         $name = 'lti';
12102:     } else {
12103:         return %lti;
12104:     }
12105:     my ($result,$cached)=&is_cached_new($name,$cdom);
12106:     if (defined($cached)) {
12107:         if (ref($result) eq 'HASH') {
12108:             %lti = %{$result};
12109:         }
12110:     } else {
12111:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12112:         if (ref($domconfig{$name}) eq 'HASH') {
12113:             %lti = %{$domconfig{$name}};
12114:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
12115:             if (ref($encdomconfig{$name}) eq 'HASH') {
12116:                 foreach my $id (keys(%lti)) {
12117:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12118:                         foreach my $item ('key','secret') {
12119:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12120:                         }
12121:                     }
12122:                 }
12123:             }
12124:         }
12125:         my $cachetime = 24*60*60;
12126:         &do_cache_new($name,$cdom,\%lti,$cachetime);
12127:     }
12128:     return %lti;
12129: }
12130: 
12131: sub get_numsuppfiles {
12132:     my ($cnum,$cdom,$ignorecache)=@_;
12133:     my $hashid=$cnum.':'.$cdom;
12134:     my ($suppcount,$cached);
12135:     unless ($ignorecache) {
12136:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12137:     }
12138:     unless (defined($cached)) {
12139:         my $chome=&homeserver($cnum,$cdom);
12140:         unless ($chome eq 'no_host') {
12141:             ($suppcount,my $supptools,my $errors) = (0,0,0);
12142:             my $suppmap = 'supplemental.sequence';
12143:             ($suppcount,$supptools,$errors) =
12144:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12145:                                                          $supptools,$errors);
12146:         }
12147:         &do_cache_new('suppcount',$hashid,$suppcount,600);
12148:     }
12149:     return $suppcount;
12150: }
12151: 
12152: #
12153: # EXT resource caching routines
12154: #
12155: 
12156: {
12157: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12158: #
12159: # The course for which we cache
12160: my $cachedmapkey='';
12161: # The cached recursive maps for this course
12162: my %cachedmaps=();
12163: # When this was last done
12164: my $cachedmaptime='';
12165: 
12166: sub clear_EXT_cache_status {
12167:     &delenv('cache.EXT.');
12168: }
12169: 
12170: sub EXT_cache_status {
12171:     my ($target_domain,$target_user) = @_;
12172:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12173:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12174:         # We know already the user has no data
12175:         return 1;
12176:     } else {
12177:         return 0;
12178:     }
12179: }
12180: 
12181: sub EXT_cache_set {
12182:     my ($target_domain,$target_user) = @_;
12183:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12184:     #&appenv({$cachename => time});
12185: }
12186: 
12187: # --------------------------------------------------------- Value of a Variable
12188: sub EXT {
12189: 
12190:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
12191:     unless ($varname) { return ''; }
12192:     #get real user name/domain, courseid and symb
12193:     my $courseid;
12194:     my $publicuser;
12195:     if ($symbparm) {
12196: 	$symbparm=&get_symb_from_alias($symbparm);
12197:     }
12198:     if (!($uname && $udom)) {
12199:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12200:       if (!$symbparm) {	$symbparm=$cursymb; }
12201:     } else {
12202: 	$courseid=$env{'request.course.id'};
12203:     }
12204:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12205:     my $rest;
12206:     if (defined($therest[0])) {
12207:        $rest=join('.',@therest);
12208:     } else {
12209:        $rest='';
12210:     }
12211: 
12212:     my $qualifierrest=$qualifier;
12213:     if ($rest) { $qualifierrest.='.'.$rest; }
12214:     my $spacequalifierrest=$space;
12215:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12216:     if ($realm eq 'user') {
12217: # --------------------------------------------------------------- user.resource
12218: 	if ($space eq 'resource') {
12219: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12220: 		  || defined($Apache::lonhomework::parsing_a_task))
12221: 		 &&
12222: 		 ($symbparm eq &symbread()) ) {	
12223: 		# if we are in the middle of processing the resource the
12224: 		# get the value we are planning on committing
12225:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12226:                     return $Apache::lonhomework::results{$qualifierrest};
12227:                 } else {
12228:                     return $Apache::lonhomework::history{$qualifierrest};
12229:                 }
12230: 	    } else {
12231: 		my %restored;
12232: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12233: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12234: 		} else {
12235: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
12236: 		}
12237: 		return $restored{$qualifierrest};
12238: 	    }
12239: # ----------------------------------------------------------------- user.access
12240:         } elsif ($space eq 'access') {
12241: 	    # FIXME - not supporting calls for a specific user
12242:             return &allowed($qualifier,$rest);
12243: # ------------------------------------------ user.preferences, user.environment
12244:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
12245: 	    if (($uname eq $env{'user.name'}) &&
12246: 		($udom eq $env{'user.domain'})) {
12247: 		return $env{join('.',('environment',$qualifierrest))};
12248: 	    } else {
12249: 		my %returnhash;
12250: 		if (!$publicuser) {
12251: 		    %returnhash=&userenvironment($udom,$uname,
12252: 						 $qualifierrest);
12253: 		}
12254: 		return $returnhash{$qualifierrest};
12255: 	    }
12256: # ----------------------------------------------------------------- user.course
12257:         } elsif ($space eq 'course') {
12258: 	    # FIXME - not supporting calls for a specific user
12259:             return $env{join('.',('request.course',$qualifier))};
12260: # ------------------------------------------------------------------- user.role
12261:         } elsif ($space eq 'role') {
12262: 	    # FIXME - not supporting calls for a specific user
12263:             my ($role,$where)=split(/\./,$env{'request.role'});
12264:             if ($qualifier eq 'value') {
12265: 		return $role;
12266:             } elsif ($qualifier eq 'extent') {
12267:                 return $where;
12268:             }
12269: # ----------------------------------------------------------------- user.domain
12270:         } elsif ($space eq 'domain') {
12271:             return $udom;
12272: # ------------------------------------------------------------------- user.name
12273:         } elsif ($space eq 'name') {
12274:             return $uname;
12275: # ---------------------------------------------------- Any other user namespace
12276:         } else {
12277: 	    my %reply;
12278: 	    if (!$publicuser) {
12279: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
12280: 	    }
12281: 	    return $reply{$qualifierrest};
12282:         }
12283:     } elsif ($realm eq 'query') {
12284: # ---------------------------------------------- pull stuff out of query string
12285:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12286: 						[$spacequalifierrest]);
12287: 	return $env{'form.'.$spacequalifierrest}; 
12288:    } elsif ($realm eq 'request') {
12289: # ------------------------------------------------------------- request.browser
12290:         if ($space eq 'browser') {
12291:             return $env{'browser.'.$qualifier};
12292: # ------------------------------------------------------------ request.filename
12293:         } else {
12294:             return $env{'request.'.$spacequalifierrest};
12295:         }
12296:     } elsif ($realm eq 'course') {
12297: # ---------------------------------------------------------- course.description
12298:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
12299:     } elsif ($realm eq 'resource') {
12300: 
12301: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
12302: 	    if (!$symbparm) { $symbparm=&symbread(); }
12303: 	}
12304: 
12305:         if ($qualifier eq '') {
12306: 	    if ($space eq 'title') {
12307: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12308: 	        return &gettitle($symbparm);
12309: 	    }
12310: 	
12311: 	    if ($space eq 'map') {
12312: 	        my ($map) = &decode_symb($symbparm);
12313: 	        return &symbread($map);
12314: 	    }
12315:             if ($space eq 'maptitle') {
12316:                 my ($map) = &decode_symb($symbparm);
12317:                 return &gettitle($map);
12318:             }
12319: 	    if ($space eq 'filename') {
12320: 	        if ($symbparm) {
12321: 		    return &clutter((&decode_symb($symbparm))[2]);
12322: 	        }
12323: 	        return &hreflocation('',$env{'request.filename'});
12324: 	    }
12325: 
12326:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12327:                 if ($space eq 'visibleparts') {
12328:                     my $navmap = Apache::lonnavmaps::navmap->new();
12329:                     my $item;
12330:                     if (ref($navmap)) {
12331:                         my $res = $navmap->getBySymb($symbparm);
12332:                         my $parts = $res->parts();
12333:                         if (ref($parts) eq 'ARRAY') {
12334:                             $item = join(',',@{$parts});
12335:                         }
12336:                         undef($navmap);
12337:                     }
12338:                     return $item;
12339:                 }
12340:             }
12341:         }
12342: 
12343: 	my ($section, $group, @groups, @recurseup, $recursed);
12344: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
12345:         if (($courseid eq '') && ($cid)) {
12346:             $courseid = $cid;
12347:         }
12348: 	if (($symbparm && $courseid) && 
12349: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
12350: 
12351: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
12352: 
12353: # ----------------------------------------------------- Cascading lookup scheme
12354: 	    my $symbp=$symbparm;
12355: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
12356: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
12357:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
12358: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
12359: 	    if (($env{'user.name'} eq $uname) &&
12360: 		($env{'user.domain'} eq $udom)) {
12361: 		$section=$env{'request.course.sec'};
12362:                 @groups = split(/:/,$env{'request.course.groups'});  
12363:                 @groups=&sort_course_groups($courseid,@groups); 
12364: 	    } else {
12365: 		if (! defined($usection)) {
12366: 		    $section=&getsection($udom,$uname,$courseid);
12367: 		} else {
12368: 		    $section = $usection;
12369: 		}
12370:                 @groups = &get_users_groups($udom,$uname,$courseid);
12371: 	    }
12372: 
12373: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12374: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
12375:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
12376: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12377: 
12378: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
12379: 	    my $courselevelr=$courseid.'.'.$symbparm;
12380:             $courseleveli=$courseid.'.'.$recurseparm;
12381: 	    $courselevelm=$courseid.'.'.$mapparm;
12382: 
12383: # ----------------------------------------------------------- first, check user
12384: 
12385: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12386:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
12387: 				       ([$courselevelr,'resource'],
12388: 					[$courselevelm,'map'     ],
12389:                                         [$courseleveli,'map'     ],
12390: 					[$courselevel, 'course'  ]));
12391: 	    if (defined($userreply)) { return &get_reply($userreply); }
12392: 
12393: # ------------------------------------------------ second, check some of course
12394:             my $coursereply;
12395:             if (@groups > 0) {
12396:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
12397:                                        $recurseparm,$mapparm,$spacequalifierrest,
12398:                                        $mapp,\$recursed,\@recurseup);
12399:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
12400:             }
12401: 
12402: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12403: 				  $env{'course.'.$courseid.'.domain'},
12404: 				  'course',$mapp,\$recursed,\@recurseup,
12405:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
12406: 				  ([$seclevelr,   'resource'],
12407: 				   [$seclevelm,   'map'     ],
12408:                                    [$secleveli,   'map'     ],
12409: 				   [$seclevel,    'course'  ],
12410: 				   [$courselevelr,'resource']));
12411: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12412: 
12413: # ------------------------------------------------------ third, check map parms
12414: 	    my %parmhash=();
12415: 	    my $thisparm='';
12416: 	    if (tie(%parmhash,'GDBM_File',
12417: 		    $env{'request.course.fn'}.'_parms.db',
12418: 		    &GDBM_READER(),0640)) {
12419: 		$thisparm=$parmhash{$symbparm};
12420: 		untie(%parmhash);
12421: 	    }
12422: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
12423: 	}
12424: # ------------------------------------------ fourth, look in resource metadata
12425:  
12426:         my $what = $spacequalifierrest;
12427: 	$what=~s/\./\_/;
12428: 	my $filename;
12429: 	if (!$symbparm) { $symbparm=&symbread(); }
12430: 	if ($symbparm) {
12431: 	    $filename=(&decode_symb($symbparm))[2];
12432: 	} else {
12433: 	    $filename=$env{'request.filename'};
12434: 	}
12435:         my $toolsymb;
12436:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12437:             $toolsymb = $symbparm;
12438:         }
12439: 	my $metadata=&metadata($filename,$what,$toolsymb);
12440: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12441: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
12442: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
12443: 
12444: # ----------------------------------------------- fifth, look in rest of course
12445: 	if ($symbparm && defined($courseid) && 
12446: 	    $courseid eq $env{'request.course.id'}) {
12447: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12448: 				     $env{'course.'.$courseid.'.domain'},
12449: 				     'course',$mapp,\$recursed,\@recurseup,
12450:                                      $courseid,'.',$spacequalifierrest,
12451: 				     ([$courselevelm,'map'   ],
12452:                                       [$courseleveli,'map'   ],
12453: 				      [$courselevel, 'course']));
12454: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
12455: 	}
12456: # ------------------------------------------------------------------ Cascade up
12457: 	unless ($space eq '0') {
12458: 	    my @parts=split(/_/,$space);
12459: 	    my $id=pop(@parts);
12460: 	    my $part=join('_',@parts);
12461: 	    if ($part eq '') { $part='0'; }
12462: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
12463: 				 $symbparm,$udom,$uname,$section,1);
12464: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
12465: 	}
12466: 	if ($recurse) { return undef; }
12467: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
12468: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
12469: # ---------------------------------------------------- Any other user namespace
12470:     } elsif ($realm eq 'environment') {
12471: # ----------------------------------------------------------------- environment
12472: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12473: 	    return $env{'environment.'.$spacequalifierrest};
12474: 	} else {
12475: 	    if ($uname eq 'anonymous' && $udom eq '') {
12476: 		return '';
12477: 	    }
12478: 	    my %returnhash=&userenvironment($udom,$uname,
12479: 					    $spacequalifierrest);
12480: 	    return $returnhash{$spacequalifierrest};
12481: 	}
12482:     } elsif ($realm eq 'system') {
12483: # ----------------------------------------------------------------- system.time
12484: 	if ($space eq 'time') {
12485: 	    return time;
12486:         }
12487:     } elsif ($realm eq 'server') {
12488: # ----------------------------------------------------------------- system.time
12489: 	if ($space eq 'name') {
12490: 	    return $ENV{'SERVER_NAME'};
12491:         }
12492:     } elsif ($realm eq 'client') {
12493:         if ($space eq 'remote_addr') {
12494:             return &get_requestor_ip();
12495:         }
12496:     }
12497:     return '';
12498: }
12499: 
12500: sub get_reply {
12501:     my ($reply_value) = @_;
12502:     if (ref($reply_value) eq 'ARRAY') {
12503:         if (wantarray) {
12504: 	    return @$reply_value;
12505:         }
12506:         return $reply_value->[0];
12507:     } else {
12508:         return $reply_value;
12509:     }
12510: }
12511: 
12512: sub check_group_parms {
12513:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12514:         $recursed,$recurseupref) = @_;
12515:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12516:                   [$what,'course']);
12517:     my $coursereply;
12518:     foreach my $group (@{$groups}) {
12519:         my @groupitems = ();
12520:         foreach my $level (@levels) {
12521:              my $item = $courseid.'.['.$group.'].'.$level->[0];
12522:              push(@groupitems,[$item,$level->[1]]);
12523:         }
12524:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12525:                                    $env{'course.'.$courseid.'.domain'},
12526:                                    'course',$mapp,$recursed,$recurseupref,
12527:                                    $courseid,'.['.$group.'].',$what,
12528:                                    @groupitems);
12529:         last if (defined($coursereply));
12530:     }
12531:     return $coursereply;
12532: }
12533: 
12534: sub get_map_hierarchy {
12535:     my ($mapname,$courseid) = @_;
12536:     my @recurseup = ();
12537:     if ($mapname) {
12538:         if (($cachedmapkey eq $courseid) &&
12539:             (abs($cachedmaptime-time)<5)) {
12540:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12541:                 return @{$cachedmaps{$mapname}};
12542:             }
12543:         }
12544:         my $navmap = Apache::lonnavmaps::navmap->new();
12545:         if (ref($navmap)) {
12546:             @recurseup = $navmap->recurseup_maps($mapname);
12547:             undef($navmap);
12548:             $cachedmaps{$mapname} = \@recurseup;
12549:             $cachedmaptime=time;
12550:             $cachedmapkey=$courseid;
12551:         }
12552:     }
12553:     return @recurseup;
12554: }
12555: 
12556: }
12557: 
12558: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
12559:     my ($courseid,@groups) = @_;
12560:     @groups = sort(@groups);
12561:     return @groups;
12562: }
12563: 
12564: sub packages_tab_default {
12565:     my ($uri,$varname,$toolsymb)=@_;
12566:     my (undef,$part,$name)=split(/\./,$varname);
12567: 
12568:     my (@extension,@specifics,$do_default);
12569:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
12570: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
12571: 	if ($pack_type eq 'default') {
12572: 	    $do_default=1;
12573: 	} elsif ($pack_type eq 'extension') {
12574: 	    push(@extension,[$package,$pack_type,$pack_part]);
12575: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
12576: 	    # only look at packages defaults for packages that this id is
12577: 	    push(@specifics,[$package,$pack_type,$pack_part]);
12578: 	}
12579:     }
12580:     # first look for a package that matches the requested part id
12581:     foreach my $package (@specifics) {
12582: 	my (undef,$pack_type,$pack_part)=@{$package};
12583: 	next if ($pack_part ne $part);
12584: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12585: 	    return $packagetab{"$pack_type&$name&default"};
12586: 	}
12587:     }
12588:     # look for any possible matching non extension_ package
12589:     foreach my $package (@specifics) {
12590: 	my (undef,$pack_type,$pack_part)=@{$package};
12591: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12592: 	    return $packagetab{"$pack_type&$name&default"};
12593: 	}
12594: 	if ($pack_type eq 'part') { $pack_part='0'; }
12595: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12596: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
12597: 	}
12598:     }
12599:     # look for any posible extension_ match
12600:     foreach my $package (@extension) {
12601: 	my ($package,$pack_type)=@{$package};
12602: 	if (defined($packagetab{"$pack_type&$name&default"})) {
12603: 	    return $packagetab{"$pack_type&$name&default"};
12604: 	}
12605: 	if (defined($packagetab{$package."&$name&default"})) {
12606: 	    return $packagetab{$package."&$name&default"};
12607: 	}
12608:     }
12609:     # look for a global default setting
12610:     if ($do_default && defined($packagetab{"default&$name&default"})) {
12611: 	return $packagetab{"default&$name&default"};
12612:     }
12613:     return undef;
12614: }
12615: 
12616: sub add_prefix_and_part {
12617:     my ($prefix,$part)=@_;
12618:     my $keyroot;
12619:     if (defined($prefix) && $prefix !~ /^__/) {
12620: 	# prefix that has a part already
12621: 	$keyroot=$prefix;
12622:     } elsif (defined($prefix)) {
12623: 	# prefix that is missing a part
12624: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12625:     } else {
12626: 	# no prefix at all
12627: 	if (defined($part)) { $keyroot='_'.$part; }
12628:     }
12629:     return $keyroot;
12630: }
12631: 
12632: # ---------------------------------------------------------------- Get metadata
12633: 
12634: my %metaentry;
12635: my %importedpartids;
12636: my %importedrespids;
12637: sub metadata {
12638:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
12639:     $uri=&declutter($uri);
12640:     # if it is a non metadata possible uri return quickly
12641:     if (($uri eq '') || 
12642: 	(($uri =~ m|^/*adm/|) && 
12643: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
12644:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
12645: 	return undef;
12646:     }
12647:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
12648: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
12649: 	return undef;
12650:     }
12651:     my $filename=$uri;
12652:     $uri=~s/\.meta$//;
12653: #
12654: # Is the metadata already cached?
12655: # Look at timestamp of caching
12656: # Everything is cached by the main uri, libraries are never directly cached
12657: #
12658:     if (!defined($liburi)) {
12659: 	my ($result,$cached)=&is_cached_new('meta',$uri);
12660: 	if (defined($cached)) { return $result->{':'.$what}; }
12661:     }
12662: 
12663: #
12664: # If the uri is for an external tool the file from
12665: # which metadata should be retrieved depends on whether
12666: # the tool had been configured to be gradable (set in the Course
12667: # Editor or Resource Editor).
12668: #
12669: # If a valid symb has been included as the third arg in the call
12670: # to &metadata() that can be used to retrieve the value of
12671: # parameter_0_gradable set for the resource, and included in the
12672: # uploaded map containing the tool. The value is retrieved via
12673: # &EXT(), if a valid symb is available.  Otherwise the value of
12674: # gradable in the exttool_$marker.db file for the tool instance
12675: # is retrieved via &get().
12676: #
12677: # When lonuserstate::traceroute() calls lonnet::EXT() for 
12678: # hiddenresource and encrypturl (during course initialization)
12679: # the map-level parameter for resource.0.gradable included in the 
12680: # uploaded map containing the tool will not yet have been stored
12681: # in the user_course_parms.db file for the user's session, so in 
12682: # this case fall back to retrieving gradable status from the
12683: # exttool_$marker.db file.
12684: #
12685: # In order to avoid an infinite loop, &metadata() will return
12686: # before a call to &EXT(), if the uri is for an external tool
12687: # and the $what for which metadata is being requested is
12688: # parameter_0_gradable or 0_gradable.
12689: #
12690: 
12691:     if ($uri =~ /ext\.tool$/) {
12692:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12693:             return;
12694:         } else {
12695:             my ($checked,$use_passback);
12696:             if ($toolsymb ne '') {
12697:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
12698:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
12699:                     $checked = 1;
12700:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12701:                         $use_passback = 1;
12702:                     }
12703:                 }
12704:             }
12705:             unless ($checked) {
12706:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12707:                 $marker=~s/\D//g;
12708:                 if ($marker) {
12709:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12710:                     $use_passback = $toolsettings{'gradable'};
12711:                 }
12712:             }
12713:             if ($use_passback) {
12714:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12715:             } else {
12716:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12717:             }
12718:         }
12719:     }
12720: 
12721:     {
12722: # Imported parts would go here
12723:         my @origfiletagids=();
12724:         my $importedparts=0;
12725: 
12726: # Imported responseids would go here
12727:         my $importedresponses=0;
12728: #
12729: # Is this a recursive call for a library?
12730: #
12731: #	if (! exists($metacache{$uri})) {
12732: #	    $metacache{$uri}={};
12733: #	}
12734: 	my $cachetime = 60*60;
12735:         if ($liburi) {
12736: 	    $liburi=&declutter($liburi);
12737:             $filename=$liburi;
12738:         } else {
12739: 	    &devalidate_cache_new('meta',$uri);
12740: 	    undef(%metaentry);
12741: 	}
12742:         my %metathesekeys=();
12743:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12744: 	my $metastring;
12745: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12746: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12747: 	    $metastring = 
12748: 		&Apache::lonnet::ssi_body($which,
12749: 					  ('grade_target' => 'meta'));
12750: 	    $cachetime = 1; # only want this cached in the child not long term
12751: 	} elsif (($uri !~ m -^(editupload)/-) && 
12752:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12753: 	    my $file=&filelocation('',&clutter($filename));
12754: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12755: 	    $metastring=&getfile($file);
12756: 	}
12757:         my $parser=HTML::LCParser->new(\$metastring);
12758:         my $token;
12759:         undef %metathesekeys;
12760:         while ($token=$parser->get_token) {
12761: 	    if ($token->[0] eq 'S') {
12762: 		if (defined($token->[2]->{'package'})) {
12763: #
12764: # This is a package - get package info
12765: #
12766: 		    my $package=$token->[2]->{'package'};
12767: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12768: 		    if (defined($token->[2]->{'id'})) { 
12769: 			$keyroot.='_'.$token->[2]->{'id'}; 
12770: 		    }
12771: 		    if ($metaentry{':packages'}) {
12772: 			$metaentry{':packages'}.=','.$package.$keyroot;
12773: 		    } else {
12774: 			$metaentry{':packages'}=$package.$keyroot;
12775: 		    }
12776: 		    foreach my $pack_entry (keys(%packagetab)) {
12777: 			my $part=$keyroot;
12778: 			$part=~s/^\_//;
12779: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12780: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12781: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12782: 			    # ignore package.tab specified default values
12783:                             # here &package_tab_default() will fetch those
12784: 			    if ($subp eq 'default') { next; }
12785: 			    my $value=$packagetab{$pack_entry};
12786: 			    my $unikey;
12787: 			    if ($pack =~ /_0$/) {
12788: 				$unikey='parameter_0_'.$name;
12789: 				$part=0;
12790: 			    } else {
12791: 				$unikey='parameter'.$keyroot.'_'.$name;
12792: 			    }
12793: 			    if ($subp eq 'display') {
12794: 				$value.=' [Part: '.$part.']';
12795: 			    }
12796: 			    $metaentry{':'.$unikey.'.part'}=$part;
12797: 			    $metathesekeys{$unikey}=1;
12798: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12799: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12800: 			    }
12801: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12802: 				$metaentry{':'.$unikey}=
12803: 				    $metaentry{':'.$unikey.'.default'};
12804: 			    }
12805: 			}
12806: 		    }
12807: 		} else {
12808: #
12809: # This is not a package - some other kind of start tag
12810: #
12811: 		    my $entry=$token->[1];
12812: 		    my $unikey='';
12813: 
12814: 		    if ($entry eq 'import') {
12815: #
12816: # Importing a library here
12817: #
12818:                         my $location=$parser->get_text('/import');
12819:                         my $dir=$filename;
12820:                         $dir=~s|[^/]*$||;
12821:                         $location=&filelocation($dir,$location);
12822: 
12823:                         my $importid=$token->[2]->{'id'};
12824:                         my $importmode=$token->[2]->{'importmode'};
12825: #
12826: # Check metadata for imported file to
12827: # see if it contained response items
12828: #
12829:                         my ($origfile,@libfilekeys);
12830:                         my %currmetaentry = %metaentry;
12831:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12832:                                                            $depthcount+1));
12833:                         if (grep(/^responseorder$/,@libfilekeys)) {
12834:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12835:                                                              undef,$depthcount+1);
12836:                             if ($libresponseorder ne '') {
12837:                                 if ($#origfiletagids<0) {
12838:                                     undef(%importedrespids);
12839:                                     undef(%importedpartids);
12840:                                 }
12841:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12842:                                 if (@respids) {
12843:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12844:                                 }
12845:                                 if ($importedrespids{$importid} ne '') {
12846:                                     $importedresponses = 1;
12847: # We need to get the original file and the imported file to get the response order correct
12848: # Load and inspect original file
12849:                                     if ($#origfiletagids<0) {
12850:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12851:                                         $origfile=&getfile($origfilelocation);
12852:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12853:                                     }
12854:                                 }
12855:                             }
12856:                         }
12857: # Do not overwrite contents of %metaentry hash for resource itself with 
12858: # hash populated for imported library file
12859:                         %metaentry = %currmetaentry;
12860:                         undef(%currmetaentry);
12861:                         if ($importmode eq 'part') {
12862: # Import as part(s)
12863:                            $importedparts=1;
12864: # We need to get the original file and the imported file to get the part order correct
12865: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12866: # Load and inspect original file if we didn't do that already
12867:                            if ($#origfiletagids<0) {
12868:                                undef(%importedrespids);
12869:                                undef(%importedpartids);
12870:                                if ($origfile eq '') {
12871:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12872:                                    $origfile=&getfile($origfilelocation);
12873:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12874:                                }
12875:                            }
12876:                            my @impfilepartids;
12877: # If <partorder> tag is included in metadata for the imported file
12878: # get the parts in the imported file from that.
12879:                            if (grep(/^partorder$/,@libfilekeys)) {
12880:                                %currmetaentry = %metaentry;
12881:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12882:                                                             $depthcount+1);
12883:                                %metaentry = %currmetaentry;
12884:                                undef(%currmetaentry);
12885:                                if ($libpartorder ne '') {
12886:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12887:                                }
12888:                            } else {
12889: # If no <partorder> tag available, load and inspect imported file
12890:                                my $impfile=&getfile($location);
12891:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12892:                            }
12893:                            if ($#impfilepartids>=0) {
12894: # This problem had parts
12895:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12896:                            } else {
12897: # Importing by turning a single problem into a problem part
12898: # It gets the import-tags ID as part-ID
12899:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12900:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12901:                            }
12902:                         } else {
12903: # Import as problem or as normal import
12904:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12905:                             unless ($importmode eq 'problem') {
12906: # Normal import
12907:                                 if (defined($token->[2]->{'id'})) {
12908:                                     $unikey.='_'.$token->[2]->{'id'};
12909:                                 }
12910:                             }
12911: # Check metadata for imported file to
12912: # see if it contained parts
12913:                             if (grep(/^partorder$/,@libfilekeys)) {
12914:                                 %currmetaentry = %metaentry;
12915:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12916:                                                              $depthcount+1);
12917:                                 %metaentry = %currmetaentry;
12918:                                 undef(%currmetaentry);
12919:                                 if ($libpartorder ne '') {
12920:                                     $importedparts = 1;
12921:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12922:                                 }
12923:                             }
12924:                         }
12925: 			if ($depthcount<20) {
12926: 			    my $metadata = 
12927: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12928: 					  $depthcount+1);
12929: 			    foreach my $meta (split(',',$metadata)) {
12930: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12931: 				$metathesekeys{$meta}=1;
12932: 			    }
12933:                         }
12934: 		    } else {
12935: #
12936: # Not importing, some other kind of non-package, non-library start tag
12937: # 
12938:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12939:                         if (defined($token->[2]->{'id'})) {
12940:                             $unikey.='_'.$token->[2]->{'id'};
12941:                         }
12942: 			if (defined($token->[2]->{'name'})) { 
12943: 			    $unikey.='_'.$token->[2]->{'name'}; 
12944: 			}
12945: 			$metathesekeys{$unikey}=1;
12946: 			foreach my $param (@{$token->[3]}) {
12947: 			    $metaentry{':'.$unikey.'.'.$param} =
12948: 				$token->[2]->{$param};
12949: 			}
12950: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12951: 			my $default=$metaentry{':'.$unikey.'.default'};
12952: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12953: 		 # only ws inside the tag, and not in default, so use default
12954: 		 # as value
12955: 			    $metaentry{':'.$unikey}=$default;
12956: 			} elsif ( $internaltext =~ /\S/ ) {
12957: 		  # something interesting inside the tag
12958: 			    $metaentry{':'.$unikey}=$internaltext;
12959: 			} else {
12960: 		  # no interesting values, don't set a default
12961: 			}
12962: # end of not-a-package not-a-library import
12963: 		    }
12964: # end of not-a-package start tag
12965: 		}
12966: # the next is the end of "start tag"
12967: 	    }
12968: 	}
12969: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12970: 	$extension = lc($extension);
12971: 	if ($extension eq 'htm') { $extension='html'; }
12972: 
12973: 	foreach my $key (keys(%packagetab)) {
12974: 	    #no specific packages #how's our extension
12975: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12976: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12977: 					 \%metathesekeys);
12978: 	}
12979: 
12980: 	if (!exists($metaentry{':packages'})
12981: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12982: 	    foreach my $key (keys(%packagetab)) {
12983: 		#no specific packages well let's get default then
12984: 		if ($key!~/^default&/) { next; }
12985: 		&metadata_create_package_def($uri,$key,'default',
12986: 					     \%metathesekeys);
12987: 	    }
12988: 	}
12989: # are there custom rights to evaluate
12990: 	if ($metaentry{':copyright'} eq 'custom') {
12991: 
12992:     #
12993:     # Importing a rights file here
12994:     #
12995: 	    unless ($depthcount) {
12996: 		my $location=$metaentry{':customdistributionfile'};
12997: 		my $dir=$filename;
12998: 		$dir=~s|[^/]*$||;
12999: 		$location=&filelocation($dir,$location);
13000: 		my $rights_metadata =
13001: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13002: 			      $depthcount+1);
13003: 		foreach my $rights (split(',',$rights_metadata)) {
13004: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13005: 		    $metathesekeys{$rights}=1;
13006: 		}
13007: 	    }
13008: 	}
13009: 	# uniqifiy package listing
13010: 	my %seen;
13011: 	my @uniq_packages =
13012: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13013: 	$metaentry{':packages'} = join(',',@uniq_packages);
13014: 
13015:         if (($importedresponses) || ($importedparts)) {
13016:             if ($importedparts) {
13017: # We had imported parts and need to rebuild partorder
13018:                 $metaentry{':partorder'}='';
13019:                 $metathesekeys{'partorder'}=1;
13020:             }
13021:             if ($importedresponses) {
13022: # We had imported responses and need to rebuil responseorder
13023:                 $metaentry{':responseorder'}='';
13024:                 $metathesekeys{'responseorder'}=1;
13025:             }
13026:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13027:                 my $origid = $origfiletagids[$index+1];
13028:                 if ($origfiletagids[$index] eq 'part') {
13029: # Original part, part of the problem
13030:                     if ($importedparts) {
13031:                         $metaentry{':partorder'}.=','.$origid;
13032:                     }
13033:                 } elsif ($origfiletagids[$index] eq 'import') {
13034:                     if ($importedparts) {
13035: # We have imported parts at this position
13036:                         if ($importedpartids{$origid} ne '') {
13037:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13038:                         }
13039:                     }
13040:                     if ($importedresponses) {
13041: # We have imported responses at this position
13042:                         if ($importedrespids{$origid} ne '') {
13043:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13044:                         }
13045:                     }
13046:                 } else {
13047: # Original response item, part of the problem
13048:                     if ($importedresponses) {
13049:                         $metaentry{':responseorder'}.=','.$origid;
13050:                     }
13051:                 }
13052:             }
13053:             if ($importedparts) {
13054:                 $metaentry{':partorder'}=~s/^\,//;
13055:             }
13056:             if ($importedresponses) {
13057:                 $metaentry{':responseorder'}=~s/^\,//;
13058:             }
13059:         }
13060: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13061: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13062: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13063:         unless ($liburi) {
13064: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13065:         }
13066: # this is the end of "was not already recently cached
13067:     }
13068:     return $metaentry{':'.$what};
13069: }
13070: 
13071: sub metadata_create_package_def {
13072:     my ($uri,$key,$package,$metathesekeys)=@_;
13073:     my ($pack,$name,$subp)=split(/\&/,$key);
13074:     if ($subp eq 'default') { next; }
13075:     
13076:     if (defined($metaentry{':packages'})) {
13077: 	$metaentry{':packages'}.=','.$package;
13078:     } else {
13079: 	$metaentry{':packages'}=$package;
13080:     }
13081:     my $value=$packagetab{$key};
13082:     my $unikey;
13083:     $unikey='parameter_0_'.$name;
13084:     $metaentry{':'.$unikey.'.part'}=0;
13085:     $$metathesekeys{$unikey}=1;
13086:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13087: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13088:     }
13089:     if (defined($metaentry{':'.$unikey.'.default'})) {
13090: 	$metaentry{':'.$unikey}=
13091: 	    $metaentry{':'.$unikey.'.default'};
13092:     }
13093: }
13094: 
13095: sub metadata_generate_part0 {
13096:     my ($metadata,$metacache,$uri) = @_;
13097:     my %allnames;
13098:     foreach my $metakey (keys(%$metadata)) {
13099: 	if ($metakey=~/^parameter\_(.*)/) {
13100: 	  my $part=$$metacache{':'.$metakey.'.part'};
13101: 	  my $name=$$metacache{':'.$metakey.'.name'};
13102: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13103: 	    $allnames{$name}=$part;
13104: 	  }
13105: 	}
13106:     }
13107:     foreach my $name (keys(%allnames)) {
13108:       $$metadata{"parameter_0_$name"}=1;
13109:       my $key=":parameter_0_$name";
13110:       $$metacache{"$key.part"}='0';
13111:       $$metacache{"$key.name"}=$name;
13112:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13113: 					   $allnames{$name}.'_'.$name.
13114: 					   '.type'};
13115:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13116: 			     '.display'};
13117:       my $expr='[Part: '.$allnames{$name}.']';
13118:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13119:       $$metacache{"$key.display"}=$olddis;
13120:     }
13121: }
13122: 
13123: # ------------------------------------------------------ Devalidate title cache
13124: 
13125: sub devalidate_title_cache {
13126:     my ($url)=@_;
13127:     if (!$env{'request.course.id'}) { return; }
13128:     my $symb=&symbread($url);
13129:     if (!$symb) { return; }
13130:     my $key=$env{'request.course.id'}."\0".$symb;
13131:     &devalidate_cache_new('title',$key);
13132: }
13133: 
13134: # ------------------------------------------------- Get the title of a course
13135: 
13136: sub current_course_title {
13137:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13138: }
13139: # ------------------------------------------------- Get the title of a resource
13140: 
13141: sub gettitle {
13142:     my $urlsymb=shift;
13143:     my $symb=&symbread($urlsymb);
13144:     if ($symb) {
13145: 	my $key=$env{'request.course.id'}."\0".$symb;
13146: 	my ($result,$cached)=&is_cached_new('title',$key);
13147: 	if (defined($cached)) { 
13148: 	    return $result;
13149: 	}
13150: 	my ($map,$resid,$url)=&decode_symb($symb);
13151: 	my $title='';
13152: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13153: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13154: 	} else {
13155: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13156: 		    &GDBM_READER(),0640)) {
13157: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13158: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13159: 		untie(%bighash);
13160: 	    }
13161: 	}
13162: 	$title=~s/\&colon\;/\:/gs;
13163: 	if ($title) {
13164: # Remember both $symb and $title for dynamic metadata
13165:             $accesshash{$symb.'___crstitle'}=$title;
13166:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13167: # Cache this title and then return it
13168: 	    return &do_cache_new('title',$key,$title,600);
13169: 	}
13170: 	$urlsymb=$url;
13171:     }
13172:     my $title=&metadata($urlsymb,'title');
13173:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13174:     return $title;
13175: }
13176: 
13177: sub get_slot {
13178:     my ($which,$cnum,$cdom)=@_;
13179:     if (!$cnum || !$cdom) {
13180: 	(undef,my $courseid)=&whichuser();
13181: 	$cdom=$env{'course.'.$courseid.'.domain'};
13182: 	$cnum=$env{'course.'.$courseid.'.num'};
13183:     }
13184:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13185:     my %slotinfo;
13186:     if (exists($remembered{$key})) {
13187: 	$slotinfo{$which} = $remembered{$key};
13188:     } else {
13189: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13190: 	&Apache::lonhomework::showhash(%slotinfo);
13191: 	my ($tmp)=keys(%slotinfo);
13192: 	if ($tmp=~/^error:/) { return (); }
13193: 	$remembered{$key} = $slotinfo{$which};
13194:     }
13195:     if (ref($slotinfo{$which}) eq 'HASH') {
13196: 	return %{$slotinfo{$which}};
13197:     }
13198:     return $slotinfo{$which};
13199: }
13200: 
13201: sub get_reservable_slots {
13202:     my ($cnum,$cdom,$uname,$udom) = @_;
13203:     my $now = time;
13204:     my $reservable_info;
13205:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13206:     if (exists($remembered{$key})) {
13207:         $reservable_info = $remembered{$key};
13208:     } else {
13209:         my %resv;
13210:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13211:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13212:         $reservable_info = \%resv;
13213:         $remembered{$key} = $reservable_info;
13214:     }
13215:     return $reservable_info;
13216: }
13217: 
13218: sub get_course_slots {
13219:     my ($cnum,$cdom) = @_;
13220:     my $hashid=$cnum.':'.$cdom;
13221:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13222:     if (defined($cached)) {
13223:         if (ref($result) eq 'HASH') {
13224:             return %{$result};
13225:         }
13226:     } else {
13227:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13228:         my ($tmp) = keys(%slots);
13229:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13230:             &do_cache_new('allslots',$hashid,\%slots,600);
13231:             return %slots;
13232:         }
13233:     }
13234:     return;
13235: }
13236: 
13237: sub devalidate_slots_cache {
13238:     my ($cnum,$cdom)=@_;
13239:     my $hashid=$cnum.':'.$cdom;
13240:     &devalidate_cache_new('allslots',$hashid);
13241: }
13242: 
13243: sub get_coursechange {
13244:     my ($cdom,$cnum) = @_;
13245:     if ($cdom eq '' || $cnum eq '') {
13246:         return unless ($env{'request.course.id'});
13247:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13248:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13249:     }
13250:     my $hashid=$cdom.'_'.$cnum;
13251:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
13252:     if ((defined($cached)) && ($change ne '')) {
13253:         return $change;
13254:     } else {
13255:         my %crshash;
13256:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13257:         if ($crshash{'internal.contentchange'} eq '') {
13258:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13259:             if ($change eq '') {
13260:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13261:                 $change = $crshash{'internal.created'};
13262:             }
13263:         } else {
13264:             $change = $crshash{'internal.contentchange'};
13265:         }
13266:         my $cachetime = 600;
13267:         &do_cache_new('crschange',$hashid,$change,$cachetime);
13268:     }
13269:     return $change;
13270: }
13271: 
13272: sub devalidate_coursechange_cache {
13273:     my ($cnum,$cdom)=@_;
13274:     my $hashid=$cnum.':'.$cdom;
13275:     &devalidate_cache_new('crschange',$hashid);
13276: }
13277: 
13278: # ------------------------------------------------- Update symbolic store links
13279: 
13280: sub symblist {
13281:     my ($mapname,%newhash)=@_;
13282:     $mapname=&deversion(&declutter($mapname));
13283:     my %hash;
13284:     if (($env{'request.course.fn'}) && (%newhash)) {
13285:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13286:                       &GDBM_WRCREAT(),0640)) {
13287: 	    foreach my $url (keys(%newhash)) {
13288: 		next if ($url eq 'last_known'
13289: 			 && $env{'form.no_update_last_known'});
13290: 		$hash{declutter($url)}=&encode_symb($mapname,
13291: 						    $newhash{$url}->[1],
13292: 						    $newhash{$url}->[0]);
13293:             }
13294:             if (untie(%hash)) {
13295: 		return 'ok';
13296:             }
13297:         }
13298:     }
13299:     return 'error';
13300: }
13301: 
13302: # --------------------------------------------------------------- Verify a symb
13303: 
13304: sub symbverify {
13305:     my ($symb,$thisurl,$encstate)=@_;
13306:     my $thisfn=$thisurl;
13307:     $thisfn=&declutter($thisfn);
13308: # direct jump to resource in page or to a sequence - will construct own symbs
13309:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13310: # check URL part
13311:     my ($map,$resid,$url)=&decode_symb($symb);
13312: 
13313:     unless ($url eq $thisfn) { return 0; }
13314: 
13315:     $symb=&symbclean($symb);
13316:     $thisurl=&deversion($thisurl);
13317:     $thisfn=&deversion($thisfn);
13318: 
13319:     my %bighash;
13320:     my $okay=0;
13321: 
13322:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13323:                             &GDBM_READER(),0640)) {
13324:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13325:             $thisurl =~ s/\?.+$//;
13326:             if ($map =~ m{^uploaded/.+\.page$}) {
13327:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13328:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
13329:             }
13330:         }
13331:         my $ids;
13332:         if ($map =~ m{^uploaded/.+\.page$}) {
13333:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
13334:         } else {
13335:             $ids=$bighash{'ids_'.&clutter($thisurl)};
13336:         }
13337:         unless ($ids) {
13338:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
13339:             $ids=$bighash{$idkey};
13340:         }
13341:         if ($ids) {
13342: # ------------------------------------------------------------------- Has ID(s)
13343:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
13344:                 $symb =~ s/\?.+$//;
13345:             }
13346: 	    foreach my $id (split(/\,/,$ids)) {
13347: 	       my ($mapid,$resid)=split(/\./,$id);
13348:                if (
13349:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
13350:    eq $symb) {
13351:                    if (ref($encstate)) {
13352:                        $$encstate = $bighash{'encrypted_'.$id};
13353:                    }
13354: 		   if (($env{'request.role.adv'}) ||
13355: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13356:                        ($thisurl eq '/adm/navmaps')) {
13357: 		       $okay=1;
13358:                        last;
13359: 		   }
13360: 	       }
13361: 	   }
13362:         }
13363: 	untie(%bighash);
13364:     }
13365:     return $okay;
13366: }
13367: 
13368: # --------------------------------------------------------------- Clean-up symb
13369: 
13370: sub symbclean {
13371:     my $symb=shift;
13372:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13373: # remove version from map
13374:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
13375: 
13376: # remove version from URL
13377:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
13378: 
13379: # remove wrapper
13380: 
13381:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
13382:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
13383:     return $symb;
13384: }
13385: 
13386: # ---------------------------------------------- Split symb to find map and url
13387: 
13388: sub encode_symb {
13389:     my ($map,$resid,$url)=@_;
13390:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13391: }
13392: 
13393: sub decode_symb {
13394:     my $symb=shift;
13395:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13396:     my ($map,$resid,$url)=split(/___/,$symb);
13397:     return (&fixversion($map),$resid,&fixversion($url));
13398: }
13399: 
13400: sub fixversion {
13401:     my $fn=shift;
13402:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
13403:     my %bighash;
13404:     my $uri=&clutter($fn);
13405:     my $key=$env{'request.course.id'}.'_'.$uri;
13406: # is this cached?
13407:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
13408:     if (defined($cached)) { return $result; }
13409: # unfortunately not cached, or expired
13410:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13411: 	    &GDBM_READER(),0640)) {
13412:  	if ($bighash{'version_'.$uri}) {
13413:  	    my $version=$bighash{'version_'.$uri};
13414:  	    unless (($version eq 'mostrecent') || 
13415: 		    ($version==&getversion($uri))) {
13416:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
13417:  	    }
13418:  	}
13419:  	untie %bighash;
13420:     }
13421:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
13422: }
13423: 
13424: sub deversion {
13425:     my $url=shift;
13426:     $url=~s/\.\d+\.(\w+)$/\.$1/;
13427:     return $url;
13428: }
13429: 
13430: # ------------------------------------------------------ Return symb list entry
13431: 
13432: sub symbread {
13433:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
13434:         $ignoresymbdb,$noenccheck)=@_;
13435:     my $cache_str='request.symbread.cached.'.$thisfn;
13436:     if (defined($env{$cache_str})) {
13437:         unless (ref($possibles) eq 'HASH') {
13438:             if ($ignorecachednull) {
13439:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
13440:             } else {
13441:                 return $env{$cache_str};
13442:             }
13443:         }
13444:     }
13445: # no filename provided? try from environment
13446:     unless ($thisfn) {
13447:         if ($env{'request.symb'}) {
13448:             return $env{$cache_str}=&symbclean($env{'request.symb'});
13449: 	}
13450: 	$thisfn=$env{'request.filename'};
13451:     }
13452:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13453: # is that filename actually a symb? Verify, clean, and return
13454:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
13455: 	if (&symbverify($thisfn,$1)) {
13456: 	    return $env{$cache_str}=&symbclean($thisfn);
13457: 	}
13458:     }
13459:     $thisfn=declutter($thisfn);
13460:     my %hash;
13461:     my %bighash;
13462:     my $syval='';
13463:     if (($env{'request.course.fn'}) && ($thisfn)) {
13464:         my $targetfn = $thisfn;
13465:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
13466:             $targetfn = 'adm/wrapper/'.$thisfn;
13467:         }
13468: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13469: 	    $targetfn=$1;
13470: 	}
13471:         unless ($ignoresymbdb) {
13472:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13473:                           &GDBM_READER(),0640)) {
13474: 	        $syval=$hash{$targetfn};
13475:                 untie(%hash);
13476:             }
13477:             if ($syval && $checkforblock) {
13478:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
13479:                 if (@blockers) {
13480:                     $syval='';
13481:                 }
13482:             }
13483:         }
13484: # ---------------------------------------------------------- There was an entry
13485:         if ($syval) {
13486: 	    #unless ($syval=~/\_\d+$/) {
13487: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
13488: 		    #&appenv({'request.ambiguous' => $thisfn});
13489: 		    #return $env{$cache_str}='';
13490: 		#}    
13491: 		#$syval.=$1;
13492: 	    #}
13493:         } else {
13494: # ------------------------------------------------------- Was not in symb table
13495:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13496:                             &GDBM_READER(),0640)) {
13497: # ---------------------------------------------- Get ID(s) for current resource
13498:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
13499:               unless ($ids) { 
13500:                  $ids=$bighash{'ids_/'.$thisfn};
13501:               }
13502:               unless ($ids) {
13503: # alias?
13504: 		  $ids=$bighash{'mapalias_'.$thisfn};
13505:               }
13506:               if ($ids) {
13507: # ------------------------------------------------------------------- Has ID(s)
13508:                  my @possibilities=split(/\,/,$ids);
13509:                  if ($#possibilities==0) {
13510: # ----------------------------------------------- There is only one possibility
13511: 		     my ($mapid,$resid)=split(/\./,$ids);
13512: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
13513: 						    $resid,$thisfn);
13514:                      if (ref($possibles) eq 'HASH') {
13515:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13516:                              $possibles->{$syval} = 1;
13517:                          }
13518:                      }
13519:                      if ($checkforblock) {
13520:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13521:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
13522:                              if (@blockers) {
13523:                                  $syval = '';
13524:                                  untie(%bighash);
13525:                                  return $env{$cache_str}='';
13526:                              }
13527:                          }
13528:                      }
13529:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
13530: # ------------------------------------------ There is more than one possibility
13531:                      my $realpossible=0;
13532:                      foreach my $id (@possibilities) {
13533: 			 my $file=$bighash{'src_'.$id};
13534:                          my $canaccess;
13535:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13536:                              $canaccess = 1;
13537:                          } else { 
13538:                              $canaccess = &allowed('bre',$file);
13539:                          }
13540:                          if ($canaccess) {
13541:          		     my ($mapid,$resid)=split(/\./,$id);
13542:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
13543:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13544: 						             $resid,$thisfn);
13545:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
13546:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
13547:                                  if ($checkforblock) {
13548:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
13549:                                      if (@blockers > 0) {
13550:                                          $syval = '';
13551:                                      } else {
13552:                                          $syval = $poss_syval;
13553:                                          $realpossible++;
13554:                                      }
13555:                                  } else {
13556:                                      $syval = $poss_syval;
13557:                                      $realpossible++;
13558:                                  }
13559:                                  if ($syval) {
13560:                                      if (ref($possibles) eq 'HASH') {
13561:                                          $possibles->{$syval} = 1;
13562:                                      }
13563:                                  }
13564:                              }
13565: 			 }
13566:                      }
13567: 		     if ($realpossible!=1) { $syval=''; }
13568:                  } else {
13569:                      $syval='';
13570:                  }
13571: 	      }
13572:               untie(%bighash);
13573:            }
13574:         }
13575:         if ($syval) {
13576: 	    return $env{$cache_str}=$syval;
13577:         }
13578:     }
13579:     &appenv({'request.ambiguous' => $thisfn});
13580:     return $env{$cache_str}='';
13581: }
13582: 
13583: # ---------------------------------------------------------- Return random seed
13584: 
13585: sub numval {
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:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
13595:     return int($txt);
13596: }
13597: 
13598: sub numval2 {
13599:     my $txt=shift;
13600:     $txt=~tr/A-J/0-9/;
13601:     $txt=~tr/a-j/0-9/;
13602:     $txt=~tr/K-T/0-9/;
13603:     $txt=~tr/k-t/0-9/;
13604:     $txt=~tr/U-Z/0-5/;
13605:     $txt=~tr/u-z/0-5/;
13606:     $txt=~s/\D//g;
13607:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13608:     my $total;
13609:     foreach my $val (@txts) { $total+=$val; }
13610:     if ($_64bit) { if ($total > 2**32) { return -1; } }
13611:     return int($total);
13612: }
13613: 
13614: sub numval3 {
13615:     use integer;
13616:     my $txt=shift;
13617:     $txt=~tr/A-J/0-9/;
13618:     $txt=~tr/a-j/0-9/;
13619:     $txt=~tr/K-T/0-9/;
13620:     $txt=~tr/k-t/0-9/;
13621:     $txt=~tr/U-Z/0-5/;
13622:     $txt=~tr/u-z/0-5/;
13623:     $txt=~s/\D//g;
13624:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13625:     my $total;
13626:     foreach my $val (@txts) { $total+=$val; }
13627:     if ($_64bit) { $total=(($total<<32)>>32); }
13628:     return $total;
13629: }
13630: 
13631: sub digest {
13632:     my ($data)=@_;
13633:     my $digest=&Digest::MD5::md5($data);
13634:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
13635:     my ($e,$f);
13636:     {
13637:         use integer;
13638:         $e=($a+$b);
13639:         $f=($c+$d);
13640:         if ($_64bit) {
13641:             $e=(($e<<32)>>32);
13642:             $f=(($f<<32)>>32);
13643:         }
13644:     }
13645:     if (wantarray) {
13646: 	return ($e,$f);
13647:     } else {
13648: 	my $g;
13649: 	{
13650: 	    use integer;
13651: 	    $g=($e+$f);
13652: 	    if ($_64bit) {
13653: 		$g=(($g<<32)>>32);
13654: 	    }
13655: 	}
13656: 	return $g;
13657:     }
13658: }
13659: 
13660: sub latest_rnd_algorithm_id {
13661:     return '64bit5';
13662: }
13663: 
13664: sub get_rand_alg {
13665:     my ($courseid)=@_;
13666:     if (!$courseid) { $courseid=(&whichuser())[1]; }
13667:     if ($courseid) {
13668: 	return $env{"course.$courseid.rndseed"};
13669:     }
13670:     return &latest_rnd_algorithm_id();
13671: }
13672: 
13673: sub validCODE {
13674:     my ($CODE)=@_;
13675:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13676:     return 0;
13677: }
13678: 
13679: sub getCODE {
13680:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
13681:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13682: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
13683: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
13684: 	return $Apache::lonhomework::history{'resource.CODE'};
13685:     }
13686:     return undef;
13687: }
13688: #
13689: #  Determines the random seed for a specific context:
13690: #
13691: # parameters:
13692: #   symb      - in course context the symb for the seed.
13693: #   course_id - The course id of the form domain_coursenum.
13694: #   domain    - Domain for the user.
13695: #   course    - Course for the user.
13696: #   cenv      - environment of the course.
13697: #
13698: # NOTE:
13699: #   All parameters are picked out of the environment if missing
13700: #   or not defined.
13701: #   If a symb cannot be determined the current time is used instead.
13702: #
13703: #  For a given well defined symb, courside, domain, username,
13704: #  and course environment, the seed is reproducible.
13705: #
13706: sub rndseed {
13707:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
13708:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
13709:     if (!defined($symb)) {
13710: 	unless ($symb=$wsymb) { return time; }
13711:     }
13712:     if (!defined $courseid) { 
13713: 	$courseid=$wcourseid; 
13714:     }
13715:     if (!defined $domain) { $domain=$wdomain; }
13716:     if (!defined $username) { $username=$wusername }
13717: 
13718:     my $which;
13719:     if (defined($cenv->{'rndseed'})) {
13720: 	$which = $cenv->{'rndseed'};
13721:     } else {
13722: 	$which =&get_rand_alg($courseid);
13723:     }
13724:     if (defined(&getCODE())) {
13725: 
13726: 	if ($which eq '64bit5') {
13727: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13728: 	} elsif ($which eq '64bit4') {
13729: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13730: 	} else {
13731: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13732: 	}
13733:     } elsif ($which eq '64bit5') {
13734: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
13735:     } elsif ($which eq '64bit4') {
13736: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
13737:     } elsif ($which eq '64bit3') {
13738: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
13739:     } elsif ($which eq '64bit2') {
13740: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
13741:     } elsif ($which eq '64bit') {
13742: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
13743:     }
13744:     return &rndseed_32bit($symb,$courseid,$domain,$username);
13745: }
13746: 
13747: sub rndseed_32bit {
13748:     my ($symb,$courseid,$domain,$username)=@_;
13749:     {
13750: 	use integer;
13751: 	my $symbchck=unpack("%32C*",$symb) << 27;
13752: 	my $symbseed=numval($symb) << 22;
13753: 	my $namechck=unpack("%32C*",$username) << 17;
13754: 	my $nameseed=numval($username) << 12;
13755: 	my $domainseed=unpack("%32C*",$domain) << 7;
13756: 	my $courseseed=unpack("%32C*",$courseid);
13757: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
13758: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13759: 	#&logthis("rndseed :$num:$symb");
13760: 	if ($_64bit) { $num=(($num<<32)>>32); }
13761: 	return $num;
13762:     }
13763: }
13764: 
13765: sub rndseed_64bit {
13766:     my ($symb,$courseid,$domain,$username)=@_;
13767:     {
13768: 	use integer;
13769: 	my $symbchck=unpack("%32S*",$symb) << 21;
13770: 	my $symbseed=numval($symb) << 10;
13771: 	my $namechck=unpack("%32S*",$username);
13772: 	
13773: 	my $nameseed=numval($username) << 21;
13774: 	my $domainseed=unpack("%32S*",$domain) << 10;
13775: 	my $courseseed=unpack("%32S*",$courseid);
13776: 	
13777: 	my $num1=$symbchck+$symbseed+$namechck;
13778: 	my $num2=$nameseed+$domainseed+$courseseed;
13779: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13780: 	#&logthis("rndseed :$num:$symb");
13781: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13782: 	return "$num1,$num2";
13783:     }
13784: }
13785: 
13786: sub rndseed_64bit2 {
13787:     my ($symb,$courseid,$domain,$username)=@_;
13788:     {
13789: 	use integer;
13790: 	# strings need to be an even # of cahracters long, it it is odd the
13791:         # last characters gets thrown away
13792: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13793: 	my $symbseed=numval($symb) << 10;
13794: 	my $namechck=unpack("%32S*",$username.' ');
13795: 	
13796: 	my $nameseed=numval($username) << 21;
13797: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13798: 	my $courseseed=unpack("%32S*",$courseid.' ');
13799: 	
13800: 	my $num1=$symbchck+$symbseed+$namechck;
13801: 	my $num2=$nameseed+$domainseed+$courseseed;
13802: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13803: 	#&logthis("rndseed :$num:$symb");
13804: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13805: 	return "$num1,$num2";
13806:     }
13807: }
13808: 
13809: sub rndseed_64bit3 {
13810:     my ($symb,$courseid,$domain,$username)=@_;
13811:     {
13812: 	use integer;
13813: 	# strings need to be an even # of cahracters long, it it is odd the
13814:         # last characters gets thrown away
13815: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13816: 	my $symbseed=numval2($symb) << 10;
13817: 	my $namechck=unpack("%32S*",$username.' ');
13818: 	
13819: 	my $nameseed=numval2($username) << 21;
13820: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13821: 	my $courseseed=unpack("%32S*",$courseid.' ');
13822: 	
13823: 	my $num1=$symbchck+$symbseed+$namechck;
13824: 	my $num2=$nameseed+$domainseed+$courseseed;
13825: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13826: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13827: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13828: 	
13829: 	return "$num1:$num2";
13830:     }
13831: }
13832: 
13833: sub rndseed_64bit4 {
13834:     my ($symb,$courseid,$domain,$username)=@_;
13835:     {
13836: 	use integer;
13837: 	# strings need to be an even # of cahracters long, it it is odd the
13838:         # last characters gets thrown away
13839: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13840: 	my $symbseed=numval3($symb) << 10;
13841: 	my $namechck=unpack("%32S*",$username.' ');
13842: 	
13843: 	my $nameseed=numval3($username) << 21;
13844: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13845: 	my $courseseed=unpack("%32S*",$courseid.' ');
13846: 	
13847: 	my $num1=$symbchck+$symbseed+$namechck;
13848: 	my $num2=$nameseed+$domainseed+$courseseed;
13849: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13850: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13851: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13852: 	
13853: 	return "$num1:$num2";
13854:     }
13855: }
13856: 
13857: sub rndseed_64bit5 {
13858:     my ($symb,$courseid,$domain,$username)=@_;
13859:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13860:     return "$num1:$num2";
13861: }
13862: 
13863: sub rndseed_CODE_64bit {
13864:     my ($symb,$courseid,$domain,$username)=@_;
13865:     {
13866: 	use integer;
13867: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13868: 	my $symbseed=numval2($symb);
13869: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13870: 	my $CODEseed=numval(&getCODE());
13871: 	my $courseseed=unpack("%32S*",$courseid.' ');
13872: 	my $num1=$symbseed+$CODEchck;
13873: 	my $num2=$CODEseed+$courseseed+$symbchck;
13874: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13875: 	#&logthis("rndseed :$num1:$num2:$symb");
13876: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13877: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13878: 	return "$num1:$num2";
13879:     }
13880: }
13881: 
13882: sub rndseed_CODE_64bit4 {
13883:     my ($symb,$courseid,$domain,$username)=@_;
13884:     {
13885: 	use integer;
13886: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13887: 	my $symbseed=numval3($symb);
13888: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13889: 	my $CODEseed=numval3(&getCODE());
13890: 	my $courseseed=unpack("%32S*",$courseid.' ');
13891: 	my $num1=$symbseed+$CODEchck;
13892: 	my $num2=$CODEseed+$courseseed+$symbchck;
13893: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13894: 	#&logthis("rndseed :$num1:$num2:$symb");
13895: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13896: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13897: 	return "$num1:$num2";
13898:     }
13899: }
13900: 
13901: sub rndseed_CODE_64bit5 {
13902:     my ($symb,$courseid,$domain,$username)=@_;
13903:     my $code = &getCODE();
13904:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13905:     return "$num1:$num2";
13906: }
13907: 
13908: sub setup_random_from_rndseed {
13909:     my ($rndseed)=@_;
13910:     if ($rndseed =~/([,:])/) {
13911:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13912:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13913:             &Math::Random::random_set_seed_from_phrase($rndseed);
13914:         } else {
13915:             &Math::Random::random_set_seed($num1,$num2);
13916:         }
13917:     } else {
13918: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13919:     }
13920: }
13921: 
13922: sub latest_receipt_algorithm_id {
13923:     return 'receipt3';
13924: }
13925: 
13926: sub recunique {
13927:     my $fucourseid=shift;
13928:     my $unique;
13929:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13930: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13931: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13932:     } else {
13933: 	$unique=$perlvar{'lonReceipt'};
13934:     }
13935:     return unpack("%32C*",$unique);
13936: }
13937: 
13938: sub recprefix {
13939:     my $fucourseid=shift;
13940:     my $prefix;
13941:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13942: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13943: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13944:     } else {
13945: 	$prefix=$perlvar{'lonHostID'};
13946:     }
13947:     return unpack("%32C*",$prefix);
13948: }
13949: 
13950: sub ireceipt {
13951:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13952: 
13953:     my $return =&recprefix($fucourseid).'-';
13954: 
13955:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13956: 	$env{'request.state'} eq 'construct') {
13957: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13958: 	return $return;
13959:     }
13960: 
13961:     my $cuname=unpack("%32C*",$funame);
13962:     my $cudom=unpack("%32C*",$fudom);
13963:     my $cucourseid=unpack("%32C*",$fucourseid);
13964:     my $cusymb=unpack("%32C*",$fusymb);
13965:     my $cunique=&recunique($fucourseid);
13966:     my $cpart=unpack("%32S*",$part);
13967:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13968: 
13969: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13970: 			       
13971: 	$return.= ($cunique%$cuname+
13972: 		   $cunique%$cudom+
13973: 		   $cusymb%$cuname+
13974: 		   $cusymb%$cudom+
13975: 		   $cucourseid%$cuname+
13976: 		   $cucourseid%$cudom+
13977: 		   $cpart%$cuname+
13978: 		   $cpart%$cudom);
13979:     } else {
13980: 	$return.= ($cunique%$cuname+
13981: 		   $cunique%$cudom+
13982: 		   $cusymb%$cuname+
13983: 		   $cusymb%$cudom+
13984: 		   $cucourseid%$cuname+
13985: 		   $cucourseid%$cudom);
13986:     }
13987:     return $return;
13988: }
13989: 
13990: sub receipt {
13991:     my ($part)=@_;
13992:     my ($symb,$courseid,$domain,$name) = &whichuser();
13993:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13994: }
13995: 
13996: sub whichuser {
13997:     my ($passedsymb)=@_;
13998:     my ($symb,$courseid,$domain,$name,$publicuser);
13999:     if (defined($env{'form.grade_symb'})) {
14000: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14001: 	my $allowed=&allowed('vgr',$tmp_courseid);
14002: 	if (!$allowed &&
14003: 	    exists($env{'request.course.sec'}) &&
14004: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14005: 	    $allowed=&allowed('vgr',$tmp_courseid.
14006: 			      '/'.$env{'request.course.sec'});
14007: 	}
14008: 	if ($allowed) {
14009: 	    ($symb)=&get_env_multiple('form.grade_symb');
14010: 	    $courseid=$tmp_courseid;
14011: 	    ($domain)=&get_env_multiple('form.grade_domain');
14012: 	    ($name)=&get_env_multiple('form.grade_username');
14013: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14014: 	}
14015:     }
14016:     if (!$passedsymb) {
14017: 	$symb=&symbread();
14018:     } else {
14019: 	$symb=$passedsymb;
14020:     }
14021:     $courseid=$env{'request.course.id'};
14022:     $domain=$env{'user.domain'};
14023:     $name=$env{'user.name'};
14024:     if ($name eq 'public' && $domain eq 'public') {
14025: 	if (!defined($env{'form.username'})) {
14026: 	    $env{'form.username'}.=time.rand(10000000);
14027: 	}
14028: 	$name.=$env{'form.username'};
14029:     }
14030:     return ($symb,$courseid,$domain,$name,$publicuser);
14031: 
14032: }
14033: 
14034: # ------------------------------------------------------------ Serves up a file
14035: # returns either the contents of the file or 
14036: # -1 if the file doesn't exist
14037: #
14038: # if the target is a file that was uploaded via DOCS, 
14039: # a check will be made to see if a current copy exists on the local server,
14040: # if it does this will be served, otherwise a copy will be retrieved from
14041: # the home server for the course and stored in /home/httpd/html/userfiles on
14042: # the local server.   
14043: 
14044: sub getfile {
14045:     my ($file) = @_;
14046:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14047:     &repcopy($file);
14048:     return &readfile($file);
14049: }
14050: 
14051: sub repcopy_userfile {
14052:     my ($file)=@_;
14053:     my $londocroot = $perlvar{'lonDocRoot'};
14054:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14055:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14056:     my ($cdom,$cnum,$filename) = 
14057: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14058:     my $uri="/uploaded/$cdom/$cnum/$filename";
14059:     if (-e "$file") {
14060: # we already have a local copy, check it out
14061: 	my @fileinfo = stat($file);
14062: 	my $rtncode;
14063: 	my $info;
14064: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14065: 	if ($lwpresp ne 'ok') {
14066: # there is no such file anymore, even though we had a local copy
14067: 	    if ($rtncode eq '404') {
14068: 		unlink($file);
14069: 	    }
14070: 	    return -1;
14071: 	}
14072: 	if ($info < $fileinfo[9]) {
14073: # nice, the file we have is up-to-date, just say okay
14074: 	    return 'ok';
14075: 	} else {
14076: # the file is outdated, get rid of it
14077: 	    unlink($file);
14078: 	}
14079:     }
14080: # one way or the other, at this point, we don't have the file
14081: # construct the correct path for the file
14082:     my @parts = ($cdom,$cnum); 
14083:     if ($filename =~ m|^(.+)/[^/]+$|) {
14084: 	push @parts, split(/\//,$1);
14085:     }
14086:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14087:     foreach my $part (@parts) {
14088: 	$path .= '/'.$part;
14089: 	if (!-e $path) {
14090: 	    mkdir($path,0770);
14091: 	}
14092:     }
14093: # now the path exists for sure
14094: # get a user agent
14095:     my $transferfile=$file.'.in.transfer';
14096: # FIXME: this should flock
14097:     if (-e $transferfile) { return 'ok'; }
14098:     my $request;
14099:     $uri=~s/^\///;
14100:     my $homeserver = &homeserver($cnum,$cdom);
14101:     my $hostname = &hostname($homeserver);
14102:     my $protocol = $protocol{$homeserver};
14103:     $protocol = 'http' if ($protocol ne 'https');
14104:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14105:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14106: # did it work?
14107:     if ($response->is_error()) {
14108: 	unlink($transferfile);
14109: 	&logthis("Userfile repcopy failed for $uri");
14110: 	return -1;
14111:     }
14112: # worked, rename the transfer file
14113:     rename($transferfile,$file);
14114:     return 'ok';
14115: }
14116: 
14117: sub tokenwrapper {
14118:     my $uri=shift;
14119:     $uri=~s|^https?\://([^/]+)||;
14120:     $uri=~s|^/||;
14121:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14122:     my $token=$1;
14123:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14124:     if ($udom && $uname && $file) {
14125: 	$file=~s|(\?\.*)*$||;
14126:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14127:         my $homeserver = &homeserver($uname,$udom);
14128:         my $hostname = &hostname($homeserver);
14129:         my $protocol = $protocol{$homeserver};
14130:         $protocol = 'http' if ($protocol ne 'https');
14131:         return $protocol.'://'.$hostname.'/'.$uri.
14132:                (($uri=~/\?/)?'&':'?').'token='.$token.
14133:                                '&tokenissued='.$perlvar{'lonHostID'};
14134:     } else {
14135:         return '/adm/notfound.html';
14136:     }
14137: }
14138: 
14139: # call with reqtype HEAD: get last modification time
14140: # call with reqtype GET: get the file contents
14141: # Do not call this with reqtype GET for large files! It loads everything into memory
14142: #
14143: sub getuploaded {
14144:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14145:     $uri=~s/^\///;
14146:     my $homeserver = &homeserver($cnum,$cdom);
14147:     my $hostname = &hostname($homeserver);
14148:     my $protocol = $protocol{$homeserver};
14149:     $protocol = 'http' if ($protocol ne 'https');
14150:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14151:     my $request=new HTTP::Request($reqtype,$uri);
14152:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14153:     $$rtncode = $response->code;
14154:     if (! $response->is_success()) {
14155: 	return 'failed';
14156:     }      
14157:     if ($reqtype eq 'HEAD') {
14158: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14159:     } elsif ($reqtype eq 'GET') {
14160: 	$$info = $response->content;
14161:     }
14162:     return 'ok';
14163: }
14164: 
14165: sub readfile {
14166:     my $file = shift;
14167:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14168:     my $fh;
14169:     open($fh,"<",$file);
14170:     my $a='';
14171:     while (my $line = <$fh>) { $a .= $line; }
14172:     return $a;
14173: }
14174: 
14175: sub filelocation {
14176:     my ($dir,$file) = @_;
14177:     my $location;
14178:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14179: 
14180:     if ($file =~ m-^/adm/-) {
14181: 	$file=~s-^/adm/wrapper/-/-;
14182: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14183:     }
14184: 
14185:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
14186:         $location = $file;
14187:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
14188:         my ($udom,$uname,$filename)=
14189:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
14190:         my $home=&homeserver($uname,$udom);
14191:         my $is_me=0;
14192:         my @ids=&current_machine_ids();
14193:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14194:         if ($is_me) {
14195:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
14196:         } else {
14197:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14198:   	      $udom.'/'.$uname.'/'.$filename;
14199:         }
14200:     } elsif ($file =~ m-^/adm/-) {
14201: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
14202:     } else {
14203:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
14204:         $file=~s:^/(res|priv)/:/:;
14205:         my $space=$1;
14206:         if ( !( $file =~ m:^/:) ) {
14207:             $location = $dir. '/'.$file;
14208:         } else {
14209:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
14210:         }
14211:     }
14212:     $location=~s://+:/:g; # remove duplicate /
14213:     while ($location=~m{/\.\./}) {
14214: 	if ($location =~ m{/[^/]+/\.\./}) {
14215: 	    $location=~ s{/[^/]+/\.\./}{/}g;
14216: 	} else {
14217: 	    $location=~ s{/\.\./}{/}g;
14218: 	}
14219:     } #remove dir/..
14220:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14221:     return $location;
14222: }
14223: 
14224: sub hreflocation {
14225:     my ($dir,$file)=@_;
14226:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
14227: 	$file=filelocation($dir,$file);
14228:     } elsif ($file=~m-^/adm/-) {
14229: 	$file=~s-^/adm/wrapper/-/-;
14230: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
14231:     }
14232:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14233: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14234:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
14235: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14236: 	        {/uploaded/$1/$2/}x;
14237:     }
14238:     if ($file=~ m{^/userfiles/}) {
14239: 	$file =~ s{^/userfiles/}{/uploaded/};
14240:     }
14241:     return $file;
14242: }
14243: 
14244: 
14245: 
14246: 
14247: 
14248: sub current_machine_domains {
14249:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
14250: }
14251: 
14252: sub machine_domains {
14253:     my ($hostname) = @_;
14254:     my @domains;
14255:     my %hostname = &all_hostnames();
14256:     while( my($id, $name) = each(%hostname)) {
14257: #	&logthis("-$id-$name-$hostname-");
14258: 	if ($hostname eq $name) {
14259: 	    push(@domains,&host_domain($id));
14260: 	}
14261:     }
14262:     return @domains;
14263: }
14264: 
14265: sub current_machine_ids {
14266:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
14267: }
14268: 
14269: sub machine_ids {
14270:     my ($hostname) = @_;
14271:     $hostname ||= &hostname($perlvar{'lonHostID'});
14272:     my @ids;
14273:     my %name_to_host = &all_names();
14274:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14275: 	return @{ $name_to_host{$hostname} };
14276:     }
14277:     return;
14278: }
14279: 
14280: sub additional_machine_domains {
14281:     my @domains;
14282:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
14283:     while( my $line = <$fh>) {
14284:         $line =~ s/\s//g;
14285:         push(@domains,$line);
14286:     }
14287:     return @domains;
14288: }
14289: 
14290: sub default_login_domain {
14291:     my $domain = $perlvar{'lonDefDomain'};
14292:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14293:     foreach my $posdom (&current_machine_domains(),
14294:                         &additional_machine_domains()) {
14295:         if (lc($posdom) eq lc($testdomain)) {
14296:             $domain=$posdom;
14297:             last;
14298:         }
14299:     }
14300:     return $domain;
14301: }
14302: 
14303: sub shared_institution {
14304:     my ($dom,$lonhost) = @_;
14305:     if ($lonhost eq '') {
14306:         $lonhost = $perlvar{'lonHostID'};
14307:     }
14308:     my $same_intdom;
14309:     my $hostintdom = &internet_dom($lonhost);
14310:     if ($hostintdom ne '') {
14311:         my %iphost = &get_iphost();
14312:         my $primary_id = &domain($dom,'primary');
14313:         my $primary_ip = &get_host_ip($primary_id);
14314:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14315:             foreach my $id (@{$iphost{$primary_ip}}) {
14316:                 my $intdom = &internet_dom($id);
14317:                 if ($intdom eq $hostintdom) {
14318:                     $same_intdom = 1;
14319:                     last;
14320:                 }
14321:             }
14322:         }
14323:     }
14324:     return $same_intdom;
14325: }
14326: 
14327: sub uses_sts {
14328:     my ($ignore_cache) = @_;
14329:     my $lonhost = $perlvar{'lonHostID'};
14330:     my $hostname = &hostname($lonhost);
14331:     my $sts_on;
14332:     if ($protocol{$lonhost} eq 'https') {
14333:         my $cachetime = 12*3600;
14334:         if (!$ignore_cache) {
14335:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14336:             if (defined($cached)) {
14337:                 return $sts_on;
14338:             }
14339:         }
14340:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14341:         my $request=new HTTP::Request('HEAD',$url);
14342:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14343:         if ($response->is_success) {
14344:             my $has_sts = $response->header('Strict-Transport-Security');
14345:             if ($has_sts eq '') {
14346:                 $sts_on = 0;
14347:             } else {
14348:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14349:                     my $maxage = $1;
14350:                     if ($maxage) {
14351:                         $sts_on = 1;
14352:                     } else {
14353:                         $sts_on = 0;
14354:                     }
14355:                 } else {
14356:                     $sts_on = 0;
14357:                 }
14358:             }
14359:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14360:         }
14361:     }
14362:     return;
14363: }
14364: 
14365: sub waf_allssl {
14366:     my ($host_name) = @_;
14367:     my $alias = &get_proxy_alias();
14368:     if ($host_name eq '') {
14369:         $host_name = $ENV{'SERVER_NAME'};
14370:     }
14371:     if (($host_name ne '') && ($alias eq $host_name)) {
14372:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14373:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
14374:         if ($defdomdefaults{'waf_sslopt'}) {
14375:             return $defdomdefaults{'waf_sslopt'};
14376:         }
14377:     }
14378:     return;
14379: }
14380: 
14381: sub get_requestor_ip {
14382:     my ($r,$nolookup,$noproxy) = @_;
14383:     my $from_ip;
14384:     if (ref($r)) {
14385:         if ($r->can('useragent_ip')) {
14386:             if ($noproxy && $r->can('client_ip')) {
14387:                 $from_ip = $r->client_ip();
14388:             } else {
14389:                 $from_ip = $r->useragent_ip();
14390:             }
14391:         } elsif ($r->connection->can('remote_ip')) {
14392:             $from_ip = $r->connection->remote_ip();
14393:         } else {
14394:             $from_ip = $r->get_remote_host($nolookup);
14395:         }
14396:     } else {
14397:         $from_ip = $ENV{'REMOTE_ADDR'};
14398:     }
14399:     return $from_ip if ($noproxy); 
14400:     # Who controls proxy settings for server
14401:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14402:     my $proxyinfo = &get_proxy_settings($dom_in_use);
14403:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
14404:         if ($proxyinfo->{'vpnint'}) {
14405:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
14406:                 return $from_ip;
14407:             }
14408:         }
14409:         if ($proxyinfo->{'trusted'}) {
14410:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14411:                 my $ipheader = $proxyinfo->{'ipheader'};
14412:                 my ($ip,$xfor);
14413:                 if (ref($r)) {
14414:                     if ($ipheader) {
14415:                         $ip = $r->headers_in->{$ipheader};
14416:                     }
14417:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
14418:                 } else {
14419:                     if ($ipheader) {
14420:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
14421:                     }
14422:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14423:                 }
14424:                 if (($ip eq '') && ($xfor ne '')) {
14425:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14426:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14427:                             $ip = $poss_ip;
14428:                             last;
14429:                         }
14430:                     }
14431:                 }
14432:                 if ($ip ne '') {
14433:                     return $ip;
14434:                 }
14435:             }
14436:         }
14437:     }
14438:     return $from_ip;
14439: }
14440: 
14441: sub get_proxy_settings {
14442:     my ($dom_in_use) = @_;
14443:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14444:     my $proxyinfo = {
14445:                        ipheader => $domdefaults{'waf_ipheader'},
14446:                        trusted  => $domdefaults{'waf_trusted'},
14447:                        vpnint   => $domdefaults{'waf_vpnint'},
14448:                        vpnext   => $domdefaults{'waf_vpnext'},
14449:                        sslopt   => $domdefaults{'waf_sslopt'},
14450:                     };
14451:     return $proxyinfo;
14452: }
14453: 
14454: sub ip_match {
14455:     my ($ip,$pattern_str) = @_;
14456:     $ip=Net::CIDR::cidrvalidate($ip);
14457:     if ($ip) {
14458:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14459:     }
14460:     return;
14461: }
14462: 
14463: sub get_proxy_alias {
14464:     my ($lonid) = @_;
14465:     if ($lonid eq '') {
14466:         $lonid = $perlvar{'lonHostID'};
14467:     }
14468:     if (!defined(&hostname($lonid))) {
14469:         return;
14470:     }
14471:     if ($lonid ne '') {
14472:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
14473:         if ($cached) {
14474:             return $alias;
14475:         }
14476:         my $dom = &Apache::lonnet::host_domain($lonid);
14477:         if ($dom ne '') {
14478:             my $cachetime = 60*60*24;
14479:             my %domconfig =
14480:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14481:             my $alias;
14482:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14483:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
14484:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14485:                 }
14486:             }
14487:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14488:         }
14489:     }
14490:     return;
14491: }
14492: 
14493: sub use_proxy_alias {
14494:     my ($r,$lonid) = @_;
14495:     my $alias = &get_proxy_alias($lonid);
14496:     if ($alias) {
14497:         my $dom = &host_domain($lonid);
14498:         if ($dom ne '') {
14499:             my $proxyinfo = &get_proxy_settings($dom );
14500:             my ($vpnint,$remote_ip);
14501:             if (ref($proxyinfo) eq 'HASH') {
14502:                 $vpnint = $proxyinfo->{'vpnint'};
14503:                 if ($vpnint) {
14504:                     $remote_ip = &get_requestor_ip($r,1,1);
14505:                 }
14506:             }
14507:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14508:                 return $alias;
14509:             }
14510:         }
14511:     }
14512:     return;
14513: }
14514: 
14515: # ------------------------------------------------------------- Declutters URLs
14516: 
14517: sub declutter {
14518:     my $thisfn=shift;
14519:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14520:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14521:         $thisfn=~s{^/home/httpd/html}{};
14522:     }
14523:     $thisfn=~s/^\///;
14524:     $thisfn=~s|^adm/wrapper/||;
14525:     $thisfn=~s|^adm/coursedocs/showdoc/||;
14526:     $thisfn=~s/^res\///;
14527:     $thisfn=~s/^priv\///;
14528:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14529:         $thisfn=~s/\?.+$//;
14530:     }
14531:     return $thisfn;
14532: }
14533: 
14534: # ------------------------------------------------------------- Clutter up URLs
14535: 
14536: sub clutter {
14537:     my $thisfn='/'.&declutter(shift);
14538:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
14539: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
14540:        $thisfn='/res'.$thisfn; 
14541:     }
14542:     if ($thisfn !~m|^/adm|) {
14543: 	if ($thisfn =~ m|^/ext/|) {
14544: 	    $thisfn='/adm/wrapper'.$thisfn;
14545: 	} else {
14546: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
14547: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
14548: 	    if ($embstyle eq 'ssi'
14549: 		|| ($embstyle eq 'hdn')
14550: 		|| ($embstyle eq 'rat')
14551: 		|| ($embstyle eq 'prv')
14552: 		|| ($embstyle eq 'ign')) {
14553: 		#do nothing with these
14554: 	    } elsif (($embstyle eq 'img') 
14555: 		|| ($embstyle eq 'emb')
14556: 		|| ($embstyle eq 'wrp')) {
14557: 		$thisfn='/adm/wrapper'.$thisfn;
14558: 	    } elsif ($embstyle eq 'unk'
14559: 		     && $thisfn!~/\.(sequence|page)$/) {
14560: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
14561: 	    } else {
14562: #		&logthis("Got a blank emb style");
14563: 	    }
14564: 	}
14565:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
14566:         $thisfn='/adm/wrapper'.$thisfn;
14567:     }
14568:     return $thisfn;
14569: }
14570: 
14571: sub clutter_with_no_wrapper {
14572:     my $uri = &clutter(shift);
14573:     if ($uri =~ m-^/adm/-) {
14574: 	$uri =~ s-^/adm/wrapper/-/-;
14575: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
14576:     }
14577:     return $uri;
14578: }
14579: 
14580: sub freeze_escape {
14581:     my ($value)=@_;
14582:     if (ref($value)) {
14583: 	$value=&nfreeze($value);
14584: 	return '__FROZEN__'.&escape($value);
14585:     }
14586:     return &escape($value);
14587: }
14588: 
14589: 
14590: sub thaw_unescape {
14591:     my ($value)=@_;
14592:     if ($value =~ /^__FROZEN__/) {
14593: 	substr($value,0,10,undef);
14594: 	$value=&unescape($value);
14595: 	return &thaw($value);
14596:     }
14597:     return &unescape($value);
14598: }
14599: 
14600: sub correct_line_ends {
14601:     my ($result)=@_;
14602:     $$result =~s/\r\n/\n/mg;
14603:     $$result =~s/\r/\n/mg;
14604: }
14605: # ================================================================ Main Program
14606: 
14607: sub goodbye {
14608:    &logthis("Starting Shut down");
14609: #not converted to using infrastruture and probably shouldn't be
14610:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
14611: #converted
14612: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
14613:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14614: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14615: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
14616: #1.1 only
14617: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14618: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14619: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14620: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14621:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
14622:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14623:    &logthis(sprintf("%-20s is %s",'hits',$hits));
14624:    &flushcourselogs();
14625:    &logthis("Shutting down");
14626: }
14627: 
14628: sub get_dns {
14629:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
14630:     if (!$ignore_cache) {
14631: 	my ($content,$cached)=
14632: 	    &Apache::lonnet::is_cached_new('dns',$url);
14633: 	if ($cached) {
14634: 	    &$func($content,$hashref);
14635: 	    return;
14636: 	}
14637:     }
14638: 
14639:     my %alldns;
14640:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14641:         foreach my $dns (<$config>) {
14642: 	    next if ($dns !~ /^\^(\S*)/x);
14643:             my $line = $1;
14644:             my ($host,$protocol) = split(/:/,$line);
14645:             if ($protocol ne 'https') {
14646:                 $protocol = 'http';
14647:             }
14648: 	    $alldns{$host} = $protocol;
14649:         }
14650:         close($config);
14651:     }
14652:     while (%alldns) {
14653: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
14654: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14655:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14656:         delete($alldns{$dns});
14657: 	next if ($response->is_error());
14658:         if ($url eq '/adm/dns/loncapaCRL') {
14659:             return &$func($response);
14660:         } else {
14661: 	    my @content = split("\n",$response->content);
14662: 	    unless ($nocache) {
14663: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
14664: 	    }
14665: 	    &$func(\@content,$hashref);
14666:             return;
14667:         }
14668:     }
14669:     my $which = (split('/',$url,4))[3];
14670:     if ($which eq 'loncapaCRL') {
14671:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14672:         if (-e $diskfile) {
14673:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
14674:         } else {
14675:             &logthis("unable to contact DNS, no on disk file $diskfile available");
14676:         }
14677:     } else {
14678:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14679:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14680:             my @content = <$config>;
14681:             close($config);
14682:             &$func(\@content,$hashref);
14683:         }
14684:     }
14685:     return;
14686: }
14687: 
14688: # ------------------------------------------------------Get DNS checksums file
14689: sub parse_dns_checksums_tab {
14690:     my ($lines,$hashref) = @_;
14691:     my $lonhost = $perlvar{'lonHostID'};
14692:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
14693:     my $loncaparev = &get_server_loncaparev($machine_dom);
14694:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14695:     my $webconfdir = '/etc/httpd/conf';
14696:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14697:         $webconfdir = '/etc/apache2';
14698:     } elsif ($distro =~ /^sles(\d+)$/) {
14699:         if ($1 >= 10) {
14700:             $webconfdir = '/etc/apache2';
14701:         }
14702:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14703:         if ($1 >= 10.0) {
14704:             $webconfdir = '/etc/apache2';
14705:         }
14706:     }
14707:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14708:     my (%chksum,%revnum);
14709:     if (ref($lines) eq 'ARRAY') {
14710:         chomp(@{$lines});
14711:         my $version = shift(@{$lines});
14712:         if ($version eq $release) {  
14713:             foreach my $line (@{$lines}) {
14714:                 my ($file,$version,$shasum) = split(/,/,$line);
14715:                 if ($file =~ m{^/etc/httpd/conf}) {
14716:                     if ($webconfdir eq '/etc/apache2') {
14717:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14718:                     }
14719:                 }
14720:                 $chksum{$file} = $shasum;
14721:                 $revnum{$file} = $version;
14722:             }
14723:             if (ref($hashref) eq 'HASH') {
14724:                 %{$hashref} = (
14725:                                 sums     => \%chksum,
14726:                                 versions => \%revnum,
14727:                               );
14728:             }
14729:         }
14730:     }
14731:     return;
14732: }
14733: 
14734: sub fetch_dns_checksums {
14735:     my %checksums;
14736:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
14737:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
14738:     my ($release,$timestamp) = split(/\-/,$loncaparev);
14739:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
14740:              \%checksums);
14741:     return \%checksums;
14742: }
14743: 
14744: sub fetch_crl_pemfile {
14745:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14746: }
14747: 
14748: sub save_crl_pem {
14749:     my ($response) = @_;
14750:     my ($msg,$hadchanges);
14751:     if (ref($response)) {
14752:         my $now = time;
14753:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14754:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14755:         if (open(my $fh,'>',"$tmpcrl")) {
14756:             print $fh $response->content;
14757:             close($fh);
14758:             if (-e $lonca) {
14759:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14760:                     my $check = <PIPE>;
14761:                     close(PIPE);
14762:                     chomp($check);
14763:                     if ($check eq 'verify OK') {
14764:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14765:                         my $backup;
14766:                         if (-e $dest) {
14767:                             if (&File::Copy::move($dest,"$dest.bak")) {
14768:                                 $backup = 'ok';
14769:                             }
14770:                         }
14771:                         if (&File::Copy::move($tmpcrl,$dest)) {
14772:                             $msg = 'ok';
14773:                             if ($backup) {
14774:                                 my (%oldnums,%newnums);
14775:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14776:                                     while (<PIPE>) {
14777:                                         $oldnums{(split(/:/))[1]} = 1;
14778:                                     }
14779:                                     close(PIPE);
14780:                                 }
14781:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14782:                                     while(<PIPE>) {
14783:                                         $newnums{(split(/:/))[1]} = 1;
14784:                                     }
14785:                                     close(PIPE);
14786:                                 }
14787:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14788:                                     unless (exists($oldnums{$key})) {
14789:                                         $hadchanges = 1;
14790:                                         last;
14791:                                     }
14792:                                 }
14793:                                 unless ($hadchanges) {
14794:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14795:                                         unless (exists($newnums{$key})) {
14796:                                             $hadchanges = 1;
14797:                                             last;
14798:                                         }
14799:                                     }
14800:                                 }
14801:                             }
14802:                         }
14803:                     } else {
14804:                         unlink($tmpcrl);
14805:                     }
14806:                 } else {
14807:                     unlink($tmpcrl);
14808:                 }
14809:             } else {
14810:                 unlink($tmpcrl);
14811:             }
14812:         }
14813:     }
14814:     return ($msg,$hadchanges);
14815: }
14816: 
14817: # ------------------------------------------------------------ Read domain file
14818: {
14819:     my $loaded;
14820:     my %domain;
14821: 
14822:     sub parse_domain_tab {
14823: 	my ($lines) = @_;
14824: 	foreach my $line (@$lines) {
14825: 	    next if ($line =~ /^(\#|\s*$ )/x);
14826: 
14827: 	    chomp($line);
14828: 	    my ($name,@elements) = split(/:/,$line,9);
14829: 	    my %this_domain;
14830: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
14831: 			       'lang_def', 'city', 'longi', 'lati',
14832: 			       'primary') {
14833: 		$this_domain{$field} = shift(@elements);
14834: 	    }
14835: 	    $domain{$name} = \%this_domain;
14836: 	}
14837:     }
14838: 
14839:     sub reset_domain_info {
14840: 	undef($loaded);
14841: 	undef(%domain);
14842:     }
14843: 
14844:     sub load_domain_tab {
14845: 	my ($ignore_cache,$nocache) = @_;
14846: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
14847: 	my $fh;
14848: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
14849: 	    my @lines = <$fh>;
14850: 	    &parse_domain_tab(\@lines);
14851: 	}
14852: 	close($fh);
14853: 	$loaded = 1;
14854:     }
14855: 
14856:     sub domain {
14857: 	&load_domain_tab() if (!$loaded);
14858: 
14859: 	my ($name,$what) = @_;
14860: 	return if ( !exists($domain{$name}) );
14861: 
14862: 	if (!$what) {
14863: 	    return $domain{$name}{'description'};
14864: 	}
14865: 	return $domain{$name}{$what};
14866:     }
14867: 
14868:     sub domain_info {
14869:         &load_domain_tab() if (!$loaded);
14870:         return %domain;
14871:     }
14872: 
14873: }
14874: 
14875: 
14876: # ------------------------------------------------------------- Read hosts file
14877: {
14878:     my %hostname;
14879:     my %hostdom;
14880:     my %libserv;
14881:     my $loaded;
14882:     my %name_to_host;
14883:     my %internetdom;
14884:     my %LC_dns_serv;
14885: 
14886:     sub parse_hosts_tab {
14887: 	my ($file) = @_;
14888: 	foreach my $configline (@$file) {
14889: 	    next if ($configline =~ /^(\#|\s*$ )/x);
14890:             chomp($configline);
14891: 	    if ($configline =~ /^\^/) {
14892:                 if ($configline =~ /^\^([\w.\-]+)/) {
14893:                     $LC_dns_serv{$1} = 1;
14894:                 }
14895:                 next;
14896:             }
14897: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
14898: 	    $name=~s/\s//g;
14899: 	    if ($id && $domain && $role && $name) {
14900:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
14901:                     my $curr = $hostname{$id};
14902:                     my $skip;
14903:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
14904:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
14905:                             $skip = 1;
14906:                         } else {
14907:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
14908:                         }
14909:                     }
14910:                     unless ($skip) {
14911:                         push(@{$name_to_host{$name}},$id);
14912:                     }
14913:                 } else {
14914:                     push(@{$name_to_host{$name}},$id);
14915:                 }
14916: 		$hostname{$id}=$name;
14917: 		$hostdom{$id}=$domain;
14918: 		if ($role eq 'library') { $libserv{$id}=$name; }
14919:                 if (defined($protocol)) {
14920:                     if ($protocol eq 'https') {
14921:                         $protocol{$id} = $protocol;
14922:                     } else {
14923:                         $protocol{$id} = 'http'; 
14924:                     }
14925:                 } else {
14926:                     $protocol{$id} = 'http';
14927:                 }
14928:                 if (defined($intdom)) {
14929:                     $internetdom{$id} = $intdom;
14930:                 }
14931: 	    }
14932: 	}
14933:     }
14934:     
14935:     sub reset_hosts_info {
14936: 	&purge_remembered();
14937: 	&reset_domain_info();
14938: 	&reset_hosts_ip_info();
14939:         undef(%internetdom);
14940: 	undef(%name_to_host);
14941: 	undef(%hostname);
14942: 	undef(%hostdom);
14943: 	undef(%libserv);
14944: 	undef($loaded);
14945:     }
14946: 
14947:     sub load_hosts_tab {
14948: 	my ($ignore_cache,$nocache) = @_;
14949: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
14950: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
14951: 	my @config = <$config>;
14952: 	&parse_hosts_tab(\@config);
14953: 	close($config);
14954: 	$loaded=1;
14955:     }
14956: 
14957:     sub hostname {
14958: 	&load_hosts_tab() if (!$loaded);
14959: 
14960: 	my ($lonid) = @_;
14961: 	return $hostname{$lonid};
14962:     }
14963: 
14964:     sub all_hostnames {
14965: 	&load_hosts_tab() if (!$loaded);
14966: 
14967: 	return %hostname;
14968:     }
14969: 
14970:     sub all_names {
14971:         my ($ignore_cache,$nocache) = @_;
14972: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
14973: 
14974: 	return %name_to_host;
14975:     }
14976: 
14977:     sub all_host_domain {
14978:         &load_hosts_tab() if (!$loaded);
14979:         return %hostdom;
14980:     }
14981: 
14982:     sub all_host_intdom {
14983:         &load_hosts_tab() if (!$loaded);
14984:         return %internetdom;
14985:     }
14986: 
14987:     sub is_library {
14988: 	&load_hosts_tab() if (!$loaded);
14989: 
14990: 	return exists($libserv{$_[0]});
14991:     }
14992: 
14993:     sub all_library {
14994: 	&load_hosts_tab() if (!$loaded);
14995: 
14996: 	return %libserv;
14997:     }
14998: 
14999:     sub unique_library {
15000: 	#2x reverse removes all hostnames that appear more than once
15001:         my %unique = reverse &all_library();
15002:         return reverse %unique;
15003:     }
15004: 
15005:     sub get_servers {
15006: 	&load_hosts_tab() if (!$loaded);
15007: 
15008: 	my ($domain,$type) = @_;
15009: 	my %possible_hosts = ($type eq 'library') ? %libserv
15010: 	                                          : %hostname;
15011: 	my %result;
15012: 	if (ref($domain) eq 'ARRAY') {
15013: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15014: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15015: 		    $result{$host} = $hostname;
15016: 		}
15017: 	    }
15018: 	} else {
15019: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15020: 		if ($hostdom{$host} eq $domain) {
15021: 		    $result{$host} = $hostname;
15022: 		}
15023: 	    }
15024: 	}
15025: 	return %result;
15026:     }
15027: 
15028:     sub get_unique_servers {
15029:         my %unique = reverse &get_servers(@_);
15030: 	return reverse %unique;
15031:     }
15032: 
15033:     sub host_domain {
15034: 	&load_hosts_tab() if (!$loaded);
15035: 
15036: 	my ($lonid) = @_;
15037: 	return $hostdom{$lonid};
15038:     }
15039: 
15040:     sub all_domains {
15041: 	&load_hosts_tab() if (!$loaded);
15042: 
15043: 	my %seen;
15044: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
15045: 	return @uniq;
15046:     }
15047: 
15048:     sub internet_dom {
15049:         &load_hosts_tab() if (!$loaded);
15050: 
15051:         my ($lonid) = @_;
15052:         return $internetdom{$lonid};
15053:     }
15054: 
15055:     sub is_LC_dns {
15056:         &load_hosts_tab() if (!$loaded);
15057: 
15058:         my ($hostname) = @_;
15059:         return exists($LC_dns_serv{$hostname});
15060:     }
15061: 
15062: }
15063: 
15064: { 
15065:     my %iphost;
15066:     my %name_to_ip;
15067:     my %lonid_to_ip;
15068: 
15069:     sub get_hosts_from_ip {
15070: 	my ($ip) = @_;
15071: 	my %iphosts = &get_iphost();
15072: 	if (ref($iphosts{$ip})) {
15073: 	    return @{$iphosts{$ip}};
15074: 	}
15075: 	return;
15076:     }
15077:     
15078:     sub reset_hosts_ip_info {
15079: 	undef(%iphost);
15080: 	undef(%name_to_ip);
15081: 	undef(%lonid_to_ip);
15082:     }
15083: 
15084:     sub get_host_ip {
15085: 	my ($lonid) = @_;
15086: 	if (exists($lonid_to_ip{$lonid})) {
15087: 	    return $lonid_to_ip{$lonid};
15088: 	}
15089: 	my $name=&hostname($lonid);
15090:    	my $ip = gethostbyname($name);
15091: 	return if (!$ip || length($ip) ne 4);
15092: 	$ip=inet_ntoa($ip);
15093: 	$name_to_ip{$name}   = $ip;
15094: 	$lonid_to_ip{$lonid} = $ip;
15095: 	return $ip;
15096:     }
15097:     
15098:     sub get_iphost {
15099: 	my ($ignore_cache,$nocache) = @_;
15100: 
15101: 	if (!$ignore_cache) {
15102: 	    if (%iphost) {
15103: 		return %iphost;
15104: 	    }
15105: 	    my ($ip_info,$cached)=
15106: 		&Apache::lonnet::is_cached_new('iphost','iphost');
15107: 	    if ($cached) {
15108: 		%iphost      = %{$ip_info->[0]};
15109: 		%name_to_ip  = %{$ip_info->[1]};
15110: 		%lonid_to_ip = %{$ip_info->[2]};
15111: 		return %iphost;
15112: 	    }
15113: 	}
15114: 
15115: 	# get yesterday's info for fallback
15116: 	my %old_name_to_ip;
15117: 	my ($ip_info,$cached)=
15118: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
15119: 	if ($cached) {
15120: 	    %old_name_to_ip = %{$ip_info->[1]};
15121: 	}
15122: 
15123: 	my %name_to_host = &all_names($ignore_cache,$nocache);
15124: 	foreach my $name (keys(%name_to_host)) {
15125: 	    my $ip;
15126: 	    if (!exists($name_to_ip{$name})) {
15127: 		$ip = gethostbyname($name);
15128: 		if (!$ip || length($ip) ne 4) {
15129: 		    if (defined($old_name_to_ip{$name})) {
15130: 			$ip = $old_name_to_ip{$name};
15131: 			&logthis("Can't find $name defaulting to old $ip");
15132: 		    } else {
15133: 			&logthis("Name $name no IP found");
15134: 			next;
15135: 		    }
15136: 		} else {
15137: 		    $ip=inet_ntoa($ip);
15138: 		}
15139: 		$name_to_ip{$name} = $ip;
15140: 	    } else {
15141: 		$ip = $name_to_ip{$name};
15142: 	    }
15143: 	    foreach my $id (@{ $name_to_host{$name} }) {
15144: 		$lonid_to_ip{$id} = $ip;
15145: 	    }
15146: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
15147: 	}
15148:         unless ($nocache) {
15149: 	    &do_cache_new('iphost','iphost',
15150: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
15151: 		          48*60*60);
15152:         }
15153: 
15154: 	return %iphost;
15155:     }
15156: 
15157:     #
15158:     #  Given a DNS returns the loncapa host name for that DNS 
15159:     # 
15160:     sub host_from_dns {
15161:         my ($dns) = @_;
15162:         my @hosts;
15163:         my $ip;
15164: 
15165:         if (exists($name_to_ip{$dns})) {
15166:             $ip = $name_to_ip{$dns};
15167:         }
15168:         if (!$ip) {
15169:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15170:             if (length($ip) == 4) { 
15171: 	        $ip   = &IO::Socket::inet_ntoa($ip);
15172:             }
15173:         }
15174:         if ($ip) {
15175: 	    @hosts = get_hosts_from_ip($ip);
15176: 	    return $hosts[0];
15177:         }
15178:         return undef;
15179:     }
15180: 
15181:     sub get_internet_names {
15182:         my ($lonid) = @_;
15183:         return if ($lonid eq '');
15184:         my ($idnref,$cached)=
15185:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
15186:         if ($cached) {
15187:             return $idnref;
15188:         }
15189:         my $ip = &get_host_ip($lonid);
15190:         my @hosts = &get_hosts_from_ip($ip);
15191:         my %iphost = &get_iphost();
15192:         my (@idns,%seen);
15193:         foreach my $id (@hosts) {
15194:             my $dom = &host_domain($id);
15195:             my $prim_id = &domain($dom,'primary');
15196:             my $prim_ip = &get_host_ip($prim_id);
15197:             next if ($seen{$prim_ip});
15198:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15199:                 foreach my $id (@{$iphost{$prim_ip}}) {
15200:                     my $intdom = &internet_dom($id);
15201:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
15202:                         push(@idns,$intdom);
15203:                     }
15204:                 }
15205:             }
15206:             $seen{$prim_ip} = 1;
15207:         }
15208:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
15209:     }
15210: 
15211: }
15212: 
15213: sub all_loncaparevs {
15214:     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);
15215: }
15216: 
15217: # ---------------------------------------------------------- Read loncaparev table
15218: {
15219:     sub load_loncaparevs { 
15220:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
15221:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
15222:                 while (my $configline=<$config>) {
15223:                     chomp($configline);
15224:                     my ($hostid,$loncaparev)=split(/:/,$configline);
15225:                     $loncaparevs{$hostid}=$loncaparev;
15226:                 }
15227:                 close($config);
15228:             }
15229:         }
15230:     }
15231: }
15232: 
15233: # ---------------------------------------------------------- Read serverhostID table
15234: {
15235:     sub load_serverhomeIDs {
15236:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
15237:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
15238:                 while (my $configline=<$config>) {
15239:                     chomp($configline);
15240:                     my ($name,$id)=split(/:/,$configline);
15241:                     $serverhomeIDs{$name}=$id;
15242:                 }
15243:                 close($config);
15244:             }
15245:         }
15246:     }
15247: }
15248: 
15249: 
15250: BEGIN {
15251: 
15252: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15253:     unless ($readit) {
15254: {
15255:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15256:     %perlvar = (%perlvar,%{$configvars});
15257: }
15258: 
15259: 
15260: # ------------------------------------------------------ Read spare server file
15261: {
15262:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
15263: 
15264:     while (my $configline=<$config>) {
15265:        chomp($configline);
15266:        if ($configline) {
15267: 	   my ($host,$type) = split(':',$configline,2);
15268: 	   if (!defined($type) || $type eq '') { $type = 'default' };
15269: 	   push(@{ $spareid{$type} }, $host);
15270:        }
15271:     }
15272:     close($config);
15273: }
15274: # ------------------------------------------------------------ Read permissions
15275: {
15276:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
15277: 
15278:     while (my $configline=<$config>) {
15279: 	chomp($configline);
15280: 	if ($configline) {
15281: 	    my ($role,$perm)=split(/ /,$configline);
15282: 	    if ($perm ne '') { $pr{$role}=$perm; }
15283: 	}
15284:     }
15285:     close($config);
15286: }
15287: 
15288: # -------------------------------------------- Read plain texts for permissions
15289: {
15290:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
15291: 
15292:     while (my $configline=<$config>) {
15293: 	chomp($configline);
15294: 	if ($configline) {
15295: 	    my ($short,@plain)=split(/:/,$configline);
15296:             %{$prp{$short}} = ();
15297: 	    if (@plain > 0) {
15298:                 $prp{$short}{'std'} = $plain[0];
15299:                 for (my $i=1; $i<@plain; $i++) {
15300:                     $prp{$short}{'alt'.$i} = $plain[$i];  
15301:                 }
15302:             }
15303: 	}
15304:     }
15305:     close($config);
15306: }
15307: 
15308: # ---------------------------------------------------------- Read package table
15309: {
15310:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
15311: 
15312:     while (my $configline=<$config>) {
15313: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
15314: 	chomp($configline);
15315: 	my ($short,$plain)=split(/:/,$configline);
15316: 	my ($pack,$name)=split(/\&/,$short);
15317: 	if ($plain ne '') {
15318: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
15319: 	    $packagetab{$short}=$plain; 
15320: 	}
15321:     }
15322:     close($config);
15323: }
15324: 
15325: # ---------------------------------------------------------- Read loncaparev table
15326: 
15327: &load_loncaparevs();
15328: 
15329: # ---------------------------------------------------------- Read serverhostID table
15330: 
15331: &load_serverhomeIDs();
15332: 
15333: # ---------------------------------------------------------- Read releaseslist XML
15334: {
15335:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15336:     if (-e $file) {
15337:         my $parser = HTML::LCParser->new($file);
15338:         while (my $token = $parser->get_token()) {
15339:             if ($token->[0] eq 'S') {
15340:                 my $item = $token->[1];
15341:                 my $name = $token->[2]{'name'};
15342:                 my $value = $token->[2]{'value'};
15343:                 my $valuematch = $token->[2]{'valuematch'};
15344:                 my $namematch = $token->[2]{'namematch'};
15345:                 if ($item eq 'parameter') {
15346:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15347:                         my $release = $parser->get_text();
15348:                         $release =~ s/(^\s*|\s*$ )//gx;
15349:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15350:                     }
15351:                 } elsif ($item ne '' && $name ne '') {
15352:                     my $release = $parser->get_text();
15353:                     $release =~ s/(^\s*|\s*$ )//gx;
15354:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
15355:                 }
15356:             }
15357:         }
15358:     }
15359: }
15360: 
15361: # ---------------------------------------------------------- Read managers table
15362: {
15363:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
15364:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
15365:             while (my $configline=<$config>) {
15366:                 chomp($configline);
15367:                 next if ($configline =~ /^\#/);
15368:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15369:                     $managerstab{$configline} = 1;
15370:                 }
15371:             }
15372:             close($config);
15373:         }
15374:     }
15375: }
15376: 
15377: # ------------- set up temporary directory
15378: {
15379:     $tmpdir = LONCAPA::tempdir();
15380: 
15381: }
15382: 
15383: # ------------- set default texengine (domain default overrides this)
15384: {
15385:     $deftex = LONCAPA::texengine();
15386: }
15387: 
15388: # ------------- set default minimum length for passwords for internal auth users
15389: {
15390:     $passwdmin = LONCAPA::passwd_min();
15391: }
15392: 
15393: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
15394: 				'compress_threshold'=> 20_000,
15395:  			        });
15396: 
15397: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
15398: $dumpcount=0;
15399: $locknum=0;
15400: 
15401: &logtouch();
15402: &logthis('<font color="yellow">INFO: Read configuration</font>');
15403: $readit=1;
15404:     {
15405: 	use integer;
15406: 	my $test=(2**32)+1;
15407: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
15408: 	&logthis(" Detected 64bit platform ($_64bit)");
15409:     }
15410: }
15411: }
15412: 
15413: 1;
15414: __END__
15415: 
15416: =pod
15417: 
15418: =head1 NAME
15419: 
15420: Apache::lonnet - Subroutines to ask questions about things in the network.
15421: 
15422: =head1 SYNOPSIS
15423: 
15424: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
15425: 
15426:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15427: 
15428: Common parameters:
15429: 
15430: =over 4
15431: 
15432: =item *
15433: 
15434: $uname : an internal username (if $cname expecting a course Id specifically)
15435: 
15436: =item *
15437: 
15438: $udom : a domain (if $cdom expecting a course's domain specifically)
15439: 
15440: =item *
15441: 
15442: $symb : a resource instance identifier
15443: 
15444: =item *
15445: 
15446: $namespace : the name of a .db file that contains the data needed or
15447: being set.
15448: 
15449: =back
15450: 
15451: =head1 OVERVIEW
15452: 
15453: lonnet provides subroutines which interact with the
15454: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15455: about classes, users, and resources.
15456: 
15457: For many of these objects you can also use this to store data about
15458: them or modify them in various ways.
15459: 
15460: =head2 Symbs
15461: 
15462: To identify a specific instance of a resource, LON-CAPA uses symbols
15463: or "symbs"X<symb>. These identifiers are built from the URL of the
15464: map, the resource number of the resource in the map, and the URL of
15465: the resource itself. The latter is somewhat redundant, but might help
15466: if maps change.
15467: 
15468: An example is
15469: 
15470:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15471: 
15472: The respective map entry is
15473: 
15474:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
15475:   title="Problem 2">
15476:  </resource>
15477: 
15478: Symbs are used by the random number generator, as well as to store and
15479: restore data specific to a certain instance of for example a problem.
15480: 
15481: =head2 Storing And Retrieving Data
15482: 
15483: X<store()>X<cstore()>X<restore()>Three of the most important functions
15484: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15485: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15486: is is the non-critical message twin of cstore. These functions are for
15487: handlers to store a perl hash to a user's permanent data space in an
15488: easy manner, and to retrieve it again on another call. It is expected
15489: that a handler would use this once at the beginning to retrieve data,
15490: and then again once at the end to send only the new data back.
15491: 
15492: The data is stored in the user's data directory on the user's
15493: homeserver under the ID of the course.
15494: 
15495: The hash that is returned by restore will have all of the previous
15496: value for all of the elements of the hash.
15497: 
15498: Example:
15499: 
15500:  #creating a hash
15501:  my %hash;
15502:  $hash{'foo'}='bar';
15503: 
15504:  #storing it
15505:  &Apache::lonnet::cstore(\%hash);
15506: 
15507:  #changing a value
15508:  $hash{'foo'}='notbar';
15509: 
15510:  #adding a new value
15511:  $hash{'bar'}='foo';
15512:  &Apache::lonnet::cstore(\%hash);
15513: 
15514:  #retrieving the hash
15515:  my %history=&Apache::lonnet::restore();
15516: 
15517:  #print the hash
15518:  foreach my $key (sort(keys(%history))) {
15519:    print("\%history{$key} = $history{$key}");
15520:  }
15521: 
15522: Will print out:
15523: 
15524:  %history{1:foo} = bar
15525:  %history{1:keys} = foo:timestamp
15526:  %history{1:timestamp} = 990455579
15527:  %history{2:bar} = foo
15528:  %history{2:foo} = notbar
15529:  %history{2:keys} = foo:bar:timestamp
15530:  %history{2:timestamp} = 990455580
15531:  %history{bar} = foo
15532:  %history{foo} = notbar
15533:  %history{timestamp} = 990455580
15534:  %history{version} = 2
15535: 
15536: Note that the special hash entries C<keys>, C<version> and
15537: C<timestamp> were added to the hash. C<version> will be equal to the
15538: total number of versions of the data that have been stored. The
15539: C<timestamp> attribute will be the UNIX time the hash was
15540: stored. C<keys> is available in every historical section to list which
15541: keys were added or changed at a specific historical revision of a
15542: hash.
15543: 
15544: B<Warning>: do not store the hash that restore returns directly. This
15545: will cause a mess since it will restore the historical keys as if the
15546: were new keys. I.E. 1:foo will become 1:1:foo etc.
15547: 
15548: Calling convention:
15549: 
15550:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
15551:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
15552: 
15553: For more detailed information, see lonnet specific documentation.
15554: 
15555: =head1 RETURN MESSAGES
15556: 
15557: =over 4
15558: 
15559: =item * B<con_lost>: unable to contact remote host
15560: 
15561: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15562: when the connection is brought back up
15563: 
15564: =item * B<con_failed>: unable to contact remote host and unable to save message
15565: for later delivery
15566: 
15567: =item * B<error:>: an error a occurred, a description of the error follows the :
15568: 
15569: =item * B<no_such_host>: unable to fund a host associated with the user/domain
15570: that was requested
15571: 
15572: =back
15573: 
15574: =head1 PUBLIC SUBROUTINES
15575: 
15576: =head2 Session Environment Functions
15577: 
15578: =over 4
15579: 
15580: =item * 
15581: X<appenv()>
15582: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
15583: the user envirnoment file, and will be restored for each access this
15584: user makes during this session, also modifies the %env for the current
15585: process. Optional rolesarrayref - if defined contains a reference to an array
15586: of roles which are exempt from the restriction on modifying user.role entries 
15587: in the user's environment.db and in %env.    
15588: 
15589: =item *
15590: X<delenv()>
15591: B<delenv($delthis,$regexp)>: removes all items from the session
15592: environment file that begin with $delthis. If the 
15593: optional second arg - $regexp - is true, $delthis is treated as a 
15594: regular expression, otherwise \Q$delthis\E is used. 
15595: The values are also deleted from the current processes %env.
15596: 
15597: =item * get_env_multiple($name) 
15598: 
15599: gets $name from the %env hash, it seemlessly handles the cases where multiple
15600: values may be defined and end up as an array ref.
15601: 
15602: returns an array of values
15603: 
15604: =back
15605: 
15606: =head2 User Information
15607: 
15608: =over 4
15609: 
15610: =item *
15611: X<queryauthenticate()>
15612: B<queryauthenticate($uname,$udom)>: try to determine user's current 
15613: authentication scheme
15614: 
15615: =item *
15616: X<authenticate()>
15617: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
15618: authenticate user from domain's lib servers (first use the current
15619: one). C<$upass> should be the users password.
15620: $checkdefauth is optional (value is 1 if a check should be made to
15621:    authenticate user using default authentication method, and allow
15622:    account creation if username does not have account in the domain).
15623: $clientcancheckhost is optional (value is 1 if checking whether the
15624:    server can host will occur on the client side in lonauth.pm).   
15625: 
15626: =item *
15627: X<homeserver()>
15628: B<homeserver($uname,$udom)>: find the server which has
15629: the user's directory and files (there must be only one), this caches
15630: the answer, and also caches if there is a borken connection.
15631: 
15632: =item *
15633: X<idget()>
15634: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
15635: a list of student/employee IDs or clicker IDs
15636: (student/employee IDs are a unique resource in a domain, there must be 
15637: only 1 ID per username, and only 1 username per ID in a specific domain).
15638: clickerIDs are not necessarily unique, as students might share clickers.
15639: (returns hash: id=>name,id=>name)
15640: 
15641: =item *
15642: X<idrget()>
15643: B<idrget($udom,@unames)>: find the IDs behind a list of
15644: usernames (returns hash: name=>id,name=>id)
15645: 
15646: =item *
15647: X<idput()>
15648: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
15649: names and associated student/employee IDs or clicker IDs.
15650: 
15651: =item *
15652: X<iddel()>
15653: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
15654: student/employee ID or clicker ID username look-ups from domain.
15655: The homeserver ($uhome) and namespace ($namespace) are optional.
15656: If no $uhome is provided, it will be determined usig &homeserver()
15657: for each user.  If no $namespace is provided, the default is ids.
15658: 
15659: =item *
15660: X<updateclickers()>
15661: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
15662: clicker ID-to-username look-ups in clickers.db on library server.
15663: Permitted actions are add or del (i.e., add or delete). The 
15664: clickers.db contains clickerID as keys (escaped), and each corresponding
15665: value is an escaped comma-separated list of usernames (for whom the
15666: library server is the homeserver), who registered that particular ID.
15667: If $critical is true, the update will be sent via &critical, otherwise
15668: &reply() will be used.
15669: 
15670: =item *
15671: X<rolesinit()>
15672: B<rolesinit($udom,$username)>: get user privileges.
15673: returns user role, first access and timer interval hashes
15674: 
15675: =item *
15676: X<privileged()>
15677: B<privileged($username,$domain)>: returns a true if user has a
15678: privileged and active role (i.e. su or dc), false otherwise.
15679: 
15680: =item *
15681: X<getsection()>
15682: B<getsection($udom,$uname,$cname)>: finds the section of student in the
15683: course $cname, return section name/number or '' for "not in course"
15684: and '-1' for "no section"
15685: 
15686: =item *
15687: X<userenvironment()>
15688: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
15689: passed in @what from the requested user's environment, returns a hash
15690: 
15691: =item * 
15692: X<userlog_query()>
15693: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15694: activity.log file. %filters defines filters applied when parsing the
15695: log file. These can be start or end timestamps, or the type of action
15696: - log to look for Login or Logout events, check for Checkin or
15697: Checkout, role for role selection. The response is in the form
15698: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
15699: escaped strings of the action recorded in the activity.log file.
15700: 
15701: =back
15702: 
15703: =head2 User Roles
15704: 
15705: =over 4
15706: 
15707: =item *
15708: 
15709: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
15710: returns codes for allowed actions.
15711: 
15712: The first argument is required, all others are optional.
15713: 
15714: $priv is the privilege being checked.
15715: $uri contains additional information about what is being checked for access (e.g.,
15716: URL, course ID etc.). 
15717: $symb is the unique resource instance identifier in a course; if needed,
15718: but not provided, it will be retrieved via a call to &symbread(). 
15719: $role is the role for which a priv is being checked (only used if priv is evb). 
15720: $clientip is the user's IP address (only used when checking for access to portfolio 
15721: files).
15722: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
15723: prevents recursive calls to &allowed.
15724: 
15725:  F: full access
15726:  U,I,K: authentication modes (cxx only)
15727:  '': forbidden
15728:  1: user needs to choose course
15729:  2: browse allowed
15730:  A: passphrase authentication needed
15731:  B: access temporarily blocked because of a blocking event in a course.
15732:  D: access blocked because access is required via session initiated via deep-link 
15733: 
15734: =item *
15735: 
15736: constructaccess($url,$setpriv) : check for access to construction space URL
15737: 
15738: See if the owner domain and name in the URL match those in the
15739: expected environment.  If so, return three element list
15740: ($ownername,$ownerdomain,$ownerhome).
15741: 
15742: Otherwise return the null string.
15743: 
15744: If second argument 'setpriv' is true, it assigns the privileges,
15745: and returns the same three element list, unless the owner has
15746: blocked "ad hoc" Domain Coordinator access to the Author Space,
15747: in which case the null string is returned.
15748: 
15749: =item *
15750: 
15751: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15752: define a custom role rolename set privileges in format of lonTabs/roles.tab
15753: for system, domain, and course level. $uname and $udom are optional (current
15754: user's username and domain will be used when either of $uname or $udom are absent.
15755: 
15756: =item *
15757: 
15758: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
15759: (rolesplain.tab); plain text explanation of a user role term.
15760: $type is Course (default) or Community.
15761: If $forcedefault evaluates to true, text returned will be default 
15762: text for $type. Otherwise, if this is a course, the text returned 
15763: will be a custom name for the role (if defined in the course's 
15764: environment).  If no custom name is defined the default is returned.
15765:    
15766: =item *
15767: 
15768: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
15769: All arguments are optional. Returns a hash of a roles, either for
15770: co-author/assistant author roles for a user's Construction Space
15771: (default), or if $context is 'userroles', roles for the user himself,
15772: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15773: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15774: For each key, value is set to colon-separated start and end times for
15775: the role.  If no username and domain are specified, will default to
15776: current user/domain. Types, roles, and roledoms are references to arrays
15777: of role statuses (active, future or previous), roles 
15778: (e.g., cc,in, st etc.) and domains of the roles which can be used
15779: to restrict the list of roles reported. If no array ref is 
15780: provided for types, will default to return only active roles.
15781: 
15782: =item *
15783: 
15784: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
15785: user: $uname:$udom has a role in the course: $cdom_$cnum. 
15786: 
15787: Additional optional arguments are: $type (if role checking is to be restricted 
15788: to certain user status types -- previous (expired roles), active (currently
15789: available roles) or future (roles available in the future), and
15790: $hideprivileged -- if true will not report course roles for users who
15791: have active Domain Coordinator role in course's domain or in additional
15792: domains (specified in 'Domains to check for privileged users' in course
15793: environment -- set via:  Course Settings -> Classlists and staff listing).
15794: 
15795: =item *
15796: 
15797: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15798: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15799: $possdomains and $possroles are optional array refs -- to domains to check and
15800: roles to check.  If $possdomains is not specified, a dump will be done of the
15801: users' roles.db to check for a dc or su role in any domain. This can be
15802: time consuming if &privileged is called repeatedly (e.g., when displaying a
15803: classlist), so in such cases, supplying a $possdomains array is preferred, as
15804: this then allows &privileged_by_domain() to be used, which caches the identity
15805: of privileged users, eliminating the need for repeated calls to &dump().
15806: 
15807: =item *
15808: 
15809: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15810: where the outer hash keys are domains specified in the $possdomains array ref,
15811: next inner hash keys are privileged roles specified in the $roles array ref,
15812: and the innermost hash contains key = value pairs for username:domain = end:start
15813: for active or future "privileged" users with that role in that domain. To avoid
15814: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15815: innerhash are cached using priv_$role and $dom as the identifiers.
15816: 
15817: =back
15818: 
15819: =head2 User Modification
15820: 
15821: =over 4
15822: 
15823: =item *
15824: 
15825: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
15826: user for the level given by URL.  Optional start and end dates (leave empty
15827: string or zero for "no date")
15828: 
15829: =item *
15830: 
15831: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15832: change a users, password, possible return values are: ok,
15833: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15834: refused
15835: 
15836: =item *
15837: 
15838: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
15839: 
15840: =item *
15841: 
15842: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15843:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
15844: 
15845: will update user information (firstname,middlename,lastname,generation,
15846: permanentemail), and if forceid is true, student/employee ID also.
15847: A user's institutional affiliation(s) can also be updated.
15848: User information fields will not be overwritten with empty entries 
15849: unless the field is included in the $candelete array reference.
15850: This array is included when a single user is modified via "Manage Users",
15851: or when Autoupdate.pl is run by cron in a domain.
15852: 
15853: =item *
15854: 
15855: modifystudent
15856: 
15857: modify a student's enrollment and identification information.
15858: The course id is resolved based on the current user's environment.  
15859: This means the invoking user must be a course coordinator or otherwise
15860: associated with a course.
15861: 
15862: This call is essentially a wrapper for lonnet::modifyuser and
15863: lonnet::modify_student_enrollment
15864: 
15865: Inputs: 
15866: 
15867: =over 4
15868: 
15869: =item B<$udom> Student's loncapa domain
15870: 
15871: =item B<$uname> Student's loncapa login name
15872: 
15873: =item B<$uid> Student/Employee ID
15874: 
15875: =item B<$umode> Student's authentication mode
15876: 
15877: =item B<$upass> Student's password
15878: 
15879: =item B<$first> Student's first name
15880: 
15881: =item B<$middle> Student's middle name
15882: 
15883: =item B<$last> Student's last name
15884: 
15885: =item B<$gene> Student's generation
15886: 
15887: =item B<$usec> Student's section in course
15888: 
15889: =item B<$end> Unix time of the roles expiration
15890: 
15891: =item B<$start> Unix time of the roles start date
15892: 
15893: =item B<$forceid> If defined, allow $uid to be changed
15894: 
15895: =item B<$desiredhome> server to use as home server for student
15896: 
15897: =item B<$email> Student's permanent e-mail address
15898: 
15899: =item B<$type> Type of enrollment (auto or manual)
15900: 
15901: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
15902: 
15903: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
15904: 
15905: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
15906: 
15907: =item B<$context> role change context (shown in User Management Logs display in a course)
15908: 
15909: =item B<$inststatus> institutional status of user - : separated string of escaped status types
15910: 
15911: =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.
15912: 
15913: =back
15914: 
15915: =item *
15916: 
15917: modify_student_enrollment
15918: 
15919: Change a student's enrollment status in a class.  The environment variable
15920: 'role.request.course' must be defined for this function to proceed.
15921: 
15922: Inputs:
15923: 
15924: =over 4
15925: 
15926: =item $udom, student's domain
15927: 
15928: =item $uname, student's name
15929: 
15930: =item $uid, student's user id
15931: 
15932: =item $first, student's first name
15933: 
15934: =item $middle
15935: 
15936: =item $last
15937: 
15938: =item $gene
15939: 
15940: =item $usec
15941: 
15942: =item $end
15943: 
15944: =item $start
15945: 
15946: =item $type
15947: 
15948: =item $locktype
15949: 
15950: =item $cid
15951: 
15952: =item $selfenroll
15953: 
15954: =item $context
15955: 
15956: =item $credits, number of credits student will earn from this class
15957: 
15958: =item $instsec, institutional course section code for student
15959: 
15960: =back
15961: 
15962: 
15963: =item *
15964: 
15965: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
15966: custom role; give a custom role to a user for the level given by URL.  Specify
15967: name and domain of role author, and role name
15968: 
15969: =item *
15970: 
15971: revokerole($udom,$uname,$url,$role) : revoke a role for url
15972: 
15973: =item *
15974: 
15975: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
15976: 
15977: =back
15978: 
15979: =head2 Course Infomation
15980: 
15981: =over 4
15982: 
15983: =item *
15984: 
15985: coursedescription($courseid,$options) : returns a hash of information about the
15986: specified course id, including all environment settings for the
15987: course, the description of the course will be in the hash under the
15988: key 'description'
15989: 
15990: $options is an optional parameter that if supplied is a hash reference that controls
15991: what how this function works.  It has the following key/values:
15992: 
15993: =over 4
15994: 
15995: =item freshen_cache
15996: 
15997: If defined, and the environment cache for the course is valid, it is 
15998: returned in the returned hash.
15999: 
16000: =item one_time
16001: 
16002: If defined, the last cache time is set to _now_
16003: 
16004: =item user
16005: 
16006: If defined, the supplied username is used instead of the current user.
16007: 
16008: 
16009: =back
16010: 
16011: =item *
16012: 
16013: resdata($name,$domain,$type,@which) : request for current parameter
16014: setting for a specific $type, where $type is either 'course' or 'user',
16015: @what should be a list of parameters to ask about. This routine caches
16016: answers for 10 minutes.
16017: 
16018: =item *
16019: 
16020: get_courseresdata($courseid, $domain) : dump the entire course resource
16021: data base, returning a hash that is keyed by the resource name and has
16022: values that are the resource value.  I believe that the timestamps and
16023: versions are also returned.
16024: 
16025: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16026: supplemental content area. This routine caches the number of files for 
16027: 10 minutes.
16028: 
16029: =back
16030: 
16031: =head2 Course Modification
16032: 
16033: =over 4
16034: 
16035: =item *
16036: 
16037: writecoursepref($courseid,%prefs) : write preferences (environment
16038: database) for a course
16039: 
16040: =item *
16041: 
16042: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16043: 
16044: =item *
16045: 
16046: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16047: 
16048: =item *
16049: 
16050: is_course($courseid), is_course($cdom, $cnum)
16051: 
16052: Accepts either a combined $courseid (in the form of domain_courseid) or the
16053: two component version $cdom, $cnum. It checks if the specified course exists.
16054: 
16055: Returns:
16056:     undef if the course doesn't exist, otherwise
16057:     in scalar context the combined courseid.
16058:     in list context the two components of the course identifier, domain and 
16059:     courseid.    
16060: 
16061: =back
16062: 
16063: =head2 Bubblesheet Configuration
16064: 
16065: =over 4
16066: 
16067: =item *
16068: 
16069: get_scantron_config($which)
16070: 
16071: $which - the name of the configuration to parse from the file.
16072: 
16073: Parses and returns the bubblesheet configuration line selected as a
16074: hash of configuration file fields.
16075: 
16076: 
16077: Returns:
16078:     If the named configuration is not in the file, an empty
16079:     hash is returned.
16080: 
16081:     a hash with the fields
16082:       name         - internal name for the this configuration setup
16083:       description  - text to display to operator that describes this config
16084:       CODElocation - if 0 or the string 'none'
16085:                           - no CODE exists for this config
16086:                      if -1 || the string 'letter'
16087:                           - a CODE exists for this config and is
16088:                             a string of letters
16089:                      Unsupported value (but planned for future support)
16090:                           if a positive integer
16091:                                - The CODE exists as the first n items from
16092:                                  the question section of the form
16093:                           if the string 'number'
16094:                                - The CODE exists for this config and is
16095:                                  a string of numbers
16096:       CODEstart   - (only matter if a CODE exists) column in the line where
16097:                      the CODE starts
16098:       CODElength  - length of the CODE
16099:       IDstart     - column where the student/employee ID starts
16100:       IDlength    - length of the student/employee ID info
16101:       Qstart      - column where the information from the bubbled
16102:                     'questions' start
16103:       Qlength     - number of columns comprising a single bubble line from
16104:                     the sheet. (usually either 1 or 10)
16105:       Qon         - either a single character representing the character used
16106:                     to signal a bubble was chosen in the positional setup, or
16107:                     the string 'letter' if the letter of the chosen bubble is
16108:                     in the final, or 'number' if a number representing the
16109:                     chosen bubble is in the file (1->A 0->J)
16110:       Qoff        - the character used to represent that a bubble was
16111:                     left blank
16112:       PaperID     - if the scanning process generates a unique number for each
16113:                     sheet scanned the column that this ID number starts in
16114:       PaperIDlength - number of columns that comprise the unique ID number
16115:                       for the sheet of paper
16116:       FirstName   - column that the first name starts in
16117:       FirstNameLength - number of columns that the first name spans
16118:       LastName    - column that the last name starts in
16119:       LastNameLength - number of columns that the last name spans
16120:       BubblesPerRow - number of bubbles available in each row used to
16121:                       bubble an answer. (If not specified, 10 assumed).
16122: 
16123: 
16124: =item *
16125: 
16126: get_scantronformat_file($cdom)
16127: 
16128: $cdom - the course's domain (optional); if not supplied, uses
16129: domain for current $env{'request.course.id'}.
16130: 
16131: Returns an array containing lines from the scantron format file for
16132: the domain of the course.
16133: 
16134: If a url for a custom.tab file is listed in domain's configuration.db,
16135: lines are from this file.
16136: 
16137: Otherwise, if a default.tab has been published in RES space by the
16138: domainconfig user, lines are from this file.
16139: 
16140: Otherwise, fall back to getting lines from the legacy file on the
16141: local server:  /home/httpd/lonTabs/default_scantronformat.tab
16142: 
16143: =back
16144: 
16145: =head2 Resource Subroutines
16146: 
16147: =over 4
16148: 
16149: =item *
16150: 
16151: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
16152: 
16153: =item *
16154: 
16155: repcopy($filename) : subscribes to the requested file, and attempts to
16156: replicate from the owning library server, Might return
16157: 'unavailable', 'not_found', 'forbidden', 'ok', or
16158: 'bad_request', also attempts to grab the metadata for the
16159: resource. Expects the local filesystem pathname
16160: (/home/httpd/html/res/....)
16161: 
16162: =back
16163: 
16164: =head2 Resource Information
16165: 
16166: =over 4
16167: 
16168: =item *
16169: 
16170: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
16171: and returns the value of a variety of different possible values,
16172: $varname should be a request string, and the other parameters can be
16173: used to specify who and what one is asking about. Ordinarily, $cid 
16174: does not need to be specified, as it is retrived from 
16175: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16176: within lonuserstate::loadmap() when initializing a course, before
16177: $env{'request.course.id'} has been set, so it needs to be provided
16178: in that one case.
16179: 
16180: Possible values for $varname are environment.lastname (or other item
16181: from the envirnment hash), user.name (or someother aspect about the
16182: user), resource.0.maxtries (or some other part and parameter of a
16183: resource)
16184: 
16185: =item *
16186: 
16187: directcondval($number) : get current value of a condition; reads from a state
16188: string
16189: 
16190: =item *
16191: 
16192: condval($condidx) : value of condition index based on state
16193: 
16194: =item *
16195: 
16196: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
16197: resource's metadata, $what should be either a specific key, or either
16198: 'keys' (to get a list of possible keys) or 'packages' to get a list of
16199: packages that this resource currently uses, the last 3 arguments are 
16200: only used internally for recursive metadata.
16201: 
16202: the toolsymb is only used where the uri is for an external tool (for which
16203: the uri as well as the symb are guaranteed to be unique).
16204: 
16205: this function automatically caches all requests except any made recursively
16206: to retrieve a list of metadata keys for an imported library file ($liburi is 
16207: defined).
16208: 
16209: =item *
16210: 
16211: metadata_query($query,$custom,$customshow) : make a metadata query against the
16212: network of library servers; returns file handle of where SQL and regex results
16213: will be stored for query
16214: 
16215: =item *
16216: 
16217: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
16218: return symbolic list entry (all arguments optional). 
16219: 
16220: Args: filename is the filename (including path) for the file for which a symb 
16221: is required; donotrecurse, if true will prevent calls to allowed() being made 
16222: to check access status if more than one resource was found in the bighash 
16223: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
16224: a randompick); ignorecachednull, if true will prevent a symb of '' being 
16225: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16226: cause possible symbs to be checked to determine if they are subject to content
16227: blocking, if so they will not be included as possible symbs; possibles is a
16228: ref to a hash, which, as a side effect, will be populated with all possible 
16229: symbs (content blocking not tested).
16230:  
16231: returns the data handle
16232: 
16233: =item *
16234: 
16235: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16236: and is a possible symb for the URL in $thisfn, and if is an encrypted
16237: resource that the user accessed using /enc/ returns a 1 on success, 0
16238: on failure, user must be in a course, as it assumes the existence of
16239: the course initial hash, and uses $env('request.course.id'}.  The third
16240: arg is an optional reference to a scalar.  If this arg is passed in the 
16241: call to symbverify, it will be set to 1 if the symb has been set to be 
16242: encrypted; otherwise it will be null.  
16243: 
16244: =item *
16245: 
16246: symbclean($symb) : removes versions numbers from a symb, returns the
16247: cleaned symb
16248: 
16249: =item *
16250: 
16251: is_on_map($uri) : checks if the $uri is somewhere on the current
16252: course map, user must be in a course for it to work.
16253: 
16254: =item *
16255: 
16256: numval($salt) : return random seed value (addend for rndseed)
16257: 
16258: =item *
16259: 
16260: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16261: a random seed, all arguments are optional, if they aren't sent it uses the
16262: environment to derive them. Note: if symb isn't sent and it can't get one
16263: from &symbread it will use the current time as its return value
16264: 
16265: =item *
16266: 
16267: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16268: unfakeable, receipt
16269: 
16270: =item *
16271: 
16272: receipt() : API to ireceipt working off of env values; given out to users
16273: 
16274: =item *
16275: 
16276: countacc($url) : count the number of accesses to a given URL
16277: 
16278: =item *
16279: 
16280: 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
16281: 
16282: =item *
16283: 
16284: 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)
16285: 
16286: =item *
16287: 
16288: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
16289: 
16290: =item *
16291: 
16292: devalidate($symb) : devalidate temporary spreadsheet calculations,
16293: forcing spreadsheet to reevaluate the resource scores next time.
16294: 
16295: =item * 
16296: 
16297: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16298: when viewing in course context.
16299: 
16300:  input: six args -- filename (decluttered), course number, course domain,
16301:                     url, symb (if registered) and group (if this is a 
16302:                     group item -- e.g., bulletin board, group page etc.).
16303: 
16304:  output: array of five scalars --
16305:          $cfile -- url for file editing if editable on current server
16306:          $home -- homeserver of resource (i.e., for author if published,
16307:                                           or course if uploaded.).
16308:          $switchserver --  1 if server switch will be needed.
16309:          $forceedit -- 1 if icon/link should be to go to edit mode 
16310:          $forceview -- 1 if icon/link should be to go to view mode
16311: 
16312: =item *
16313: 
16314: is_course_upload($file,$cnum,$cdom)
16315: 
16316: Used in course context to determine if current file was uploaded to 
16317: the course (i.e., would be found in /userfiles/docs on the course's 
16318: homeserver.
16319: 
16320:   input: 3 args -- filename (decluttered), course number and course domain.
16321:   output: boolean -- 1 if file was uploaded.
16322: 
16323: =back
16324: 
16325: =head2 Storing/Retreiving Data
16326: 
16327: =over 4
16328: 
16329: =item *
16330: 
16331: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16332: permanently for this url; hashref needs to be given and should be a \%hashname;
16333: the remaining args aren't required and if they aren't passed or are '' they will
16334: be derived from the env (with the exception of $laststore, which is an 
16335: optional arg used when a user's submission is stored in grading).
16336: $laststore is $version=$timestamp, where $version is the most recent version
16337: number retrieved for the corresponding $symb in the $namespace db file, and
16338: $timestamp is the timestamp for that transaction (UNIX time).
16339: $laststore is currently only passed when cstore() is called by 
16340: structuretags::finalize_storage().
16341: 
16342: =item *
16343: 
16344: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16345: but uses critical subroutine
16346: 
16347: =item *
16348: 
16349: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16350: all args are optional
16351: 
16352: =item *
16353: 
16354: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
16355: dumps the complete (or key matching regexp) namespace into a hash
16356: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16357: normally &store()ed into
16358: 
16359: $range should be either an integer '100' (give me the first 100
16360:                                            matching records)
16361:               or be  two integers sperated by a - with no spaces
16362:                  '30-50' (give me the 30th through the 50th matching
16363:                           records)
16364: 
16365: 
16366: =item *
16367: 
16368: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
16369: replaces a &store() version of data with a replacement set of data
16370: for a particular resource in a namespace passed in the $storehash hash 
16371: reference. If $tolog is true, the transaction is logged in the courselog
16372: with an action=PUTSTORE.
16373: 
16374: =item *
16375: 
16376: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16377: works very similar to store/cstore, but all data is stored in a
16378: temporary location and can be reset using tmpreset, $storehash should
16379: be a hash reference, returns nothing on success
16380: 
16381: =item *
16382: 
16383: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16384: similar to restore, but all data is stored in a temporary location and
16385: can be reset using tmpreset. Returns a hash of values on success,
16386: error string otherwise.
16387: 
16388: =item *
16389: 
16390: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16391: deltes all keys for $symb form the temporary storage hash.
16392: 
16393: =item *
16394: 
16395: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16396: reference filled in from namesp ($udom and $uname are optional)
16397: 
16398: =item *
16399: 
16400: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16401: namesp ($udom and $uname are optional)
16402: 
16403: =item *
16404: 
16405: dump($namespace,$udom,$uname,$regexp,$range) : 
16406: dumps the complete (or key matching regexp) namespace into a hash
16407: ($udom, $uname, $regexp, $range are optional)
16408: 
16409: $range should be either an integer '100' (give me the first 100
16410:                                            matching records)
16411:               or be  two integers sperated by a - with no spaces
16412:                  '30-50' (give me the 30th through the 50th matching
16413:                           records)
16414: =item *
16415: 
16416: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16417: $store can be a scalar, an array reference, or if the amount to be 
16418: incremented is > 1, a hash reference.
16419: 
16420: ($udom and $uname are optional)
16421: 
16422: =item *
16423: 
16424: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16425: ($udom and $uname are optional)
16426: 
16427: =item *
16428: 
16429: cput($namespace,$storehash,$udom,$uname) : critical put
16430: ($udom and $uname are optional)
16431: 
16432: =item *
16433: 
16434: newput($namespace,$storehash,$udom,$uname) :
16435: 
16436: Attempts to store the items in the $storehash, but only if they don't
16437: currently exist, if this succeeds you can be certain that you have 
16438: successfully created a new key value pair in the $namespace db.
16439: 
16440: 
16441: Args:
16442:  $namespace: name of database to store values to
16443:  $storehash: hashref to store to the db
16444:  $udom: (optional) domain of user containing the db
16445:  $uname: (optional) name of user caontaining the db
16446: 
16447: Returns:
16448:  'ok' -> succeeded in storing all keys of $storehash
16449:  'key_exists: <key>' -> failed to anything out of $storehash, as at
16450:                         least <key> already existed in the db (other
16451:                         requested keys may also already exist)
16452:  'error: <msg>' -> unable to tie the DB or other error occurred
16453:  'con_lost' -> unable to contact request server
16454:  'refused' -> action was not allowed by remote machine
16455: 
16456: 
16457: =item *
16458: 
16459: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16460: reference filled in from namesp (encrypts the return communication)
16461: ($udom and $uname are optional)
16462: 
16463: =item *
16464: 
16465: log($udom,$name,$home,$message) : write to permanent log for user; use
16466: critical subroutine
16467: 
16468: =item *
16469: 
16470: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16471: array reference filled in from namespace found in domain level on either
16472: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
16473: 
16474: =item *
16475: 
16476: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
16477: domain level either on specified domain server ($uhome) or primary domain 
16478: server ($udom and $uhome are optional)
16479: 
16480: =item * 
16481: 
16482: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
16483: for: authentication, language, quotas, timezone, date locale, and portal URL in
16484: the target domain.
16485: 
16486: May also include additional key => value pairs for the following groups:
16487: 
16488: =over
16489: 
16490: =item
16491: disk quotas (MB allocated by default to portfolios and authoring spaces).
16492: 
16493: =over
16494: 
16495: =item defaultquota, authorquota
16496: 
16497: =back
16498: 
16499: =item
16500: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16501: portfolio for users).
16502: 
16503: =over
16504: 
16505: =item
16506: aboutme, blog, webdav, portfolio
16507: 
16508: =back
16509: 
16510: =item
16511: requestcourses: ability to request courses, and how requests are processed.
16512: 
16513: =over
16514: 
16515: =item
16516: official, unofficial, community, textbook, placement
16517: 
16518: =back
16519: 
16520: =item
16521: inststatus: types of institutional affiliation, and order in which they are displayed.
16522: 
16523: =over
16524: 
16525: =item
16526: inststatustypes, inststatusorder, inststatusguest
16527: 
16528: =back
16529: 
16530: =item
16531: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16532: for course's uploaded content.
16533: 
16534: =over
16535: 
16536: =item
16537: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
16538: communityquota, textbookquota, placementquota
16539: 
16540: =back
16541: 
16542: =item
16543: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16544: on your servers.
16545: 
16546: =over
16547: 
16548: =item 
16549: remotesessions, hostedsessions
16550: 
16551: =back
16552: 
16553: =back
16554: 
16555: In cases where a domain coordinator has never used the "Set Domain Configuration"
16556: utility to create a configuration.db file on a domain's primary library server 
16557: only the following domain defaults: auth_def, auth_arg_def, lang_def
16558: -- corresponding values are authentication type (internal, krb4, krb5,
16559: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
16560: will be available. Values are retrieved from cache (if current), unless the
16561: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16562: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16563: 
16564: Typical usage:
16565: 
16566: %domdefaults = &get_domain_defaults($target_domain);
16567: 
16568: =back
16569: 
16570: =head2 Network Status Functions
16571: 
16572: =over 4
16573: 
16574: =item *
16575: 
16576: dirlist() : return directory list based on URI (first arg).
16577: 
16578: Inputs: 1 required, 5 optional.
16579: 
16580: =over
16581: 
16582: =item 
16583: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16584: 
16585: =item
16586: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
16587: 
16588: =item
16589: $username -  username of user/course to be listed. Extracted from $uri if absent. 
16590: 
16591: =item
16592: $getpropath - boolean: 1 if prepend path using &propath(). 
16593: 
16594: =item
16595: $getuserdir - boolean: 1 if prepend path for "userfiles".
16596: 
16597: =item 
16598: $alternateRoot - path to prepend in place of path from $uri.
16599: 
16600: =back
16601: 
16602: Returns: Array of up to two items.
16603: 
16604: =over
16605: 
16606: a reference to an array of files/subdirectories
16607: 
16608: =over
16609: 
16610: Each element in the array of files/subdirectories is a & separated list of
16611: item name and the result of running stat on the item.  If dirlist was requested
16612: for a file instead of a directory, the item name will be ''. For a directory 
16613: listing, if the item is a metadata file, the element will end &N&M 
16614: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16615: default copyright set (1).  
16616: 
16617: =back
16618: 
16619: a scalar containing error condition (if encountered).
16620: 
16621: =over
16622: 
16623: =item 
16624: no_host (no homeserver identified for $username:$domain).
16625: 
16626: =item 
16627: no_such_host (server contacted for listing not identified as valid host).
16628: 
16629: =item 
16630: con_lost (connection to remote server failed).
16631: 
16632: =item 
16633: refused (invalid $username:$domain received on lond side).
16634: 
16635: =item 
16636: no_such_dir (directory at specified path on lond side does not exist). 
16637: 
16638: =item 
16639: empty (directory at specified path on lond side is empty).
16640: 
16641: =over
16642: 
16643: This is currently not encountered because the &ls3, &ls2, 
16644: &ls (_handler) routines on the lond side do not filter out
16645: . and .. from a directory listing. 
16646: 
16647: =back
16648: 
16649: =back
16650: 
16651: =back
16652: 
16653: =item *
16654: 
16655: spareserver() : find server with least workload from spare.tab
16656: 
16657: 
16658: =item *
16659: 
16660: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16661: if there is no corresponding loncapa host.
16662: 
16663: =back
16664: 
16665: 
16666: =head2 Apache Request
16667: 
16668: =over 4
16669: 
16670: =item *
16671: 
16672: ssi($url,%hash) : server side include, does a complete request cycle on url to
16673: localhost, posts hash
16674: 
16675: =back
16676: 
16677: =head2 Data to String to Data
16678: 
16679: =over 4
16680: 
16681: =item *
16682: 
16683: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16684: and '&' separators, supports elements that are arrayrefs and hashrefs
16685: 
16686: =item *
16687: 
16688: hashref2str($hashref) : convert a hashref into a string complete with
16689: escaping and '=' and '&' separators, supports elements that are
16690: arrayrefs and hashrefs
16691: 
16692: =item *
16693: 
16694: arrayref2str($arrayref) : convert an arrayref into a string complete
16695: with escaping and '&' separators, supports elements that are arrayrefs
16696: and hashrefs
16697: 
16698: =item *
16699: 
16700: str2hash($string) : convert string to hash using unescaping and
16701: splitting on '=' and '&', supports elements that are arrayrefs and
16702: hashrefs
16703: 
16704: =item *
16705: 
16706: str2array($string) : convert string to hash using unescaping and
16707: splitting on '&', supports elements that are arrayrefs and hashrefs
16708: 
16709: =back
16710: 
16711: =head2 Logging Routines
16712: 
16713: 
16714: These routines allow one to make log messages in the lonnet.log and
16715: lonnet.perm logfiles.
16716: 
16717: =over 4
16718: 
16719: =item *
16720: 
16721: logtouch() : make sure the logfile, lonnet.log, exists
16722: 
16723: =item *
16724: 
16725: logthis() : append message to the normal lonnet.log file, it gets
16726: preiodically rolled over and deleted.
16727: 
16728: =item *
16729: 
16730: logperm() : append a permanent message to lonnet.perm.log, this log
16731: file never gets deleted by any automated portion of the system, only
16732: messages of critical importance should go in here.
16733: 
16734: 
16735: =back
16736: 
16737: =head2 General File Helper Routines
16738: 
16739: =over 4
16740: 
16741: =item *
16742: 
16743: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16744: (a) files in /uploaded
16745:   (i) If a local copy of the file exists - 
16746:       compares modification date of local copy with last-modified date for 
16747:       definitive version stored on home server for course. If local copy is 
16748:       stale, requests a new version from the home server and stores it. 
16749:       If the original has been removed from the home server, then local copy 
16750:       is unlinked.
16751:   (ii) If local copy does not exist -
16752:       requests the file from the home server and stores it. 
16753:   
16754:   If $caller is 'uploadrep':  
16755:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16756:     for request for files originally uploaded via DOCS. 
16757:      - returns 'ok' if fresh local copy now available, -1 otherwise.
16758:   
16759:   Otherwise:
16760:      This indicates a call from the content generation phase of the request.
16761:      -  returns the entire contents of the file or -1.
16762:      
16763: (b) files in /res
16764:    - returns the entire contents of a file or -1; 
16765:    it properly subscribes to and replicates the file if neccessary.
16766: 
16767: 
16768: =item *
16769: 
16770: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16771:                   reference
16772: 
16773: returns either a stat() list of data about the file or an empty list
16774: if the file doesn't exist or couldn't find out about it (connection
16775: problems or user unknown)
16776: 
16777: =item *
16778: 
16779: filelocation($dir,$file) : returns file system location of a file
16780: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16781: directory that relative $file lookups are to looked in ($dir of /a/dir
16782: and a file of ../bob will become /a/bob)
16783: 
16784: =item *
16785: 
16786: hreflocation($dir,$file) : returns file system location or a URL; same as
16787: filelocation except for hrefs
16788: 
16789: =item *
16790: 
16791: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16792: also removes beginning /home/httpd/html unless /priv/ follows it.
16793: 
16794: =back
16795: 
16796: =head2 Usererfile file routines (/uploaded*)
16797: 
16798: =over 4
16799: 
16800: =item *
16801: 
16802: userfileupload(): main rotine for putting a file in a user or course's
16803:                   filespace, arguments are,
16804: 
16805:  formname - required - this is the name of the element in $env where the
16806:            filename, and the contents of the file to create/modifed exist
16807:            the filename is in $env{'form.'.$formname.'.filename'} and the
16808:            contents of the file is located in $env{'form.'.$formname}
16809:  context - if coursedoc, store the file in the course of the active role
16810:              of the current user; 
16811:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16812:            if 'canceloverwrite': delete file in tmp/overwrites directory
16813:  subdir - required - subdirectory to put the file in under ../userfiles/
16814:          if undefined, it will be placed in "unknown"
16815: 
16816:  (This routine calls clean_filename() to remove any dangerous
16817:  characters from the filename, and then calls finuserfileupload() to
16818:  complete the transaction)
16819: 
16820:  returns either the url of the uploaded file (/uploaded/....) if successful
16821:  and /adm/notfound.html if unsuccessful
16822: 
16823: =item *
16824: 
16825: clean_filename(): routine for cleaing a filename up for storage in
16826:                  userfile space, argument is:
16827: 
16828:  filename - proposed filename
16829: 
16830: returns: the new clean filename
16831: 
16832: =item *
16833: 
16834: finishuserfileupload(): routine that creates and sends the file to
16835: userspace, probably shouldn't be called directly
16836: 
16837:   docuname: username or courseid of destination for the file
16838:   docudom: domain of user/course of destination for the file
16839:   formname: same as for userfileupload()
16840:   fname: filename (including subdirectories) for the file
16841:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
16842:           if hashref, and context is scantron, will convert csv format to standard format
16843:   allfiles: reference to hash used to store objects found by parser
16844:   codebase: reference to hash used for codebases of java objects found by parser
16845:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16846:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
16847:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
16848:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
16849:   context: if 'overwrite', will move the uploaded file from its temporary location to
16850:             userfiles to facilitate overwriting a previously uploaded file with same name.
16851:   mimetype: reference to scalar to accommodate mime type determined
16852:             from File::MMagic if $parser = parse.
16853: 
16854:  returns either the url of the uploaded file (/uploaded/....) if successful
16855:  and /adm/notfound.html if unsuccessful (or an error message if context 
16856:  was 'overwrite').
16857:  
16858: 
16859: =item *
16860: 
16861: renameuserfile(): renames an existing userfile to a new name
16862: 
16863:   Args:
16864:    docuname: username or courseid of destination for the file
16865:    docudom: domain of user/course of destination for the file
16866:    old: current file name (including any subdirs under userfiles)
16867:    new: desired file name (including any subdirs under userfiles)
16868: 
16869: =item *
16870: 
16871: mkdiruserfile(): creates a directory is a userfiles dir
16872: 
16873:   Args:
16874:    docuname: username or courseid of destination for the file
16875:    docudom: domain of user/course of destination for the file
16876:    dir: dir to create (including any subdirs under userfiles)
16877: 
16878: =item *
16879: 
16880: removeuserfile(): removes a file that exists in userfiles
16881: 
16882:   Args:
16883:    docuname: username or courseid of destination for the file
16884:    docudom: domain of user/course of destination for the file
16885:    fname: filname to delete (including any subdirs under userfiles)
16886: 
16887: =item *
16888: 
16889: removeuploadedurl(): convience function for removeuserfile()
16890: 
16891:   Args:
16892:    url:  a full /uploaded/... url to delete
16893: 
16894: =item * 
16895: 
16896: get_portfile_permissions():
16897:   Args:
16898:     domain: domain of user or course contain the portfolio files
16899:     user: name of user or num of course contain the portfolio files
16900:   Returns:
16901:     hashref of a dump of the proper file_permissions.db
16902:    
16903: 
16904: =item * 
16905: 
16906: get_access_controls():
16907: 
16908: Args:
16909:   current_permissions: the hash ref returned from get_portfile_permissions()
16910:   group: (optional) the group you want the files associated with
16911:   file: (optional) the file you want access info on
16912: 
16913: Returns:
16914:     a hash (keys are file names) of hashes containing
16915:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
16916:         values are XML containing access control settings (see below) 
16917: 
16918: Internal notes:
16919: 
16920:  access controls are stored in file_permissions.db as key=value pairs.
16921:     key -> path to file/file_name\0uniqueID:scope_end_start
16922:         where scope -> public,guest,course,group,domains or users.
16923:               end -> UNIX time for end of access (0 -> no end date)
16924:               start -> UNIX time for start of access
16925: 
16926:     value -> XML description of access control
16927:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
16928:             <start></start>
16929:             <end></end>
16930: 
16931:             <password></password>  for scope type = guest
16932: 
16933:             <domain></domain>     for scope type = course or group
16934:             <number></number>
16935:             <roles id="">
16936:              <role></role>
16937:              <access></access>
16938:              <section></section>
16939:              <group></group>
16940:             </roles>
16941: 
16942:             <dom></dom>         for scope type = domains
16943: 
16944:             <users>             for scope type = users
16945:              <user>
16946:               <uname></uname>
16947:               <udom></udom>
16948:              </user>
16949:             </users>
16950:            </scope> 
16951:               
16952:  Access data is also aggregated for each file in an additional key=value pair:
16953:  key -> path to file/file_name\0accesscontrol 
16954:  value -> reference to hash
16955:           hash contains key = value pairs
16956:           where key = uniqueID:scope_end_start
16957:                 value = UNIX time record was last updated
16958: 
16959:           Used to improve speed of look-ups of access controls for each file.  
16960:  
16961:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
16962: 
16963: =item *
16964: 
16965: modify_access_controls():
16966: 
16967: Modifies access controls for a portfolio file
16968: Args
16969: 1. file name
16970: 2. reference to hash of required changes,
16971: 3. domain
16972: 4. username
16973:   where domain,username are the domain of the portfolio owner 
16974:   (either a user or a course) 
16975: 
16976: Returns:
16977: 1. result of additions or updates ('ok' or 'error', with error message). 
16978: 2. result of deletions ('ok' or 'error', with error message).
16979: 3. reference to hash of any new or updated access controls.
16980: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
16981:    key = integer (inbound ID)
16982:    value = uniqueID
16983: 
16984: =item *
16985: 
16986: get_timebased_id():
16987: 
16988: Attempts to get a unique timestamp-based suffix for use with items added to a 
16989: course via the Course Editor (e.g., folders, composite pages, 
16990: group bulletin boards).
16991: 
16992: Args: (first three required; six others optional)
16993: 
16994: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
16995:    docssequence, or name of group
16996: 
16997: 2. keyid (alphanumeric): name of temporary locking key in hash,
16998:    e.g., num, boardids
16999: 
17000: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17001:    file will be named nohist_namespace.db
17002: 
17003: 4. cdom: domain of course; default is current course domain from %env
17004: 
17005: 5. cnum: course number; default is current course number from %env
17006: 
17007: 6. idtype: set to concat if an additional digit is to be appended to the 
17008:    unix timestamp to form the suffix, if the plain timestamp is already
17009:    in use.  Default is to not do this, but simply increment the unix 
17010:    timestamp by 1 until a unique key is obtained.
17011: 
17012: 7. who: holder of locking key; defaults to user:domain for user.
17013: 
17014: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17015:    retrying); default is 3.
17016: 
17017: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17018: 
17019: Returns:
17020: 
17021: 1. suffix obtained (numeric)
17022: 
17023: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17024: 
17025: 3. error: contains (localized) error message if an error occurred.
17026: 
17027: 
17028: =back
17029: 
17030: =head2 HTTP Helper Routines
17031: 
17032: =over 4
17033: 
17034: =item *
17035: 
17036: escape() : unpack non-word characters into CGI-compatible hex codes
17037: 
17038: =item *
17039: 
17040: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17041: 
17042: =back
17043: 
17044: =head1 PRIVATE SUBROUTINES
17045: 
17046: =head2 Underlying communication routines (Shouldn't call)
17047: 
17048: =over 4
17049: 
17050: =item *
17051: 
17052: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17053: 
17054: =item *
17055: 
17056: reply() : uses subreply to send a message to remote machine, logs all failures
17057: 
17058: =item *
17059: 
17060: critical() : passes a critical message to another server; if cannot
17061: get through then place message in connection buffer directory and
17062: returns con_delayed, if incapable of saving message, returns
17063: con_failed
17064: 
17065: =item *
17066: 
17067: reconlonc() : tries to reconnect lonc client processes.
17068: 
17069: =back
17070: 
17071: =head2 Resource Access Logging
17072: 
17073: =over 4
17074: 
17075: =item *
17076: 
17077: flushcourselogs() : flush (save) buffer logs and access logs
17078: 
17079: =item *
17080: 
17081: courselog($what) : save message for course in hash
17082: 
17083: =item *
17084: 
17085: courseacclog($what) : save message for course using &courselog().  Perform
17086: special processing for specific resource types (problems, exams, quizzes, etc).
17087: 
17088: =item *
17089: 
17090: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17091: as a PerlChildExitHandler
17092: 
17093: =back
17094: 
17095: =head2 Other
17096: 
17097: =over 4
17098: 
17099: =item *
17100: 
17101: symblist($mapname,%newhash) : update symbolic storage links
17102: 
17103: =back
17104: 
17105: =cut
17106: 

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