File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1389: download - view: text, annotated - select for diffs
Sat Nov 24 16:19:20 2018 UTC (5 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Domain config for load balancer to use cookie to record offload target.
  Subsequent requests by same user/browser will send requests to same target
  if remote session still active, and remote node not overloaded.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1389 2018/11/24 16:19:20 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$hostname,$context) = @_;
  234:     return if ($lonhost eq '');
  235:     if ($hostname eq '') {
  236:         $hostname = &hostname($lonhost);
  237:     }
  238:     return if ($hostname eq '');
  239:     my ($rep,$uselocal);
  240:     if ($context eq 'install') {
  241:         $uselocal = 1;
  242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  243:         $uselocal = 1;
  244:     }
  245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  247:         if ($distro eq '') {
  248:             $uselocal = 0;
  249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  250:             if ($1 < 6) {
  251:                 $uselocal = 0;
  252:             }
  253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  254:             if ($1 < 12) {
  255:                 $uselocal = 0;
  256:             }
  257:         }
  258:     }
  259:     if ($uselocal) {
  260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  261:     } else {
  262:         $rep=&reply('servercerts',$lonhost);
  263:     }
  264:     my ($result,%returnhash);
  265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  266:         ($rep eq 'unknown_cmd')) {
  267:         $result = $rep;
  268:     } else {
  269:         $result = 'ok';
  270:         my @pairs=split(/\&/,$rep);
  271:         foreach my $item (@pairs) {
  272:             my ($key,$value)=split(/=/,$item,2);
  273:             my $what = &unescape($key);
  274:             $returnhash{$what}=&thaw_unescape($value);
  275:         }
  276:     }
  277:     return ($result,\%returnhash);
  278: }
  279: 
  280: sub get_server_loncaparev {
  281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  282:     if (defined($lonhost)) {
  283:         if (!defined(&hostname($lonhost))) {
  284:             undef($lonhost);
  285:         }
  286:     }
  287:     if (!defined($lonhost)) {
  288:         if (defined(&domain($dom,'primary'))) {
  289:             $lonhost=&domain($dom,'primary');
  290:             if ($lonhost eq 'no_host') {
  291:                 undef($lonhost);
  292:             }
  293:         }
  294:     }
  295:     if (defined($lonhost)) {
  296:         my $cachetime = 12*3600;
  297:         if (!$ignore_cache) {
  298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  299:             if (defined($cached)) {
  300:                 return $loncaparev;
  301:             }
  302:         }
  303:         my ($answer,$loncaparev);
  304:         my @ids=&current_machine_ids();
  305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  306:             $answer = $perlvar{'lonVersion'};
  307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  308:                 $loncaparev = $1;
  309:             }
  310:         } else {
  311:             $answer = &reply('serverloncaparev',$lonhost);
  312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  313:                 if ($caller eq 'loncron') {
  314:                     my $protocol = $protocol{$lonhost};
  315:                     $protocol = 'http' if ($protocol ne 'https');
  316:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  317:                     my $request=new HTTP::Request('GET',$url);
  318:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  319:                     unless ($response->is_error()) {
  320:                         my $content = $response->content;
  321:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  322:                             $loncaparev = $1;
  323:                         }
  324:                     }
  325:                 } else {
  326:                     $loncaparev = $loncaparevs{$lonhost};
  327:                 }
  328:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  329:                 $loncaparev = $1;
  330:             }
  331:         }
  332:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  333:     }
  334: }
  335: 
  336: sub get_server_homeID {
  337:     my ($hostname,$ignore_cache,$caller) = @_;
  338:     unless ($ignore_cache) {
  339:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  340:         if (defined($cached)) {
  341:             return $serverhomeID;
  342:         }
  343:     }
  344:     my $cachetime = 12*3600;
  345:     my $serverhomeID;
  346:     if ($caller eq 'loncron') { 
  347:         my @machine_ids = &machine_ids($hostname);
  348:         foreach my $id (@machine_ids) {
  349:             my $response = &reply('serverhomeID',$id);
  350:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  351:                 $serverhomeID = $response;
  352:                 last;
  353:             }
  354:         }
  355:         if ($serverhomeID eq '') {
  356:             $serverhomeID = $machine_ids[-1];
  357:         }
  358:     } else {
  359:         $serverhomeID = $serverhomeIDs{$hostname};
  360:     }
  361:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  362: }
  363: 
  364: sub get_remote_globals {
  365:     my ($lonhost,$whathash,$ignore_cache) = @_;
  366:     my ($result,%returnhash,%whatneeded);
  367:     if (ref($whathash) eq 'HASH') {
  368:         foreach my $what (sort(keys(%{$whathash}))) {
  369:             my $hashid = $lonhost.'-'.$what;
  370:             my ($response,$cached);
  371:             unless ($ignore_cache) {
  372:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  373:             }
  374:             if (defined($cached)) {
  375:                 $returnhash{$what} = $response;
  376:             } else {
  377:                 $whatneeded{$what} = 1;
  378:             }
  379:         }
  380:         if (keys(%whatneeded) == 0) {
  381:             $result = 'ok';
  382:         } else {
  383:             my $requested = &freeze_escape(\%whatneeded);
  384:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  385:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  386:                 ($rep eq 'unknown_cmd')) {
  387:                 $result = $rep;
  388:             } else {
  389:                 $result = 'ok';
  390:                 my @pairs=split(/\&/,$rep);
  391:                 foreach my $item (@pairs) {
  392:                     my ($key,$value)=split(/=/,$item,2);
  393:                     my $what = &unescape($key);
  394:                     my $hashid = $lonhost.'-'.$what;
  395:                     $returnhash{$what}=&thaw_unescape($value);
  396:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  397:                 }
  398:             }
  399:         }
  400:     }
  401:     return ($result,\%returnhash);
  402: }
  403: 
  404: sub remote_devalidate_cache {
  405:     my ($lonhost,$cachekeys) = @_;
  406:     my $items;
  407:     return unless (ref($cachekeys) eq 'ARRAY');
  408:     my $cachestr = join('&',@{$cachekeys});
  409:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  410:     return $response;
  411: }
  412: 
  413: # -------------------------------------------------- Non-critical communication
  414: sub subreply {
  415:     my ($cmd,$server)=@_;
  416:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  417:     #
  418:     #  With loncnew process trimming, there's a timing hole between lonc server
  419:     #  process exit and the master server picking up the listen on the AF_UNIX
  420:     #  socket.  In that time interval, a lock file will exist:
  421: 
  422:     my $lockfile=$peerfile.".lock";
  423:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  424: 	sleep(0.1);
  425:     }
  426:     # At this point, either a loncnew parent is listening or an old lonc
  427:     # or loncnew child is listening so we can connect or everything's dead.
  428:     #
  429:     #   We'll give the connection a few tries before abandoning it.  If
  430:     #   connection is not possible, we'll con_lost back to the client.
  431:     #   
  432:     my $client;
  433:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  434: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  435: 				      Type    => SOCK_STREAM,
  436: 				      Timeout => 10);
  437: 	if ($client) {
  438: 	    last;		# Connected!
  439: 	} else {
  440: 	    &create_connection(&hostname($server),$server);
  441: 	}
  442:         sleep(0.1);	# Try again later if failed connection.
  443:     }
  444:     my $answer;
  445:     if ($client) {
  446: 	print $client "sethost:$server:$cmd\n";
  447: 	$answer=<$client>;
  448: 	if (!$answer) { $answer="con_lost"; }
  449: 	chomp($answer);
  450:     } else {
  451: 	$answer = 'con_lost';	# Failed connection.
  452:     }
  453:     return $answer;
  454: }
  455: 
  456: sub reply {
  457:     my ($cmd,$server)=@_;
  458:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  459:     my $answer=subreply($cmd,$server);
  460:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  461:        &logthis("<font color=\"blue\">WARNING:".
  462:                 " $cmd to $server returned $answer</font>");
  463:     }
  464:     return $answer;
  465: }
  466: 
  467: # ----------------------------------------------------------- Send USR1 to lonc
  468: 
  469: sub reconlonc {
  470:     my ($lonid) = @_;
  471:     if ($lonid) {
  472:         my $hostname = &hostname($lonid);
  473: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  474: 	if ($hostname && -e $peerfile) {
  475: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  476: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  477: 					     Type    => SOCK_STREAM,
  478: 					     Timeout => 10);
  479: 	    if ($client) {
  480: 		print $client ("reset_retries\n");
  481: 		my $answer=<$client>;
  482: 		#reset just this one.
  483: 	    }
  484: 	}
  485: 	return;
  486:     }
  487: 
  488:     &logthis("Trying to reconnect lonc");
  489:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  490:     if (open(my $fh,"<",$loncfile)) {
  491: 	my $loncpid=<$fh>;
  492:         chomp($loncpid);
  493:         if (kill 0 => $loncpid) {
  494: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  495:             kill USR1 => $loncpid;
  496:             sleep 1;
  497:         } else {
  498: 	    &logthis(
  499:                "<font color=\"blue\">WARNING:".
  500:                " lonc at pid $loncpid not responding, giving up</font>");
  501:         }
  502:     } else {
  503: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  504:     }
  505: }
  506: 
  507: # ------------------------------------------------------ Critical communication
  508: 
  509: sub critical {
  510:     my ($cmd,$server)=@_;
  511:     unless (&hostname($server)) {
  512:         &logthis("<font color=\"blue\">WARNING:".
  513:                " Critical message to unknown server ($server)</font>");
  514:         return 'no_such_host';
  515:     }
  516:     my $answer=reply($cmd,$server);
  517:     if ($answer eq 'con_lost') {
  518: 	&reconlonc($server);
  519: 	my $answer=reply($cmd,$server);
  520:         if ($answer eq 'con_lost') {
  521:             my $now=time;
  522:             my $middlename=$cmd;
  523:             $middlename=substr($middlename,0,16);
  524:             $middlename=~s/\W//g;
  525:             my $dfilename=
  526:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  527:             $dumpcount++;
  528:             {
  529: 		my $dfh;
  530: 		if (open($dfh,">",$dfilename)) {
  531: 		    print $dfh "$cmd\n"; 
  532: 		    close($dfh);
  533: 		}
  534:             }
  535:             sleep 1;
  536:             my $wcmd='';
  537:             {
  538: 		my $dfh;
  539: 		if (open($dfh,"<",$dfilename)) {
  540: 		    $wcmd=<$dfh>; 
  541: 		    close($dfh);
  542: 		}
  543:             }
  544:             chomp($wcmd);
  545:             if ($wcmd eq $cmd) {
  546: 		&logthis("<font color=\"blue\">WARNING: ".
  547:                          "Connection buffer $dfilename: $cmd</font>");
  548:                 &logperm("D:$server:$cmd");
  549: 	        return 'con_delayed';
  550:             } else {
  551:                 &logthis("<font color=\"red\">CRITICAL:"
  552:                         ." Critical connection failed: $server $cmd</font>");
  553:                 &logperm("F:$server:$cmd");
  554:                 return 'con_failed';
  555:             }
  556:         }
  557:     }
  558:     return $answer;
  559: }
  560: 
  561: # ------------------------------------------- check if return value is an error
  562: 
  563: sub error {
  564:     my ($result) = @_;
  565:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  566: 	if ($2 == 2) { return undef; }
  567: 	return $1;
  568:     }
  569:     return undef;
  570: }
  571: 
  572: sub convert_and_load_session_env {
  573:     my ($lonidsdir,$handle)=@_;
  574:     my @profile;
  575:     {
  576: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  577: 	if (!$opened) {
  578: 	    return 0;
  579: 	}
  580: 	flock($idf,LOCK_SH);
  581: 	@profile=<$idf>;
  582: 	close($idf);
  583:     }
  584:     my %temp_env;
  585:     foreach my $line (@profile) {
  586: 	if ($line !~ m/=/) {
  587: 	    return 0;
  588: 	}
  589: 	chomp($line);
  590: 	my ($envname,$envvalue)=split(/=/,$line,2);
  591: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  592:     }
  593:     unlink("$lonidsdir/$handle.id");
  594:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  595: 	    0640)) {
  596: 	%disk_env = %temp_env;
  597: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  598: 	untie(%disk_env);
  599:     }
  600:     return 1;
  601: }
  602: 
  603: # ------------------------------------------- Transfer profile into environment
  604: my $env_loaded;
  605: sub transfer_profile_to_env {
  606:     my ($lonidsdir,$handle,$force_transfer) = @_;
  607:     if (!$force_transfer && $env_loaded) { return; } 
  608: 
  609:     if (!defined($lonidsdir)) {
  610: 	$lonidsdir = $perlvar{'lonIDsDir'};
  611:     }
  612:     if (!defined($handle)) {
  613:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  614:     }
  615: 
  616:     my $convert;
  617:     {
  618:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  619: 	if (!$opened) {
  620: 	    return;
  621: 	}
  622: 	flock($idf,LOCK_SH);
  623: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  624: 		&GDBM_READER(),0640)) {
  625: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  626: 	    untie(%disk_env);
  627: 	} else {
  628: 	    $convert = 1;
  629: 	}
  630:     }
  631:     if ($convert) {
  632: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  633: 	    &logthis("Failed to load session, or convert session.");
  634: 	}
  635:     }
  636: 
  637:     my %remove;
  638:     while ( my $envname = each(%env) ) {
  639:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  640:             if ($time < time-300) {
  641:                 $remove{$key}++;
  642:             }
  643:         }
  644:     }
  645: 
  646:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  647:     $env_loaded=1;
  648:     foreach my $expired_key (keys(%remove)) {
  649:         &delenv($expired_key);
  650:     }
  651: }
  652: 
  653: # ---------------------------------------------------- Check for valid session 
  654: sub check_for_valid_session {
  655:     my ($r,$name,$userhashref,$domref) = @_;
  656:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  657:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  658:     if ($name eq 'lonDAV') {
  659:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  660:     } else {
  661:         $lonidsdir=$r->dir_config('lonIDsDir');
  662:         if ($name eq '') {
  663:             $name = 'lonID';
  664:         }
  665:     }
  666:     if ($name eq 'lonID') {
  667:         $secure = 'lonSID';
  668:         $linkname = 'lonLinkID';
  669:         $pubname = 'lonPubID';
  670:         if (exists($cookies{$secure})) {
  671:             $lonid=$cookies{$secure};
  672:         } elsif (exists($cookies{$name})) {
  673:             $lonid=$cookies{$name};
  674:         } elsif (exists($cookies{$linkname})) {
  675:             $lonid=$cookies{$linkname};
  676:         } elsif (exists($cookies{$pubname})) {
  677:             $lonid=$cookies{$pubname};
  678:         }
  679:     } else {
  680:         $lonid=$cookies{$name};
  681:     }
  682:     return undef if (!$lonid);
  683: 
  684:     my $handle=&LONCAPA::clean_handle($lonid->value);
  685:     if (-l "$lonidsdir/$handle.id") {
  686:         my $link = readlink("$lonidsdir/$handle.id");
  687:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  688:             $handle = $1;
  689:         }
  690:     }
  691:     if (!-e "$lonidsdir/$handle.id") {
  692:         if ((ref($domref)) && ($name eq 'lonID') && 
  693:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  694:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  695:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  696:                 $$domref = $possudom;
  697:             }
  698:         }
  699:         return undef;
  700:     }
  701: 
  702:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  703:     return undef if (!$opened);
  704: 
  705:     flock($idf,LOCK_SH);
  706:     my %disk_env;
  707:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  708: 	    &GDBM_READER(),0640)) {
  709: 	return undef;	
  710:     }
  711: 
  712:     if (!defined($disk_env{'user.name'})
  713: 	|| !defined($disk_env{'user.domain'})) {
  714: 	return undef;
  715:     }
  716: 
  717:     if (ref($userhashref) eq 'HASH') {
  718:         $userhashref->{'name'} = $disk_env{'user.name'};
  719:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  720:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  721:         if ($userhashref->{'lti'}) {
  722:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  723:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  724:         }
  725:     }
  726: 
  727:     return $handle;
  728: }
  729: 
  730: sub timed_flock {
  731:     my ($file,$lock_type) = @_;
  732:     my $failed=0;
  733:     eval {
  734: 	local $SIG{__DIE__}='DEFAULT';
  735: 	local $SIG{ALRM}=sub {
  736: 	    $failed=1;
  737: 	    die("failed lock");
  738: 	};
  739: 	alarm(13);
  740: 	flock($file,$lock_type);
  741: 	alarm(0);
  742:     };
  743:     if ($failed) {
  744: 	return undef;
  745:     } else {
  746: 	return 1;
  747:     }
  748: }
  749: 
  750: # ---------------------------------------------------------- Append Environment
  751: 
  752: sub appenv {
  753:     my ($newenv,$roles) = @_;
  754:     if (ref($newenv) eq 'HASH') {
  755:         foreach my $key (keys(%{$newenv})) {
  756:             my $refused = 0;
  757: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  758:                 $refused = 1;
  759:                 if (ref($roles) eq 'ARRAY') {
  760:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  761:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  762:                         $refused = 0;
  763:                     }
  764:                 }
  765:             }
  766:             if ($refused) {
  767:                 &logthis("<font color=\"blue\">WARNING: ".
  768:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  769:                          .'</font>');
  770: 	        delete($newenv->{$key});
  771:             } else {
  772:                 $env{$key}=$newenv->{$key};
  773:             }
  774:         }
  775:         my $lonids = $perlvar{'lonIDsDir'};
  776:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  777:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  778:             if ($opened
  779: 	        && &timed_flock($env_file,LOCK_EX)
  780: 	        &&
  781: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  782: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  783: 	        while (my ($key,$value) = each(%{$newenv})) {
  784: 	            $disk_env{$key} = $value;
  785: 	        }
  786: 	        untie(%disk_env);
  787:             }
  788:         }
  789:     }
  790:     return 'ok';
  791: }
  792: # ----------------------------------------------------- Delete from Environment
  793: 
  794: sub delenv {
  795:     my ($delthis,$regexp,$roles) = @_;
  796:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  797:         my $refused = 1;
  798:         if (ref($roles) eq 'ARRAY') {
  799:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  800:             if (grep(/^\Q$role\E$/,@{$roles})) {
  801:                 $refused = 0;
  802:             }
  803:         }
  804:         if ($refused) {
  805:             &logthis("<font color=\"blue\">WARNING: ".
  806:                      "Attempt to delete from environment ".$delthis);
  807:             return 'error';
  808:         }
  809:     }
  810:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  811:     if ($opened
  812: 	&& &timed_flock($env_file,LOCK_EX)
  813: 	&&
  814: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  815: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  816: 	foreach my $key (keys(%disk_env)) {
  817: 	    if ($regexp) {
  818:                 if ($key=~/^$delthis/) {
  819:                     delete($env{$key});
  820:                     delete($disk_env{$key});
  821:                 } 
  822:             } else {
  823:                 if ($key=~/^\Q$delthis\E/) {
  824: 		    delete($env{$key});
  825: 		    delete($disk_env{$key});
  826: 	        }
  827:             }
  828: 	}
  829: 	untie(%disk_env);
  830:     }
  831:     return 'ok';
  832: }
  833: 
  834: sub get_env_multiple {
  835:     my ($name) = @_;
  836:     my @values;
  837:     if (defined($env{$name})) {
  838:         # exists is it an array
  839:         if (ref($env{$name})) {
  840:             @values=@{ $env{$name} };
  841:         } else {
  842:             $values[0]=$env{$name};
  843:         }
  844:     }
  845:     return(@values);
  846: }
  847: 
  848: # ------------------------------------------------------------------- Locking
  849: 
  850: sub set_lock {
  851:     my ($text)=@_;
  852:     $locknum++;
  853:     my $id=$$.'-'.$locknum;
  854:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  855:              'session.lock.'.$id => $text});
  856:     return $id;
  857: }
  858: 
  859: sub get_locks {
  860:     my $num=0;
  861:     my %texts=();
  862:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  863:        if ($lock=~/\w/) {
  864:           $num++;
  865:           $texts{$lock}=$env{'session.lock.'.$lock};
  866:        }
  867:    }
  868:    return ($num,%texts);
  869: }
  870: 
  871: sub remove_lock {
  872:     my ($id)=@_;
  873:     my $newlocks='';
  874:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  875:        if (($lock=~/\w/) && ($lock ne $id)) {
  876:           $newlocks.=','.$lock;
  877:        }
  878:     }
  879:     &appenv({'session.locks' => $newlocks});
  880:     &delenv('session.lock.'.$id);
  881: }
  882: 
  883: sub remove_all_locks {
  884:     my $activelocks=$env{'session.locks'};
  885:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  886:        if ($lock=~/\w/) {
  887:           &remove_lock($lock);
  888:        }
  889:     }
  890: }
  891: 
  892: 
  893: # ------------------------------------------ Find out current server userload
  894: sub userload {
  895:     my $numusers=0;
  896:     {
  897: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  898: 	my $filename;
  899: 	my $curtime=time;
  900: 	while ($filename=readdir(LONIDS)) {
  901: 	    next if ($filename eq '.' || $filename eq '..');
  902: 	    next if ($filename =~ /publicuser_\d+\.id/);
  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  905: 	}
  906: 	closedir(LONIDS);
  907:     }
  908:     my $userloadpercent=0;
  909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  910:     if ($maxuserload) {
  911: 	$userloadpercent=100*$numusers/$maxuserload;
  912:     }
  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  914:     return $userloadpercent;
  915: }
  916: 
  917: # ------------------------------ Find server with least workload from spare.tab
  918: 
  919: sub spareserver {
  920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  921:     my $spare_server;
  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  924:                                                      :  $userloadpercent;
  925:     my ($uint_dom,$remotesessions);
  926:     if (($udom ne '') && (&domain($udom) ne '')) {
  927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  930:         $remotesessions = $udomdefaults{'remotesessions'};
  931:     }
  932:     my $spareshash = &this_host_spares($udom);
  933:     if (ref($spareshash) eq 'HASH') {
  934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  937:                                              $try_server));
  938: 	        ($spare_server, $lowest_load) =
  939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  940:             }
  941:         }
  942: 
  943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  944: 
  945:         if (!$found_server) {
  946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  948:                     next unless (&spare_can_host($udom,$uint_dom,
  949:                                                  $remotesessions,$try_server));
  950: 	            ($spare_server, $lowest_load) =
  951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  952:                 }
  953: 	    }
  954:         }
  955:     }
  956: 
  957:     if (!$want_server_name) {
  958:         my $protocol = 'http';
  959:         if ($protocol{$spare_server} eq 'https') {
  960:             $protocol = $protocol{$spare_server};
  961:         }
  962:         if (defined($spare_server)) {
  963:             my $hostname = &hostname($spare_server);
  964:             if (defined($hostname)) {
  965: 	        $spare_server = $protocol.'://'.$hostname;
  966:             }
  967:         }
  968:     }
  969:     return $spare_server;
  970: }
  971: 
  972: sub compare_server_load {
  973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  974: 
  975:     if ($required) {
  976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  979:         if (($major eq '' && $minor eq '') ||
  980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  981:             return ($spare_server,$lowest_load);
  982:         }
  983:     }
  984: 
  985:     my $loadans     = &reply('load',    $try_server);
  986:     my $userloadans = &reply('userload',$try_server);
  987: 
  988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  990:     }
  991: 
  992:     my $load;
  993:     if ($loadans =~ /\d/) {
  994: 	if ($userloadans =~ /\d/) {
  995: 	    #both are numbers, pick the bigger one
  996: 	    $load = ($loadans > $userloadans) ? $loadans 
  997: 		                              : $userloadans;
  998: 	} else {
  999: 	    $load = $loadans;
 1000: 	}
 1001:     } else {
 1002: 	$load = $userloadans;
 1003:     }
 1004: 
 1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1006: 	$spare_server = $try_server;
 1007: 	$lowest_load  = $load;
 1008:     }
 1009:     return ($spare_server,$lowest_load);
 1010: }
 1011: 
 1012: # --------------------------- ask offload servers if user already has a session
 1013: sub find_existing_session {
 1014:     my ($udom,$uname) = @_;
 1015:     my $spareshash = &this_host_spares($udom);
 1016:     if (ref($spareshash) eq 'HASH') {
 1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1020:             }
 1021:         }
 1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1025:             }
 1026:         }
 1027:     }
 1028:     return;
 1029: }
 1030: 
 1031: # check if user's browser sent load balancer cookie and server still has session
 1032: # and is not overloaded.
 1033: sub check_for_balancer_cookie {
 1034:     my ($r,$update_mtime) = @_;
 1035:     my ($otherserver,$cookie);
 1036:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1037:     if (exists($cookies{'balanceID'})) {
 1038:         my $balid = $cookies{'balanceID'};
 1039:         $cookie=&LONCAPA::clean_handle($balid->value);
 1040:         my $balancedir=$r->dir_config('lonBalanceDir');
 1041:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1042:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1043:                 my ($possudom,$possuname) = ($1,$2);
 1044:                 my $has_session = 0;
 1045:                 if ((&domain($possudom) ne '') &&
 1046:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1047:                     my $try_server;
 1048:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1049:                     if ($opened) {
 1050:                         flock($idf,LOCK_SH);
 1051:                         while (my $line = <$idf>) {
 1052:                             chomp($line);
 1053:                             if (&hostname($line) ne '') {
 1054:                                 $try_server = $line;
 1055:                                 last;
 1056:                             }
 1057:                         }
 1058:                         close($idf);
 1059:                         if (($try_server) &&
 1060:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1061:                             my $lowest_load = 30000;
 1062:                             ($otherserver,$lowest_load) =
 1063:                                 &compare_server_load($try_server,undef,$lowest_load);
 1064:                             if ($otherserver ne '' && $lowest_load < 100) {
 1065:                                 $has_session = 1;
 1066:                             } else {
 1067:                                 undef($otherserver);
 1068:                             }
 1069:                         }
 1070:                     }
 1071:                 }
 1072:                 if ($has_session) {
 1073:                     if ($update_mtime) {
 1074:                         my $atime = my $mtime = time;
 1075:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1076:                     }
 1077:                 } else {
 1078:                     unlink("$balancedir/$cookie.id");
 1079:                 }
 1080:             }
 1081:         }
 1082:     }
 1083:     return ($otherserver,$cookie);
 1084: }
 1085: 
 1086: sub delbalcookie {
 1087:     my ($cookie,$balancer) =@_;
 1088:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1089:         my ($udom,$uname) = ($1,$2);
 1090:         my $uprimary_id = &domain($udom,'primary');
 1091:         my $uintdom = &internet_dom($uprimary_id);
 1092:         my $intdom = &internet_dom($balancer);
 1093:         my $serverhomedom = &host_domain($balancer);
 1094:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1095:             return &reply("delbalcookie:$cookie",$balancer);
 1096:         }
 1097:     }
 1098: }
 1099: 
 1100: # -------------------------------- ask if server already has a session for user
 1101: sub has_user_session {
 1102:     my ($lonid,$udom,$uname) = @_;
 1103:     my $result = &reply(join(':','userhassession',
 1104: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1105:     return 1 if ($result eq 'ok');
 1106: 
 1107:     return 0;
 1108: }
 1109: 
 1110: # --------- determine least loaded server in a user's domain which allows login
 1111: 
 1112: sub choose_server {
 1113:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1114:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1115:     my %servers = &get_servers($udom);
 1116:     my $lowest_load = 30000;
 1117:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1118:     if ($skiploadbal) {
 1119:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1120:         unless (defined($cached)) {
 1121:             my $cachetime = 60*60*24;
 1122:             my %domconfig =
 1123:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1124:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1125:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1126:                                            $cachetime);
 1127:             }
 1128:         }
 1129:     }
 1130:     foreach my $lonhost (keys(%servers)) {
 1131:         if ($skiploadbal) {
 1132:             if (ref($balancers) eq 'HASH') {
 1133:                 next if (exists($balancers->{$lonhost}));
 1134:             }
 1135:         }
 1136:         my $loginvia;
 1137:         if ($checkloginvia) {
 1138:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1139:             if ($loginvia) {
 1140:                 my ($server,$path) = split(/:/,$loginvia);
 1141:                 ($login_host, $lowest_load) =
 1142:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1143:                 if ($login_host eq $server) {
 1144:                     $portal_path = $path;
 1145:                     $isredirect = 1;
 1146:                 }
 1147:             } else {
 1148:                 ($login_host, $lowest_load) =
 1149:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1150:                 if ($login_host eq $lonhost) {
 1151:                     $portal_path = '';
 1152:                     $isredirect = ''; 
 1153:                 }
 1154:             }
 1155:         } else {
 1156:             ($login_host, $lowest_load) =
 1157:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1158:         }
 1159:     }
 1160:     if ($login_host ne '') {
 1161:         $hostname = &hostname($login_host);
 1162:     }
 1163:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1164: }
 1165: 
 1166: # --------------------------------------------- Try to change a user's password
 1167: 
 1168: sub changepass {
 1169:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1170:     $currentpass = &escape($currentpass);
 1171:     $newpass     = &escape($newpass);
 1172:     my $lonhost = $perlvar{'lonHostID'};
 1173:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1174: 		       $server);
 1175:     if (! $answer) {
 1176: 	&logthis("No reply on password change request to $server ".
 1177: 		 "by $uname in domain $udom.");
 1178:     } elsif ($answer =~ "^ok") {
 1179:         &logthis("$uname in $udom successfully changed their password ".
 1180: 		 "on $server.");
 1181:     } elsif ($answer =~ "^pwchange_failure") {
 1182: 	&logthis("$uname in $udom was unable to change their password ".
 1183: 		 "on $server.  The action was blocked by either lcpasswd ".
 1184: 		 "or pwchange");
 1185:     } elsif ($answer =~ "^non_authorized") {
 1186:         &logthis("$uname in $udom did not get their password correct when ".
 1187: 		 "attempting to change it on $server.");
 1188:     } elsif ($answer =~ "^auth_mode_error") {
 1189:         &logthis("$uname in $udom attempted to change their password despite ".
 1190: 		 "not being locally or internally authenticated on $server.");
 1191:     } elsif ($answer =~ "^unknown_user") {
 1192:         &logthis("$uname in $udom attempted to change their password ".
 1193: 		 "on $server but were unable to because $server is not ".
 1194: 		 "their home server.");
 1195:     } elsif ($answer =~ "^refused") {
 1196: 	&logthis("$server refused to change $uname in $udom password because ".
 1197: 		 "it was sent an unencrypted request to change the password.");
 1198:     } elsif ($answer =~ "invalid_client") {
 1199:         &logthis("$server refused to change $uname in $udom password because ".
 1200:                  "it was a reset by e-mail originating from an invalid server.");
 1201:     }
 1202:     return $answer;
 1203: }
 1204: 
 1205: # ----------------------- Try to determine user's current authentication scheme
 1206: 
 1207: sub queryauthenticate {
 1208:     my ($uname,$udom)=@_;
 1209:     my $uhome=&homeserver($uname,$udom);
 1210:     if (!$uhome) {
 1211: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1212: 	return 'no_host';
 1213:     }
 1214:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1215:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1216: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1217:     }
 1218:     return $answer;
 1219: }
 1220: 
 1221: # --------- Try to authenticate user from domain's lib servers (first this one)
 1222: 
 1223: sub authenticate {
 1224:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1225:     $upass=&escape($upass);
 1226:     $uname= &LONCAPA::clean_username($uname);
 1227:     my $uhome=&homeserver($uname,$udom,1);
 1228:     my $newhome;
 1229:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1230: # Maybe the machine was offline and only re-appeared again recently?
 1231:         &reconlonc();
 1232: # One more
 1233: 	$uhome=&homeserver($uname,$udom,1);
 1234:         if (($uhome eq 'no_host') && $checkdefauth) {
 1235:             if (defined(&domain($udom,'primary'))) {
 1236:                 $newhome=&domain($udom,'primary');
 1237:             }
 1238:             if ($newhome ne '') {
 1239:                 $uhome = $newhome;
 1240:             }
 1241:         }
 1242: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1243: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1244: 	    return 'no_host';
 1245:         }
 1246:     }
 1247:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1248:     if ($answer eq 'authorized') {
 1249:         if ($newhome) {
 1250:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1251:             return 'no_account_on_host'; 
 1252:         } else {
 1253:             &logthis("User $uname at $udom authorized by $uhome");
 1254:             return $uhome;
 1255:         }
 1256:     }
 1257:     if ($answer eq 'non_authorized') {
 1258: 	&logthis("User $uname at $udom rejected by $uhome");
 1259: 	return 'no_host'; 
 1260:     }
 1261:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1262:     return 'no_host';
 1263: }
 1264: 
 1265: sub can_host_session {
 1266:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1267:     my $canhost = 1;
 1268:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1269:     if (ref($remotesessions) eq 'HASH') {
 1270:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1271:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1272:                 $canhost = 0;
 1273:             } else {
 1274:                 $canhost = 1;
 1275:             }
 1276:         }
 1277:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1278:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1279:                 $canhost = 1;
 1280:             } else {
 1281:                 $canhost = 0;
 1282:             }
 1283:         }
 1284:         if ($canhost) {
 1285:             if ($remotesessions->{'version'} ne '') {
 1286:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1287:                 if ($reqmajor ne '' && $reqminor ne '') {
 1288:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1289:                         my $major = $1;
 1290:                         my $minor = $2;
 1291:                         if (($major < $reqmajor ) ||
 1292:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1293:                             $canhost = 0;
 1294:                         }
 1295:                     } else {
 1296:                         $canhost = 0;
 1297:                     }
 1298:                 }
 1299:             }
 1300:         }
 1301:     }
 1302:     if ($canhost) {
 1303:         if (ref($hostedsessions) eq 'HASH') {
 1304:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1305:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1306:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1307:                 if (($uint_dom ne '') && 
 1308:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1309:                     $canhost = 0;
 1310:                 } else {
 1311:                     $canhost = 1;
 1312:                 }
 1313:             }
 1314:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1315:                 if (($uint_dom ne '') && 
 1316:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1317:                     $canhost = 1;
 1318:                 } else {
 1319:                     $canhost = 0;
 1320:                 }
 1321:             }
 1322:         }
 1323:     }
 1324:     return $canhost;
 1325: }
 1326: 
 1327: sub spare_can_host {
 1328:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1329:     my $canhost=1;
 1330:     my $try_server_hostname = &hostname($try_server);
 1331:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1332:     my $serverhomedom = &host_domain($serverhomeID);
 1333:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1334:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1335:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1336:             $canhost = 0;
 1337:         }
 1338:     }
 1339:     if (($canhost) && ($uint_dom)) {
 1340:         my @intdoms;
 1341:         my $internet_names = &get_internet_names($try_server);
 1342:         if (ref($internet_names) eq 'ARRAY') {
 1343:             @intdoms = @{$internet_names};
 1344:         }
 1345:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1346:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1347:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1348:                                          $remotesessions,
 1349:                                          $defdomdefaults{'hostedsessions'});
 1350:         }
 1351:     }
 1352:     return $canhost;
 1353: }
 1354: 
 1355: sub this_host_spares {
 1356:     my ($dom) = @_;
 1357:     my ($dom_in_use,$lonhost_in_use,$result);
 1358:     my @hosts = &current_machine_ids();
 1359:     foreach my $lonhost (@hosts) {
 1360:         if (&host_domain($lonhost) eq $dom) {
 1361:             $dom_in_use = $dom;
 1362:             $lonhost_in_use = $lonhost;
 1363:             last;
 1364:         }
 1365:     }
 1366:     if ($dom_in_use ne '') {
 1367:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1368:     }
 1369:     if (ref($result) ne 'HASH') {
 1370:         $lonhost_in_use = $perlvar{'lonHostID'};
 1371:         $dom_in_use = &host_domain($lonhost_in_use);
 1372:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1373:         if (ref($result) ne 'HASH') {
 1374:             $result = \%spareid;
 1375:         }
 1376:     }
 1377:     return $result;
 1378: }
 1379: 
 1380: sub spares_for_offload  {
 1381:     my ($dom_in_use,$lonhost_in_use) = @_;
 1382:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1383:     if (defined($cached)) {
 1384:         return $result;
 1385:     } else {
 1386:         my $cachetime = 60*60*24;
 1387:         my %domconfig =
 1388:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1389:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1390:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1391:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1392:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1393:                 }
 1394:             }
 1395:         }
 1396:     }
 1397:     return;
 1398: }
 1399: 
 1400: sub get_lonbalancer_config {
 1401:     my ($servers) = @_;
 1402:     my ($currbalancer,$currtargets);
 1403:     if (ref($servers) eq 'HASH') {
 1404:         foreach my $server (keys(%{$servers})) {
 1405:             my %what = (
 1406:                          spareid => 1,
 1407:                          perlvar => 1,
 1408:                        );
 1409:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1410:             if ($result eq 'ok') {
 1411:                 if (ref($returnhash) eq 'HASH') {
 1412:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1413:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1414:                             $currbalancer = $server;
 1415:                             $currtargets = {};
 1416:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1417:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1418:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1419:                                 }
 1420:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1421:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1422:                                 }
 1423:                             }
 1424:                             last;
 1425:                         }
 1426:                     }
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return ($currbalancer,$currtargets);
 1432: }
 1433: 
 1434: sub check_loadbalancing {
 1435:     my ($uname,$udom,$caller) = @_;
 1436:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1437:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
 1438:     my $lonhost = $perlvar{'lonHostID'};
 1439:     my @hosts = &current_machine_ids();
 1440:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1441:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1442:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1443:     my $serverhomedom = &host_domain($lonhost);
 1444:     my $domneedscache;
 1445:     my $cachetime = 60*60*24;
 1446: 
 1447:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1448:         $dom_in_use = $udom;
 1449:         $homeintdom = 1;
 1450:     } else {
 1451:         $dom_in_use = $serverhomedom;
 1452:     }
 1453:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1454:     unless (defined($cached)) {
 1455:         my %domconfig =
 1456:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1457:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1458:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1459:         } else {
 1460:             $domneedscache = $dom_in_use;
 1461:         }
 1462:     }
 1463:     if (ref($result) eq 'HASH') {
 1464:         ($is_balancer,$currtargets,$currrules,$setcookie) =
 1465:             &check_balancer_result($result,@hosts);
 1466:         if ($is_balancer) {
 1467:             if (ref($currrules) eq 'HASH') {
 1468:                 if ($homeintdom) {
 1469:                     if ($uname ne '') {
 1470:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1471:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1472:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1473:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1474:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1475:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1476:                             }
 1477:                         }
 1478:                         if ($rule_in_effect eq '') {
 1479:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1480:                             if ($userenv{'inststatus'} ne '') {
 1481:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1482:                                 my ($othertitle,$usertypes,$types) =
 1483:                                     &Apache::loncommon::sorted_inst_types($udom);
 1484:                                 if (ref($types) eq 'ARRAY') {
 1485:                                     foreach my $type (@{$types}) {
 1486:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1487:                                             if (exists($currrules->{$type})) {
 1488:                                                 $rule_in_effect = $currrules->{$type};
 1489:                                             }
 1490:                                         }
 1491:                                     }
 1492:                                 }
 1493:                             } else {
 1494:                                 if (exists($currrules->{'default'})) {
 1495:                                     $rule_in_effect = $currrules->{'default'};
 1496:                                 }
 1497:                             }
 1498:                         }
 1499:                     } else {
 1500:                         if (exists($currrules->{'default'})) {
 1501:                             $rule_in_effect = $currrules->{'default'};
 1502:                         }
 1503:                     }
 1504:                 } else {
 1505:                     if ($currrules->{'_LC_external'} ne '') {
 1506:                         $rule_in_effect = $currrules->{'_LC_external'};
 1507:                     }
 1508:                 }
 1509:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1510:                                                        $uname,$udom);
 1511:             }
 1512:         }
 1513:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1514:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1515:         unless (defined($cached)) {
 1516:             my %domconfig =
 1517:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1518:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1519:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1520:             } else {
 1521:                 $domneedscache = $serverhomedom;
 1522:             }
 1523:         }
 1524:         if (ref($result) eq 'HASH') {
 1525:             ($is_balancer,$currtargets,$currrules,$setcookie) =
 1526:                 &check_balancer_result($result,@hosts);
 1527:             if ($is_balancer) {
 1528:                 if (ref($currrules) eq 'HASH') {
 1529:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1530:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1531:                     }
 1532:                 }
 1533:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1534:                                                        $uname,$udom);
 1535:             }
 1536:         } else {
 1537:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1538:                 $is_balancer = 1;
 1539:                 $offloadto = &this_host_spares($dom_in_use);
 1540:             }
 1541:             unless (defined($cached)) {
 1542:                 $domneedscache = $serverhomedom;
 1543:             }
 1544:         }
 1545:     } else {
 1546:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1547:             $is_balancer = 1;
 1548:             $offloadto = &this_host_spares($dom_in_use);
 1549:         }
 1550:         unless (defined($cached)) {
 1551:             $domneedscache = $serverhomedom;
 1552:         }
 1553:     }
 1554:     if ($domneedscache) {
 1555:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1556:     }
 1557:     if ($is_balancer) {
 1558:         my $lowest_load = 30000;
 1559:         if (ref($offloadto) eq 'HASH') {
 1560:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1561:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1562:                     ($otherserver,$lowest_load) =
 1563:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1564:                 }
 1565:             }
 1566:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1567: 
 1568:             if (!$found_server) {
 1569:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1570:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1571:                         ($otherserver,$lowest_load) =
 1572:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1573:                     }
 1574:                 }
 1575:             }
 1576:         } elsif (ref($offloadto) eq 'ARRAY') {
 1577:             if (@{$offloadto} == 1) {
 1578:                 $otherserver = $offloadto->[0];
 1579:             } elsif (@{$offloadto} > 1) {
 1580:                 foreach my $try_server (@{$offloadto}) {
 1581:                     ($otherserver,$lowest_load) =
 1582:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1583:                 }
 1584:             }
 1585:         }
 1586:         unless ($caller eq 'login') {
 1587:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1588:                 $is_balancer = 0;
 1589:                 if ($uname ne '' && $udom ne '') {
 1590:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1591:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1592:                                  'user.loadbalcheck.time' => time});
 1593:                     }
 1594:                 }
 1595:             }
 1596:         }
 1597:         unless ($homeintdom) {
 1598:             undef($setcookie);
 1599:         }
 1600:     }
 1601:     return ($is_balancer,$otherserver,$setcookie);
 1602: }
 1603: 
 1604: sub check_balancer_result {
 1605:     my ($result,@hosts) = @_;
 1606:     my ($is_balancer,$currtargets,$currrules,$setcookie);
 1607:     if (ref($result) eq 'HASH') {
 1608:         if ($result->{'lonhost'} ne '') {
 1609:             my $currbalancer = $result->{'lonhost'};
 1610:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1611:                 $is_balancer = 1;
 1612:                 $currtargets = $result->{'targets'};
 1613:                 $currrules = $result->{'rules'};
 1614:             }
 1615:         } else {
 1616:             foreach my $key (keys(%{$result})) {
 1617:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1618:                     (ref($result->{$key}) eq 'HASH')) {
 1619:                     $is_balancer = 1;
 1620:                     $currrules = $result->{$key}{'rules'};
 1621:                     $currtargets = $result->{$key}{'targets'};
 1622:                     $setcookie = $result->{$key}{'cookie'};
 1623:                     last;
 1624:                 }
 1625:             }
 1626:         }
 1627:     }
 1628:     return ($is_balancer,$currtargets,$currrules,$setcookie);
 1629: }
 1630: 
 1631: sub get_loadbalancer_targets {
 1632:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1633:     my $offloadto;
 1634:     if ($rule_in_effect eq 'none') {
 1635:         return [$perlvar{'lonHostID'}];
 1636:     } elsif ($rule_in_effect eq '') {
 1637:         $offloadto = $currtargets;
 1638:     } else {
 1639:         if ($rule_in_effect eq 'homeserver') {
 1640:             my $homeserver = &homeserver($uname,$udom);
 1641:             if ($homeserver ne 'no_host') {
 1642:                 $offloadto = [$homeserver];
 1643:             }
 1644:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1645:             my %domconfig =
 1646:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1647:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1648:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1649:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1650:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1651:                     }
 1652:                 }
 1653:             } else {
 1654:                 my %servers = &internet_dom_servers($udom);
 1655:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1656:                 if (&hostname($remotebalancer) ne '') {
 1657:                     $offloadto = [$remotebalancer];
 1658:                 }
 1659:             }
 1660:         } elsif (&hostname($rule_in_effect) ne '') {
 1661:             $offloadto = [$rule_in_effect];
 1662:         }
 1663:     }
 1664:     return $offloadto;
 1665: }
 1666: 
 1667: sub internet_dom_servers {
 1668:     my ($dom) = @_;
 1669:     my (%uniqservers,%servers);
 1670:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1671:     my @machinedoms = &machine_domains($primaryserver);
 1672:     foreach my $mdom (@machinedoms) {
 1673:         my %currservers = %servers;
 1674:         my %server = &get_servers($mdom);
 1675:         %servers = (%currservers,%server);
 1676:     }
 1677:     my %by_hostname;
 1678:     foreach my $id (keys(%servers)) {
 1679:         push(@{$by_hostname{$servers{$id}}},$id);
 1680:     }
 1681:     foreach my $hostname (sort(keys(%by_hostname))) {
 1682:         if (@{$by_hostname{$hostname}} > 1) {
 1683:             my $match = 0;
 1684:             foreach my $id (@{$by_hostname{$hostname}}) {
 1685:                 if (&host_domain($id) eq $dom) {
 1686:                     $uniqservers{$id} = $hostname;
 1687:                     $match = 1;
 1688:                 }
 1689:             }
 1690:             unless ($match) {
 1691:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1692:             }
 1693:         } else {
 1694:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1695:         }
 1696:     }
 1697:     return %uniqservers;
 1698: }
 1699: 
 1700: sub trusted_domains {
 1701:     my ($cmdtype,$calldom) = @_;
 1702:     my ($trusted,$untrusted);
 1703:     if (&domain($calldom) eq '') {
 1704:         return ($trusted,$untrusted);
 1705:     }
 1706:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1707:         return ($trusted,$untrusted);
 1708:     }
 1709:     my $callprimary = &domain($calldom,'primary');
 1710:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1711:     if ($intcalldom eq '') {
 1712:         return ($trusted,$untrusted);
 1713:     }
 1714: 
 1715:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1716:     unless (defined($cached)) {
 1717:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1718:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1719:         $trustconfig = $domconfig{'trust'};
 1720:     }
 1721:     if (ref($trustconfig)) {
 1722:         my (%possexc,%possinc,@allexc,@allinc); 
 1723:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1724:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1725:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1726:             }
 1727:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1728:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1729:             }
 1730:         }
 1731:         if (keys(%possexc)) {
 1732:             if (keys(%possinc)) {
 1733:                 foreach my $key (sort(keys(%possexc))) {
 1734:                     next if ($key eq $intcalldom);
 1735:                     unless ($possinc{$key}) {
 1736:                         push(@allexc,$key);
 1737:                     }
 1738:                 }
 1739:             } else {
 1740:                 @allexc = sort(keys(%possexc));
 1741:             }
 1742:         }
 1743:         if (keys(%possinc)) {
 1744:             $possinc{$intcalldom} = 1;
 1745:             @allinc = sort(keys(%possinc));
 1746:         }
 1747:         if ((@allexc > 0) || (@allinc > 0)) {
 1748:             my %doms_by_intdom;
 1749:             my %allintdoms = &all_host_intdom();
 1750:             my %alldoms = &all_host_domain();
 1751:             foreach my $key (%allintdoms) {
 1752:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1753:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1754:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1755:                     }
 1756:                 } else {
 1757:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1758:                 }
 1759:             }
 1760:             foreach my $exc (@allexc) {
 1761:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1762:                     $untrusted = $doms_by_intdom{$exc};
 1763:                 }
 1764:             }
 1765:             foreach my $inc (@allinc) {
 1766:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1767:                     $trusted = $doms_by_intdom{$inc};
 1768:                 }
 1769:             }
 1770:         }
 1771:     }
 1772:     return ($trusted,$untrusted);
 1773: }
 1774: 
 1775: sub will_trust {
 1776:     my ($cmdtype,$domain,$possdom) = @_;
 1777:     return 1 if ($domain eq $possdom);
 1778:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1779:     my $willtrust; 
 1780:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1781:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1782:             $willtrust = 1;
 1783:         }
 1784:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1785:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1786:             $willtrust = 1;
 1787:         }
 1788:     } else {
 1789:         $willtrust = 1;
 1790:     }
 1791:     return $willtrust;
 1792: }
 1793: 
 1794: # ---------------------- Find the homebase for a user from domain's lib servers
 1795: 
 1796: my %homecache;
 1797: sub homeserver {
 1798:     my ($uname,$udom,$ignoreBadCache)=@_;
 1799:     my $index="$uname:$udom";
 1800: 
 1801:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1802: 
 1803:     my %servers = &get_servers($udom,'library');
 1804:     foreach my $tryserver (keys(%servers)) {
 1805:         next if ($ignoreBadCache ne 'true' && 
 1806: 		 exists($badServerCache{$tryserver}));
 1807: 
 1808: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1809: 	if ($answer eq 'found') {
 1810: 	    delete($badServerCache{$tryserver}); 
 1811: 	    return $homecache{$index}=$tryserver;
 1812: 	} elsif ($answer eq 'no_host') {
 1813: 	    $badServerCache{$tryserver}=1;
 1814: 	}
 1815:     }    
 1816:     return 'no_host';
 1817: }
 1818: 
 1819: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1820: 
 1821: sub idget {
 1822:     my ($udom,$idsref,$namespace)=@_;
 1823:     my %returnhash=();
 1824:     my @ids=(); 
 1825:     if (ref($idsref) eq 'ARRAY') {
 1826:         @ids = @{$idsref};
 1827:     } else {
 1828:         return %returnhash; 
 1829:     }
 1830:     if ($namespace eq '') {
 1831:         $namespace = 'ids';
 1832:     }
 1833:     
 1834:     my %servers = &get_servers($udom,'library');
 1835:     foreach my $tryserver (keys(%servers)) {
 1836: 	my $idlist=join('&', map { &escape($_); } @ids);
 1837: 	if ($namespace eq 'ids') {
 1838: 	    $idlist=~tr/A-Z/a-z/;
 1839: 	}
 1840: 	my $reply;
 1841: 	if ($namespace eq 'ids') {
 1842: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1843: 	} else {
 1844: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1845: 	}
 1846: 	my @answer=();
 1847: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1848: 	    @answer=split(/\&/,$reply);
 1849: 	}                    ;
 1850: 	my $i;
 1851: 	for ($i=0;$i<=$#ids;$i++) {
 1852: 	    if ($answer[$i]) {
 1853: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1854: 	    }
 1855: 	}
 1856:     }
 1857:     return %returnhash;
 1858: }
 1859: 
 1860: # ------------------------------------- Find the IDs behind a list of usernames
 1861: 
 1862: sub idrget {
 1863:     my ($udom,@unames)=@_;
 1864:     my %returnhash=();
 1865:     foreach my $uname (@unames) {
 1866:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1867:     }
 1868:     return %returnhash;
 1869: }
 1870: 
 1871: # Store away a list of names and associated student/employee IDs or clicker IDs
 1872: 
 1873: sub idput {
 1874:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1875:     my %servers=();
 1876:     my %ids=();
 1877:     my %byid = ();
 1878:     if (ref($idsref) eq 'HASH') {
 1879:         %ids=%{$idsref};
 1880:     }
 1881:     if ($namespace eq '') {
 1882:         $namespace = 'ids'; 
 1883:     }
 1884:     foreach my $uname (keys(%ids)) {
 1885: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1886:         if ($uhom eq '') {
 1887:             $uhom=&homeserver($uname,$udom);
 1888:         }
 1889:         if ($uhom ne 'no_host') {
 1890:             my $esc_unam=&escape($uname);
 1891:             if ($namespace eq 'ids') {
 1892:                 my $id=&escape($ids{$uname});
 1893:                 $id=~tr/A-Z/a-z/;
 1894:                 my $esc_unam=&escape($uname);
 1895:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1896:             } else {
 1897:                 my @currids = split(/,/,$ids{$uname});
 1898:                 foreach my $id (@currids) {
 1899:                     $byid{$uhom}{$id} .= $uname.',';
 1900:                 }
 1901:             }
 1902:         }
 1903:     }
 1904:     if ($namespace eq 'clickers') {
 1905:         foreach my $server (keys(%byid)) {
 1906:             if (ref($byid{$server}) eq 'HASH') {
 1907:                 foreach my $id (keys(%{$byid{$server}})) {
 1908:                     $byid{$server} =~ s/,$//;
 1909:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1910:                 }
 1911:             }
 1912:         }
 1913:     }
 1914:     foreach my $server (keys(%servers)) {
 1915:         $servers{$server} =~ s/\&$//;
 1916:         if ($namespace eq 'ids') {     
 1917:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1918:         } else {
 1919:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1920:         }
 1921:     }
 1922: }
 1923: 
 1924: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1925: 
 1926: sub iddel {
 1927:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1928:     my %result=();
 1929:     my %ids=();
 1930:     my %byid = ();
 1931:     if (ref($idshashref) eq 'HASH') {
 1932:         %ids=%{$idshashref};
 1933:     } else {
 1934:         return %result;
 1935:     }
 1936:     if ($namespace eq '') {
 1937:         $namespace = 'ids';
 1938:     }
 1939:     my %servers=();
 1940:     while (my ($id,$unamestr) = each(%ids)) {
 1941:         if ($namespace eq 'ids') {
 1942:             my $uhom = $uhome;
 1943:             if ($uhom eq '') { 
 1944:                 $uhom=&homeserver($unamestr,$udom);
 1945:             }
 1946:             if ($uhom ne 'no_host') {
 1947:                 $servers{$uhom}.='&'.&escape($id);
 1948:             }
 1949:          } else {
 1950:             my @curritems = split(/,/,$ids{$id});
 1951:             foreach my $uname (@curritems) {
 1952:                 my $uhom = $uhome;
 1953:                 if ($uhom eq '') {
 1954:                     $uhom=&homeserver($uname,$udom);
 1955:                 }
 1956:                 if ($uhom ne 'no_host') { 
 1957:                     $byid{$uhom}{$id} .= $uname.',';
 1958:                 }
 1959:             }
 1960:         }
 1961:     }
 1962:     if ($namespace eq 'clickers') {
 1963:         foreach my $server (keys(%byid)) {
 1964:             if (ref($byid{$server}) eq 'HASH') {
 1965:                 foreach my $id (keys(%{$byid{$server}})) {
 1966:                     $byid{$server}{$id} =~ s/,$//;
 1967:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1968:                 }
 1969:             }
 1970:         }
 1971:     }
 1972:     foreach my $server (keys(%servers)) {
 1973:         $servers{$server} =~ s/\&$//;
 1974:         if ($namespace eq 'ids') {
 1975:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1976:         } elsif ($namespace eq 'clickers') {
 1977:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1978:         }
 1979:     }
 1980:     return %result;
 1981: }
 1982: 
 1983: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1984: 
 1985: sub updateclickers {
 1986:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1987:     my %clickers;
 1988:     if (ref($idshashref) eq 'HASH') {
 1989:         %clickers=%{$idshashref};
 1990:     } else {
 1991:         return;
 1992:     }
 1993:     my $items='';
 1994:     foreach my $item (keys(%clickers)) {
 1995:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1996:     }
 1997:     $items=~s/\&$//;
 1998:     my $request = "updateclickers:$udom:$action:$items";
 1999:     if ($critical) {
 2000:         return &critical($request,$uhome);
 2001:     } else {
 2002:         return &reply($request,$uhome);
 2003:     }
 2004: }
 2005: 
 2006: # ------------------------------dump from db file owned by domainconfig user
 2007: sub dump_dom {
 2008:     my ($namespace, $udom, $regexp) = @_;
 2009: 
 2010:     $udom ||= $env{'user.domain'};
 2011: 
 2012:     return () unless $udom;
 2013: 
 2014:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2015: }
 2016: 
 2017: # ------------------------------------------ get items from domain db files   
 2018: 
 2019: sub get_dom {
 2020:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2021:     return if ($udom eq 'public');
 2022:     my $items='';
 2023:     foreach my $item (@$storearr) {
 2024:         $items.=&escape($item).'&';
 2025:     }
 2026:     $items=~s/\&$//;
 2027:     if (!$udom) {
 2028:         $udom=$env{'user.domain'};
 2029:         return if ($udom eq 'public');
 2030:         if (defined(&domain($udom,'primary'))) {
 2031:             $uhome=&domain($udom,'primary');
 2032:         } else {
 2033:             undef($uhome);
 2034:         }
 2035:     } else {
 2036:         if (!$uhome) {
 2037:             if (defined(&domain($udom,'primary'))) {
 2038:                 $uhome=&domain($udom,'primary');
 2039:             }
 2040:         }
 2041:     }
 2042:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2043:         my $rep;
 2044:         if ($namespace =~ /^enc/) {
 2045:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2046:         } else {
 2047:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2048:         }
 2049:         my %returnhash;
 2050:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2051:             return %returnhash;
 2052:         }
 2053:         my @pairs=split(/\&/,$rep);
 2054:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2055:             return @pairs;
 2056:         }
 2057:         my $i=0;
 2058:         foreach my $item (@$storearr) {
 2059:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2060:             $i++;
 2061:         }
 2062:         return %returnhash;
 2063:     } else {
 2064:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2065:     }
 2066: }
 2067: 
 2068: # -------------------------------------------- put items in domain db files 
 2069: 
 2070: sub put_dom {
 2071:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2072:     if (!$udom) {
 2073:         $udom=$env{'user.domain'};
 2074:         if (defined(&domain($udom,'primary'))) {
 2075:             $uhome=&domain($udom,'primary');
 2076:         } else {
 2077:             undef($uhome);
 2078:         }
 2079:     } else {
 2080:         if (!$uhome) {
 2081:             if (defined(&domain($udom,'primary'))) {
 2082:                 $uhome=&domain($udom,'primary');
 2083:             }
 2084:         }
 2085:     } 
 2086:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2087:         my $items='';
 2088:         foreach my $item (keys(%$storehash)) {
 2089:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2090:         }
 2091:         $items=~s/\&$//;
 2092:         if ($namespace =~ /^enc/) {
 2093:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2094:         } else {
 2095:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2096:         }
 2097:     } else {
 2098:         &logthis("put_dom failed - no homeserver and/or domain");
 2099:     }
 2100: }
 2101: 
 2102: # --------------------- newput for items in db file owned by domainconfig user
 2103: sub newput_dom {
 2104:     my ($namespace,$storehash,$udom) = @_;
 2105:     my $result;
 2106:     if (!$udom) {
 2107:         $udom=$env{'user.domain'};
 2108:     }
 2109:     if ($udom) {
 2110:         my $uname = &get_domainconfiguser($udom);
 2111:         $result = &newput($namespace,$storehash,$udom,$uname);
 2112:     }
 2113:     return $result;
 2114: }
 2115: 
 2116: # --------------------- delete for items in db file owned by domainconfig user
 2117: sub del_dom {
 2118:     my ($namespace,$storearr,$udom)=@_;
 2119:     if (ref($storearr) eq 'ARRAY') {
 2120:         if (!$udom) {
 2121:             $udom=$env{'user.domain'};
 2122:         }
 2123:         if ($udom) {
 2124:             my $uname = &get_domainconfiguser($udom); 
 2125:             return &del($namespace,$storearr,$udom,$uname);
 2126:         }
 2127:     }
 2128: }
 2129: 
 2130: # ----------------------------------construct domainconfig user for a domain 
 2131: sub get_domainconfiguser {
 2132:     my ($udom) = @_;
 2133:     return $udom.'-domainconfig';
 2134: }
 2135: 
 2136: sub retrieve_inst_usertypes {
 2137:     my ($udom) = @_;
 2138:     my (%returnhash,@order);
 2139:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2140:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2141:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2142:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2143:     } else {
 2144:         if (defined(&domain($udom,'primary'))) {
 2145:             my $uhome=&domain($udom,'primary');
 2146:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2147:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2148:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2149:                 return (\%returnhash,\@order);
 2150:             }
 2151:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2152:             my @pairs=split(/\&/,$hashitems);
 2153:             foreach my $item (@pairs) {
 2154:                 my ($key,$value)=split(/=/,$item,2);
 2155:                 $key = &unescape($key);
 2156:                 next if ($key =~ /^error: 2 /);
 2157:                 $returnhash{$key}=&thaw_unescape($value);
 2158:             }
 2159:             my @esc_order = split(/\&/,$orderitems);
 2160:             foreach my $item (@esc_order) {
 2161:                 push(@order,&unescape($item));
 2162:             }
 2163:         } else {
 2164:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2165:         }
 2166:         return (\%returnhash,\@order);
 2167:     }
 2168: }
 2169: 
 2170: sub is_domainimage {
 2171:     my ($url) = @_;
 2172:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2173:         if (&domain($1) ne '') {
 2174:             return '1';
 2175:         }
 2176:     }
 2177:     return;
 2178: }
 2179: 
 2180: sub inst_directory_query {
 2181:     my ($srch) = @_;
 2182:     my $udom = $srch->{'srchdomain'};
 2183:     my %results;
 2184:     my $homeserver = &domain($udom,'primary');
 2185:     my $outcome;
 2186:     if ($homeserver ne '') {
 2187:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2188:             if ($srch->{'srchby'} eq 'email') {
 2189:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2190:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2191:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2192:                     (($major == 2) && ($minor < 12))) {
 2193:                     return;
 2194:                 }
 2195:             }
 2196:         }
 2197: 	my $queryid=&reply("querysend:instdirsearch:".
 2198: 			   &escape($srch->{'srchby'}).':'.
 2199: 			   &escape($srch->{'srchterm'}).':'.
 2200: 			   &escape($srch->{'srchtype'}),$homeserver);
 2201: 	my $host=&hostname($homeserver);
 2202: 	if ($queryid !~/^\Q$host\E\_/) {
 2203: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2204: 	    return;
 2205: 	}
 2206: 	my $response = &get_query_reply($queryid);
 2207: 	my $maxtries = 5;
 2208: 	my $tries = 1;
 2209: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2210: 	    $response = &get_query_reply($queryid);
 2211: 	    $tries ++;
 2212: 	}
 2213: 
 2214:         if (!&error($response) && $response ne 'refused') {
 2215:             if ($response eq 'unavailable') {
 2216:                 $outcome = $response;
 2217:             } else {
 2218:                 $outcome = 'ok';
 2219:                 my @matches = split(/\n/,$response);
 2220:                 foreach my $match (@matches) {
 2221:                     my ($key,$value) = split(/=/,$match);
 2222:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2223:                 }
 2224:             }
 2225:         }
 2226:     }
 2227:     return ($outcome,%results);
 2228: }
 2229: 
 2230: sub usersearch {
 2231:     my ($srch) = @_;
 2232:     my $dom = $srch->{'srchdomain'};
 2233:     my %results;
 2234:     my %libserv = &all_library();
 2235:     my $query = 'usersearch';
 2236:     foreach my $tryserver (keys(%libserv)) {
 2237:         if (&host_domain($tryserver) eq $dom) {
 2238:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2239:                 if ($srch->{'srchby'} eq 'email') {
 2240:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2241:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2242:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2243:                              (($major == 2) && ($minor < 12)));
 2244:                 }
 2245:             }
 2246:             my $host=&hostname($tryserver);
 2247:             my $queryid=
 2248:                 &reply("querysend:".&escape($query).':'.
 2249:                        &escape($srch->{'srchby'}).':'.
 2250:                        &escape($srch->{'srchtype'}).':'.
 2251:                        &escape($srch->{'srchterm'}),$tryserver);
 2252:             if ($queryid !~/^\Q$host\E\_/) {
 2253:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2254:                 next;
 2255:             }
 2256:             my $reply = &get_query_reply($queryid);
 2257:             my $maxtries = 1;
 2258:             my $tries = 1;
 2259:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2260:                 $reply = &get_query_reply($queryid);
 2261:                 $tries ++;
 2262:             }
 2263:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2264:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2265:             } else {
 2266:                 my @matches;
 2267:                 if ($reply =~ /\n/) {
 2268:                     @matches = split(/\n/,$reply);
 2269:                 } else {
 2270:                     @matches = split(/\&/,$reply);
 2271:                 }
 2272:                 foreach my $match (@matches) {
 2273:                     my ($uname,$udom,%userhash);
 2274:                     foreach my $entry (split(/:/,$match)) {
 2275:                         my ($key,$value) =
 2276:                             map {&unescape($_);} split(/=/,$entry);
 2277:                         $userhash{$key} = $value;
 2278:                         if ($key eq 'username') {
 2279:                             $uname = $value;
 2280:                         } elsif ($key eq 'domain') {
 2281:                             $udom = $value;
 2282:                         }
 2283:                     }
 2284:                     $results{$uname.':'.$udom} = \%userhash;
 2285:                 }
 2286:             }
 2287:         }
 2288:     }
 2289:     return %results;
 2290: }
 2291: 
 2292: sub get_instuser {
 2293:     my ($udom,$uname,$id) = @_;
 2294:     my $homeserver = &domain($udom,'primary');
 2295:     my ($outcome,%results);
 2296:     if ($homeserver ne '') {
 2297:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2298:                            &escape($id).':'.&escape($udom),$homeserver);
 2299:         my $host=&hostname($homeserver);
 2300:         if ($queryid !~/^\Q$host\E\_/) {
 2301:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2302:             return;
 2303:         }
 2304:         my $response = &get_query_reply($queryid);
 2305:         my $maxtries = 5;
 2306:         my $tries = 1;
 2307:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2308:             $response = &get_query_reply($queryid);
 2309:             $tries ++;
 2310:         }
 2311:         if (!&error($response) && $response ne 'refused') {
 2312:             if ($response eq 'unavailable') {
 2313:                 $outcome = $response;
 2314:             } else {
 2315:                 $outcome = 'ok';
 2316:                 my @matches = split(/\n/,$response);
 2317:                 foreach my $match (@matches) {
 2318:                     my ($key,$value) = split(/=/,$match);
 2319:                     $results{&unescape($key)} = &thaw_unescape($value);
 2320:                 }
 2321:             }
 2322:         }
 2323:     }
 2324:     my %userinfo;
 2325:     if (ref($results{$uname}) eq 'HASH') {
 2326:         %userinfo = %{$results{$uname}};
 2327:     } 
 2328:     return ($outcome,%userinfo);
 2329: }
 2330: 
 2331: sub get_multiple_instusers {
 2332:     my ($udom,$users,$caller) = @_;
 2333:     my ($outcome,$results);
 2334:     if (ref($users) eq 'HASH') {
 2335:         my $count = keys(%{$users}); 
 2336:         my $requested = &freeze_escape($users);
 2337:         my $homeserver = &domain($udom,'primary');
 2338:         if ($homeserver ne '') {
 2339:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2340:             my $host=&hostname($homeserver);
 2341:             if ($queryid !~/^\Q$host\E\_/) {
 2342:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2343:                          ' for host: '.$homeserver.'in domain '.$udom);
 2344:                 return ($outcome,$results);
 2345:             }
 2346:             my $response = &get_query_reply($queryid);
 2347:             my $maxtries = 5;
 2348:             if ($count > 100) {
 2349:                 $maxtries = 1+int($count/20);
 2350:             }
 2351:             my $tries = 1;
 2352:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2353:                 $response = &get_query_reply($queryid);
 2354:                 $tries ++;
 2355:             }
 2356:             if ($response eq '') {
 2357:                 $results = {};
 2358:                 foreach my $key (keys(%{$users})) {
 2359:                     my ($uname,$id);
 2360:                     if ($caller eq 'id') {
 2361:                         $id = $key;
 2362:                     } else {
 2363:                         $uname = $key;
 2364:                     }
 2365:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2366:                     $outcome = $resp;
 2367:                     if ($resp eq 'ok') {
 2368:                         %{$results} = (%{$results}, %info);
 2369:                     } else {
 2370:                         last;
 2371:                     }
 2372:                 }
 2373:             } elsif(!&error($response) && ($response ne 'refused')) {
 2374:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2375:                     $outcome = $response;
 2376:                 } else {
 2377:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2378:                     if ($outcome eq 'ok') {
 2379:                         $results = &thaw_unescape($userdata); 
 2380:                     }
 2381:                 }
 2382:             }
 2383:         }
 2384:     }
 2385:     return ($outcome,$results);
 2386: }
 2387: 
 2388: sub inst_rulecheck {
 2389:     my ($udom,$uname,$id,$item,$rules) = @_;
 2390:     my %returnhash;
 2391:     if ($udom ne '') {
 2392:         if (ref($rules) eq 'ARRAY') {
 2393:             @{$rules} = map {&escape($_);} (@{$rules});
 2394:             my $rulestr = join(':',@{$rules});
 2395:             my $homeserver=&domain($udom,'primary');
 2396:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2397:                 my $response;
 2398:                 if ($item eq 'username') {                
 2399:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2400:                                               ':'.&escape($uname).':'.$rulestr,
 2401:                                               $homeserver));
 2402:                 } elsif ($item eq 'id') {
 2403:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2404:                                               ':'.&escape($id).':'.$rulestr,
 2405:                                               $homeserver));
 2406:                 } elsif ($item eq 'selfcreate') {
 2407:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2408:                                                &escape($udom).':'.&escape($uname).
 2409:                                               ':'.$rulestr,$homeserver));
 2410:                 }
 2411:                 if ($response ne 'refused') {
 2412:                     my @pairs=split(/\&/,$response);
 2413:                     foreach my $item (@pairs) {
 2414:                         my ($key,$value)=split(/=/,$item,2);
 2415:                         $key = &unescape($key);
 2416:                         next if ($key =~ /^error: 2 /);
 2417:                         $returnhash{$key}=&thaw_unescape($value);
 2418:                     }
 2419:                 }
 2420:             }
 2421:         }
 2422:     }
 2423:     return %returnhash;
 2424: }
 2425: 
 2426: sub inst_userrules {
 2427:     my ($udom,$check) = @_;
 2428:     my (%ruleshash,@ruleorder);
 2429:     if ($udom ne '') {
 2430:         my $homeserver=&domain($udom,'primary');
 2431:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2432:             my $response;
 2433:             if ($check eq 'id') {
 2434:                 $response=&reply('instidrules:'.&escape($udom),
 2435:                                  $homeserver);
 2436:             } elsif ($check eq 'email') {
 2437:                 $response=&reply('instemailrules:'.&escape($udom),
 2438:                                  $homeserver);
 2439:             } else {
 2440:                 $response=&reply('instuserrules:'.&escape($udom),
 2441:                                  $homeserver);
 2442:             }
 2443:             if (($response ne 'refused') && ($response ne 'error') && 
 2444:                 ($response ne 'unknown_cmd') && 
 2445:                 ($response ne 'no_such_host')) {
 2446:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2447:                 my @pairs=split(/\&/,$hashitems);
 2448:                 foreach my $item (@pairs) {
 2449:                     my ($key,$value)=split(/=/,$item,2);
 2450:                     $key = &unescape($key);
 2451:                     next if ($key =~ /^error: 2 /);
 2452:                     $ruleshash{$key}=&thaw_unescape($value);
 2453:                 }
 2454:                 my @esc_order = split(/\&/,$orderitems);
 2455:                 foreach my $item (@esc_order) {
 2456:                     push(@ruleorder,&unescape($item));
 2457:                 }
 2458:             }
 2459:         }
 2460:     }
 2461:     return (\%ruleshash,\@ruleorder);
 2462: }
 2463: 
 2464: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2465: 
 2466: sub get_domain_defaults {
 2467:     my ($domain,$ignore_cache) = @_;
 2468:     return if (($domain eq '') || ($domain eq 'public'));
 2469:     my $cachetime = 60*60*24;
 2470:     unless ($ignore_cache) {
 2471:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2472:         if (defined($cached)) {
 2473:             if (ref($result) eq 'HASH') {
 2474:                 return %{$result};
 2475:             }
 2476:         }
 2477:     }
 2478:     my %domdefaults;
 2479:     my %domconfig =
 2480:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2481:                                   'requestcourses','inststatus',
 2482:                                   'coursedefaults','usersessions',
 2483:                                   'requestauthor','selfenrollment',
 2484:                                   'coursecategories','ssl','autoenroll',
 2485:                                   'trust','helpsettings'],$domain);
 2486:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2487:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2488:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2489:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2490:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2491:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2492:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2493:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2494:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2495:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2496:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2497:     } else {
 2498:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2499:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2500:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2501:     }
 2502:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2503:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2504:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2505:         } else {
 2506:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2507:         }
 2508:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2509:         foreach my $item (@usertools) {
 2510:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2511:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2512:             }
 2513:         }
 2514:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2515:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2516:         }
 2517:     }
 2518:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2519:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2520:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2521:         }
 2522:     }
 2523:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2524:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2525:     }
 2526:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2527:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2528:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2529:         }
 2530:     }
 2531:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2532:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2533:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2534:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2535:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2536:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2537:         }
 2538:         foreach my $type (@coursetypes) {
 2539:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2540:                 unless ($type eq 'community') {
 2541:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2542:                 }
 2543:             }
 2544:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2545:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2546:             }
 2547:             if ($domdefaults{'postsubmit'} eq 'on') {
 2548:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2549:                     $domdefaults{$type.'postsubtimeout'} = 
 2550:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2551:                 }
 2552:             }
 2553:         }
 2554:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2555:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2556:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2557:                 if (@clonecodes) {
 2558:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2559:                 }
 2560:             }
 2561:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2562:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2563:         }
 2564:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2565:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2566:         } 
 2567:     }
 2568:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2569:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2570:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2571:         }
 2572:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2573:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2574:         }
 2575:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2576:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2577:         }
 2578:     }
 2579:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2580:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2581:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2582:                             'approval','limit');
 2583:             foreach my $type (@coursetypes) {
 2584:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2585:                     my @mgrdc = ();
 2586:                     foreach my $item (@settings) {
 2587:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2588:                             push(@mgrdc,$item);
 2589:                         }
 2590:                     }
 2591:                     if (@mgrdc) {
 2592:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2593:                     }
 2594:                 }
 2595:             }
 2596:         }
 2597:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2598:             foreach my $type (@coursetypes) {
 2599:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2600:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2601:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2602:                     }
 2603:                 }
 2604:             }
 2605:         }
 2606:     }
 2607:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2608:         $domdefaults{'catauth'} = 'std';
 2609:         $domdefaults{'catunauth'} = 'std';
 2610:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2611:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2612:         }
 2613:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2614:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2615:         }
 2616:     }
 2617:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2618:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2619:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2620:         }
 2621:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2622:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2623:         }
 2624:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2625:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2626:         }
 2627:     }
 2628:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2629:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2630:         foreach my $prefix (@prefixes) {
 2631:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2632:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2633:             }
 2634:         }
 2635:     }
 2636:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2637:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2638:     }
 2639:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2640:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2641:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2642:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2643:         }
 2644:     }
 2645:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2646:     return %domdefaults;
 2647: }
 2648: 
 2649: sub course_portal_url {
 2650:     my ($cnum,$cdom) = @_;
 2651:     my $chome = &homeserver($cnum,$cdom);
 2652:     my $hostname = &hostname($chome);
 2653:     my $protocol = $protocol{$chome};
 2654:     $protocol = 'http' if ($protocol ne 'https');
 2655:     my %domdefaults = &get_domain_defaults($cdom);
 2656:     my $firsturl;
 2657:     if ($domdefaults{'portal_def'}) {
 2658:         $firsturl = $domdefaults{'portal_def'};
 2659:     } else {
 2660:         $firsturl = $protocol.'://'.$hostname;
 2661:     }
 2662:     return $firsturl;
 2663: }
 2664: 
 2665: # --------------------------------------------------- Assign a key to a student
 2666: 
 2667: sub assign_access_key {
 2668: #
 2669: # a valid key looks like uname:udom#comments
 2670: # comments are being appended
 2671: #
 2672:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2673:     $kdom=
 2674:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2675:     $knum=
 2676:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2677:     $cdom=
 2678:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2679:     $cnum=
 2680:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2681:     $udom=$env{'user.name'} unless (defined($udom));
 2682:     $uname=$env{'user.domain'} unless (defined($uname));
 2683:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2684:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2685:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2686:                                                   # assigned to this person
 2687:                                                   # - this should not happen,
 2688:                                                   # unless something went wrong
 2689:                                                   # the first time around
 2690: # ready to assign
 2691:         $logentry=$1.'; '.$logentry;
 2692:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2693:                                                  $kdom,$knum) eq 'ok') {
 2694: # key now belongs to user
 2695: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2696:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2697:                 &appenv({'environment.'.$envkey => $ckey});
 2698:                 return 'ok';
 2699:             } else {
 2700:                 return 
 2701:   'error: Count not permanently assign key, will need to be re-entered later.';
 2702: 	    }
 2703:         } else {
 2704:             return 'error: Could not assign key, try again later.';
 2705:         }
 2706:     } elsif (!$existing{$ckey}) {
 2707: # the key does not exist
 2708: 	return 'error: The key does not exist';
 2709:     } else {
 2710: # the key is somebody else's
 2711: 	return 'error: The key is already in use';
 2712:     }
 2713: }
 2714: 
 2715: # ------------------------------------------ put an additional comment on a key
 2716: 
 2717: sub comment_access_key {
 2718: #
 2719: # a valid key looks like uname:udom#comments
 2720: # comments are being appended
 2721: #
 2722:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2723:     $cdom=
 2724:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2725:     $cnum=
 2726:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2727:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2728:     if ($existing{$ckey}) {
 2729:         $existing{$ckey}.='; '.$logentry;
 2730: # ready to assign
 2731:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2732:                                                  $cdom,$cnum) eq 'ok') {
 2733: 	    return 'ok';
 2734:         } else {
 2735: 	    return 'error: Count not store comment.';
 2736:         }
 2737:     } else {
 2738: # the key does not exist
 2739: 	return 'error: The key does not exist';
 2740:     }
 2741: }
 2742: 
 2743: # ------------------------------------------------------ Generate a set of keys
 2744: 
 2745: sub generate_access_keys {
 2746:     my ($number,$cdom,$cnum,$logentry)=@_;
 2747:     $cdom=
 2748:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2749:     $cnum=
 2750:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2751:     unless (&allowed('mky',$cdom)) { return 0; }
 2752:     unless (($cdom) && ($cnum)) { return 0; }
 2753:     if ($number>10000) { return 0; }
 2754:     sleep(2); # make sure don't get same seed twice
 2755:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2756:     my $total=0;
 2757:     for (my $i=1;$i<=$number;$i++) {
 2758:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2759:                   sprintf("%lx",int(100000*rand)).'-'.
 2760:                   sprintf("%lx",int(100000*rand));
 2761:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2762:        $newkey=~s/0/h/g; # and also 0 and O
 2763:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2764:        if ($existing{$newkey}) {
 2765:            $i--;
 2766:        } else {
 2767: 	  if (&put('accesskeys',
 2768:               { $newkey => '# generated '.localtime().
 2769:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2770:                            '; '.$logentry },
 2771: 		   $cdom,$cnum) eq 'ok') {
 2772:               $total++;
 2773: 	  }
 2774:        }
 2775:     }
 2776:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2777:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2778:     return $total;
 2779: }
 2780: 
 2781: # ------------------------------------------------------- Validate an accesskey
 2782: 
 2783: sub validate_access_key {
 2784:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2785:     $cdom=
 2786:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2787:     $cnum=
 2788:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2789:     $udom=$env{'user.domain'} unless (defined($udom));
 2790:     $uname=$env{'user.name'} unless (defined($uname));
 2791:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2792:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2793: }
 2794: 
 2795: # ------------------------------------- Find the section of student in a course
 2796: sub devalidate_getsection_cache {
 2797:     my ($udom,$unam,$courseid)=@_;
 2798:     my $hashid="$udom:$unam:$courseid";
 2799:     &devalidate_cache_new('getsection',$hashid);
 2800: }
 2801: 
 2802: sub courseid_to_courseurl {
 2803:     my ($courseid) = @_;
 2804:     #already url style courseid
 2805:     return $courseid if ($courseid =~ m{^/});
 2806: 
 2807:     if (exists($env{'course.'.$courseid.'.num'})) {
 2808: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2809: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2810: 	return "/$cdom/$cnum";
 2811:     }
 2812: 
 2813:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2814:     if (exists($courseinfo{'num'})) {
 2815: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2816:     }
 2817: 
 2818:     return undef;
 2819: }
 2820: 
 2821: sub getsection {
 2822:     my ($udom,$unam,$courseid)=@_;
 2823:     my $cachetime=1800;
 2824: 
 2825:     my $hashid="$udom:$unam:$courseid";
 2826:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2827:     if (defined($cached)) { return $result; }
 2828: 
 2829:     my %Pending; 
 2830:     my %Expired;
 2831:     #
 2832:     # Each role can either have not started yet (pending), be active, 
 2833:     #    or have expired.
 2834:     #
 2835:     # If there is an active role, we are done.
 2836:     #
 2837:     # If there is more than one role which has not started yet, 
 2838:     #     choose the one which will start sooner
 2839:     # If there is one role which has not started yet, return it.
 2840:     #
 2841:     # If there is more than one expired role, choose the one which ended last.
 2842:     # If there is a role which has expired, return it.
 2843:     #
 2844:     $courseid = &courseid_to_courseurl($courseid);
 2845:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2846:     foreach my $key (keys(%roleshash)) {
 2847:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2848:         my $section=$1;
 2849:         if ($key eq $courseid.'_st') { $section=''; }
 2850:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2851:         my $now=time;
 2852:         if (defined($end) && $end && ($now > $end)) {
 2853:             $Expired{$end}=$section;
 2854:             next;
 2855:         }
 2856:         if (defined($start) && $start && ($now < $start)) {
 2857:             $Pending{$start}=$section;
 2858:             next;
 2859:         }
 2860:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2861:     }
 2862:     #
 2863:     # Presumedly there will be few matching roles from the above
 2864:     # loop and the sorting time will be negligible.
 2865:     if (scalar(keys(%Pending))) {
 2866:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2867:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2868:     } 
 2869:     if (scalar(keys(%Expired))) {
 2870:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2871:         my $time = pop(@sorted);
 2872:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2873:     }
 2874:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2875: }
 2876: 
 2877: sub save_cache {
 2878:     &purge_remembered();
 2879:     #&Apache::loncommon::validate_page();
 2880:     undef(%env);
 2881:     undef($env_loaded);
 2882: }
 2883: 
 2884: my $to_remember=-1;
 2885: my %remembered;
 2886: my %accessed;
 2887: my $kicks=0;
 2888: my $hits=0;
 2889: sub make_key {
 2890:     my ($name,$id) = @_;
 2891:     if (length($id) > 65 
 2892: 	&& length(&escape($id)) > 200) {
 2893: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2894:     }
 2895:     return &escape($name.':'.$id);
 2896: }
 2897: 
 2898: sub devalidate_cache_new {
 2899:     my ($name,$id,$debug) = @_;
 2900:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2901:     my $remembered_id=$name.':'.$id;
 2902:     $id=&make_key($name,$id);
 2903:     $memcache->delete($id);
 2904:     delete($remembered{$remembered_id});
 2905:     delete($accessed{$remembered_id});
 2906: }
 2907: 
 2908: sub is_cached_new {
 2909:     my ($name,$id,$debug) = @_;
 2910:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2911:     if (exists($remembered{$remembered_id})) {
 2912: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2913: 	$accessed{$remembered_id}=[&gettimeofday()];
 2914: 	$hits++;
 2915: 	return ($remembered{$remembered_id},1);
 2916:     }
 2917:     $id=&make_key($name,$id);
 2918:     my $value = $memcache->get($id);
 2919:     if (!(defined($value))) {
 2920: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2921: 	return (undef,undef);
 2922:     }
 2923:     if ($value eq '__undef__') {
 2924: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2925: 	$value=undef;
 2926:     }
 2927:     &make_room($remembered_id,$value,$debug);
 2928:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2929:     return ($value,1);
 2930: }
 2931: 
 2932: sub do_cache_new {
 2933:     my ($name,$id,$value,$time,$debug) = @_;
 2934:     my $remembered_id=$name.':'.$id;
 2935:     $id=&make_key($name,$id);
 2936:     my $setvalue=$value;
 2937:     if (!defined($setvalue)) {
 2938: 	$setvalue='__undef__';
 2939:     }
 2940:     if (!defined($time) ) {
 2941: 	$time=600;
 2942:     }
 2943:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2944:     my $result = $memcache->set($id,$setvalue,$time);
 2945:     if (! $result) {
 2946: 	&logthis("caching of id -> $id  failed");
 2947: 	$memcache->disconnect_all();
 2948:     }
 2949:     # need to make a copy of $value
 2950:     &make_room($remembered_id,$value,$debug);
 2951:     return $value;
 2952: }
 2953: 
 2954: sub make_room {
 2955:     my ($remembered_id,$value,$debug)=@_;
 2956: 
 2957:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2958:                                     : $value;
 2959:     if ($to_remember<0) { return; }
 2960:     $accessed{$remembered_id}=[&gettimeofday()];
 2961:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2962:     my $to_kick;
 2963:     my $max_time=0;
 2964:     foreach my $other (keys(%accessed)) {
 2965: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2966: 	    $to_kick=$other;
 2967: 	    $max_time=&tv_interval($accessed{$other});
 2968: 	}
 2969:     }
 2970:     delete($remembered{$to_kick});
 2971:     delete($accessed{$to_kick});
 2972:     $kicks++;
 2973:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2974:     return;
 2975: }
 2976: 
 2977: sub purge_remembered {
 2978:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2979:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2980:     undef(%remembered);
 2981:     undef(%accessed);
 2982: }
 2983: # ------------------------------------- Read an entry from a user's environment
 2984: 
 2985: sub userenvironment {
 2986:     my ($udom,$unam,@what)=@_;
 2987:     my $items;
 2988:     foreach my $item (@what) {
 2989:         $items.=&escape($item).'&';
 2990:     }
 2991:     $items=~s/\&$//;
 2992:     my %returnhash=();
 2993:     my $uhome = &homeserver($unam,$udom);
 2994:     unless ($uhome eq 'no_host') {
 2995:         my @answer=split(/\&/, 
 2996:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2997:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2998:             return %returnhash;
 2999:         }
 3000:         my $i;
 3001:         for ($i=0;$i<=$#what;$i++) {
 3002: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3003:         }
 3004:     }
 3005:     return %returnhash;
 3006: }
 3007: 
 3008: # ---------------------------------------------------------- Get a studentphoto
 3009: sub studentphoto {
 3010:     my ($udom,$unam,$ext) = @_;
 3011:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3012:     if (defined($env{'request.course.id'})) {
 3013:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3014:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3015:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3016:             } else {
 3017:                 my ($result,$perm_reqd)=
 3018: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3019:                 if ($result eq 'ok') {
 3020:                     if (!($perm_reqd eq 'yes')) {
 3021:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3022:                     }
 3023:                 }
 3024:             }
 3025:         }
 3026:     } else {
 3027:         my ($result,$perm_reqd) = 
 3028: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3029:         if ($result eq 'ok') {
 3030:             if (!($perm_reqd eq 'yes')) {
 3031:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3032:             }
 3033:         }
 3034:     }
 3035:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3036: }
 3037: 
 3038: sub retrievestudentphoto {
 3039:     my ($udom,$unam,$ext,$type) = @_;
 3040:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3041:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3042:     if ($ret eq 'ok') {
 3043:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3044:         if ($type eq 'thumbnail') {
 3045:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3046:         }
 3047:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3048:         return $tokenurl;
 3049:     } else {
 3050:         if ($type eq 'thumbnail') {
 3051:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3052:         } else { 
 3053:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3054:         }
 3055:     }
 3056: }
 3057: 
 3058: # -------------------------------------------------------------------- New chat
 3059: 
 3060: sub chatsend {
 3061:     my ($newentry,$anon,$group)=@_;
 3062:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3063:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3064:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3065:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3066: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3067: 		   &escape($newentry)).':'.$group,$chome);
 3068: }
 3069: 
 3070: # ------------------------------------------ Find current version of a resource
 3071: 
 3072: sub getversion {
 3073:     my $fname=&clutter(shift);
 3074:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3075:     return &currentversion(&filelocation('',$fname));
 3076: }
 3077: 
 3078: sub currentversion {
 3079:     my $fname=shift;
 3080:     my $author=$fname;
 3081:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3082:     my ($udom,$uname)=split(/\//,$author);
 3083:     my $home=&homeserver($uname,$udom);
 3084:     if ($home eq 'no_host') { 
 3085:         return -1; 
 3086:     }
 3087:     my $answer=&reply("currentversion:$fname",$home);
 3088:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3089: 	return -1;
 3090:     }
 3091:     return $answer;
 3092: }
 3093: 
 3094: #
 3095: # Return special version number of resource if set by override, empty otherwise
 3096: #
 3097: sub usedversion {
 3098:     my $fname=shift;
 3099:     unless ($fname) { $fname=$env{'request.uri'}; }
 3100:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3101:     if ($urlversion) { return $urlversion; }
 3102:     return '';
 3103: }
 3104: 
 3105: # ----------------------------- Subscribe to a resource, return URL if possible
 3106: 
 3107: sub subscribe {
 3108:     my $fname=shift;
 3109:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3110:     $fname=~s/[\n\r]//g;
 3111:     my $author=$fname;
 3112:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3113:     my ($udom,$uname)=split(/\//,$author);
 3114:     my $home=homeserver($uname,$udom);
 3115:     if ($home eq 'no_host') {
 3116:         return 'not_found';
 3117:     }
 3118:     my $answer=reply("sub:$fname",$home);
 3119:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3120: 	$answer.=' by '.$home;
 3121:     }
 3122:     return $answer;
 3123: }
 3124:     
 3125: # -------------------------------------------------------------- Replicate file
 3126: 
 3127: sub repcopy {
 3128:     my $filename=shift;
 3129:     $filename=~s/\/+/\//g;
 3130:     my $londocroot = $perlvar{'lonDocRoot'};
 3131:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3132:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3133:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3134: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3135: 	return &repcopy_userfile($filename);
 3136:     }
 3137:     $filename=~s/[\n\r]//g;
 3138:     my $transname="$filename.in.transfer";
 3139: # FIXME: this should flock
 3140:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3141:     my $remoteurl=subscribe($filename);
 3142:     if ($remoteurl =~ /^con_lost by/) {
 3143: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3144:            return 'unavailable';
 3145:     } elsif ($remoteurl eq 'not_found') {
 3146: 	   #&logthis("Subscribe returned not_found: $filename");
 3147: 	   return 'not_found';
 3148:     } elsif ($remoteurl =~ /^rejected by/) {
 3149: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3150:            return 'forbidden';
 3151:     } elsif ($remoteurl eq 'directory') {
 3152:            return 'ok';
 3153:     } else {
 3154:         my $author=$filename;
 3155:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3156:         my ($udom,$uname)=split(/\//,$author);
 3157:         my $home=homeserver($uname,$udom);
 3158:         unless ($home eq $perlvar{'lonHostID'}) {
 3159:            my @parts=split(/\//,$filename);
 3160:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3161:            if ($path ne "$londocroot/res") {
 3162:                &logthis("Malconfiguration for replication: $filename");
 3163: 	       return 'bad_request';
 3164:            }
 3165:            my $count;
 3166:            for ($count=5;$count<$#parts;$count++) {
 3167:                $path.="/$parts[$count]";
 3168:                if ((-e $path)!=1) {
 3169: 		   mkdir($path,0777);
 3170:                }
 3171:            }
 3172:            my $request=new HTTP::Request('GET',"$remoteurl");
 3173:            my $response;
 3174:            if ($remoteurl =~ m{/raw/}) {
 3175:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3176:            } else {
 3177:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3178:            }
 3179:            if ($response->is_error()) {
 3180: 	       unlink($transname);
 3181:                my $message=$response->status_line;
 3182:                &logthis("<font color=\"blue\">WARNING:"
 3183:                        ." LWP get: $message: $filename</font>");
 3184:                return 'unavailable';
 3185:            } else {
 3186: 	       if ($remoteurl!~/\.meta$/) {
 3187:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3188:                   my $mresponse;
 3189:                   if ($remoteurl =~ m{/raw/}) {
 3190:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3191:                   } else {
 3192:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3193:                   }
 3194:                   if ($mresponse->is_error()) {
 3195: 		      unlink($filename.'.meta');
 3196:                       &logthis(
 3197:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3198:                   }
 3199: 	       }
 3200:                rename($transname,$filename);
 3201:                return 'ok';
 3202:            }
 3203:        }
 3204:     }
 3205: }
 3206: 
 3207: # ------------------------------------------------ Get server side include body
 3208: sub ssi_body {
 3209:     my ($filelink,%form)=@_;
 3210:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3211:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3212:     }
 3213:     my $output='';
 3214:     my $response;
 3215:     if ($filelink=~/^https?\:/) {
 3216:        ($output,$response)=&externalssi($filelink);
 3217:     } else {
 3218:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3219:        $filelink .= 'inhibitmenu=yes';
 3220:        ($output,$response)=&ssi($filelink,%form);
 3221:     }
 3222:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3223:     $output=~s/^.*?\<body[^\>]*\>//si;
 3224:     $output=~s/\<\/body\s*\>.*?$//si;
 3225:     if (wantarray) {
 3226:         return ($output, $response);
 3227:     } else {
 3228:         return $output;
 3229:     }
 3230: }
 3231: 
 3232: # --------------------------------------------------------- Server Side Include
 3233: 
 3234: sub absolute_url {
 3235:     my ($host_name) = @_;
 3236:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3237:     if ($host_name eq '') {
 3238: 	$host_name = $ENV{'SERVER_NAME'};
 3239:     }
 3240:     return $protocol.$host_name;
 3241: }
 3242: 
 3243: #
 3244: #   Server side include.
 3245: # Parameters:
 3246: #  fn     Possibly encrypted resource name/id.
 3247: #  form   Hash that describes how the rendering should be done
 3248: #         and other things.
 3249: # Returns:
 3250: #   Scalar context: The content of the response.
 3251: #   Array context:  2 element list of the content and the full response object.
 3252: #     
 3253: sub ssi {
 3254: 
 3255:     my ($fn,%form)=@_;
 3256:     my $request;
 3257: 
 3258:     $form{'no_update_last_known'}=1;
 3259:     &Apache::lonenc::check_encrypt(\$fn);
 3260:     if (%form) {
 3261:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3262:       $request->content(join('&',map { 
 3263:             my $name = escape($_);
 3264:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3265:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3266:             : &escape($form{$_}) );    
 3267:         } keys(%form)));
 3268:     } else {
 3269:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3270:     }
 3271: 
 3272:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3273:     my $lonhost = $perlvar{'lonHostID'};
 3274:     my $islocal;
 3275:     if (($env{'request.course.id'}) &&
 3276:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3277:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3278:         ($form{'grade_symb'} ne '') &&
 3279:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3280:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3281:         $islocal = 1;
 3282:     }
 3283:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3284:                                                 '','','',$islocal);
 3285: 
 3286:     if (wantarray) {
 3287: 	return ($response->content, $response);
 3288:     } else {
 3289: 	return $response->content;
 3290:     }
 3291: }
 3292: 
 3293: sub externalssi {
 3294:     my ($url)=@_;
 3295:     my $request=new HTTP::Request('GET',$url);
 3296:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3297:     if (wantarray) {
 3298:         return ($response->content, $response);
 3299:     } else {
 3300:         return $response->content;
 3301:     }
 3302: }
 3303: 
 3304: 
 3305: # If the local copy of a replicated resource is outdated, trigger a  
 3306: # connection from the homeserver to flush the delayed queue. If no update 
 3307: # happens, remove local copies of outdated resource (and corresponding
 3308: # metadata file).
 3309: 
 3310: sub remove_stale_resfile {
 3311:     my ($url) = @_;
 3312:     my $removed;
 3313:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3314:         my $audom = $1;
 3315:         my $auname = $2;
 3316:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3317:             my $homeserver = &homeserver($auname,$audom);
 3318:             unless (($homeserver eq 'no_host') ||
 3319:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3320:                 my $fname = &filelocation('',$url);
 3321:                 if (-e $fname) {
 3322:                     my $protocol = $protocol{$homeserver};
 3323:                     $protocol = 'http' if ($protocol ne 'https');
 3324:                     my $hostname = &hostname($homeserver);
 3325:                     if ($hostname) {
 3326:                         my $uri = &declutter($url);
 3327:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3328:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3329:                         if ($response->is_success()) {
 3330:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3331:                             my $locmodtime = (stat($fname))[9];
 3332:                             if ($locmodtime < $remmodtime) {
 3333:                                 my $stale;
 3334:                                 my $answer = &reply('pong',$homeserver);
 3335:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3336:                                     sleep(0.2);
 3337:                                     $locmodtime = (stat($fname))[9];
 3338:                                     if ($locmodtime < $remmodtime) {
 3339:                                         my $posstransfer = $fname.'.in.transfer';
 3340:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3341:                                             $removed = 1;
 3342:                                         } else {
 3343:                                             $stale = 1;
 3344:                                         }
 3345:                                     } else {
 3346:                                         $removed = 1;
 3347:                                     }
 3348:                                 } else {
 3349:                                     $stale = 1;
 3350:                                 }
 3351:                                 if ($stale) {
 3352:                                     unlink($fname);
 3353:                                     if ($uri!~/\.meta$/) {
 3354:                                         unlink($fname.'.meta');
 3355:                                     }
 3356:                                     &reply("unsub:$fname",$homeserver);
 3357:                                     $removed = 1;
 3358:                                 }
 3359:                             }
 3360:                         }
 3361:                     }
 3362:                 }
 3363:             }
 3364:         }
 3365:     }
 3366:     return $removed;
 3367: }
 3368: 
 3369: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3370: 
 3371: sub allowuploaded {
 3372:     my ($srcurl,$url)=@_;
 3373:     $url=&clutter(&declutter($url));
 3374:     my $dir=$url;
 3375:     $dir=~s/\/[^\/]+$//;
 3376:     my %httpref=();
 3377:     my $httpurl=&hreflocation('',$url);
 3378:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3379:     &Apache::lonnet::appenv(\%httpref);
 3380: }
 3381: 
 3382: #
 3383: # Determine if the current user should be able to edit a particular resource,
 3384: # when viewing in course context.
 3385: # (a) When viewing resource used to determine if "Edit" item is included in 
 3386: #     Functions.
 3387: # (b) When displaying folder contents in course editor, used to determine if
 3388: #     "Edit" link will be displayed alongside resource.
 3389: #
 3390: #  input: six args -- filename (decluttered), course number, course domain,
 3391: #                   url, symb (if registered) and group (if this is a group
 3392: #                   item -- e.g., bulletin board, group page etc.).
 3393: #  output: array of five scalars -- 
 3394: #          $cfile -- url for file editing if editable on current server
 3395: #          $home -- homeserver of resource (i.e., for author if published,
 3396: #                                           or course if uploaded.).
 3397: #          $switchserver --  1 if server switch will be needed.
 3398: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3399: #          $forceview -- 1 if icon/link should be to go to view mode
 3400: #
 3401: 
 3402: sub can_edit_resource {
 3403:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3404:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3405: #
 3406: # For aboutme pages user can only edit his/her own.
 3407: #
 3408:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3409:         my ($sdom,$sname) = ($1,$2);
 3410:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3411:             $home = $env{'user.home'};
 3412:             $cfile = $resurl;
 3413:             if ($env{'form.forceedit'}) {
 3414:                 $forceview = 1;
 3415:             } else {
 3416:                 $forceedit = 1;
 3417:             }
 3418:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3419:         } else {
 3420:             return;
 3421:         }
 3422:     }
 3423: 
 3424:     if ($env{'request.course.id'}) {
 3425:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3426:         if ($group ne '') {
 3427: # if this is a group homepage or group bulletin board, check group privs
 3428:             my $allowed = 0;
 3429:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3430:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3431:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3432:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3433:                     $allowed = 1;
 3434:                 }
 3435:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3436:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3437:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3438:                     $allowed = 1;
 3439:                 }
 3440:             }
 3441:             if ($allowed) {
 3442:                 $home=&homeserver($cnum,$cdom);
 3443:                 if ($env{'form.forceedit'}) {
 3444:                     $forceview = 1;
 3445:                 } else {
 3446:                     $forceedit = 1;
 3447:                 }
 3448:                 $cfile = $resurl;
 3449:             } else {
 3450:                 return;
 3451:             }
 3452:         } else {
 3453:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3454:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3455:                     return;
 3456:                 }
 3457:             } elsif (!$crsedit) {
 3458: #
 3459: # No edit allowed where CC has switched to student role.
 3460: #
 3461:                 return;
 3462:             }
 3463:         }
 3464:     }
 3465: 
 3466:     if ($file ne '') {
 3467:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3468:             if (&is_course_upload($file,$cnum,$cdom)) {
 3469:                 $uploaded = 1;
 3470:                 $incourse = 1;
 3471:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3472:                     $cfile = &hreflocation('',$file);
 3473:                     if ($env{'form.forceedit'}) {
 3474:                         $forceview = 1;
 3475:                     } else {
 3476:                         $forceedit = 1;
 3477:                     }
 3478:                 }
 3479:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3480:                 $incourse = 1;
 3481:                 if ($env{'form.forceedit'}) {
 3482:                     $forceview = 1;
 3483:                 } else {
 3484:                     $forceedit = 1;
 3485:                 }
 3486:                 $cfile = $resurl;
 3487:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3488:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3489:                     $incourse = 1;
 3490:                     if ($env{'form.forceedit'}) {
 3491:                         $forceview = 1;
 3492:                     } else {
 3493:                         $forceedit = 1;
 3494:                     }
 3495:                     $cfile = $resurl;
 3496:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3497:                     $incourse = 1;
 3498:                     $cfile = $resurl.'/smpedit';
 3499:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3500:                     $incourse = 1;
 3501:                     if ($env{'form.forceedit'}) {
 3502:                         $forceview = 1;
 3503:                     } else {
 3504:                         $forceedit = 1;
 3505:                     }
 3506:                     $cfile = $resurl;
 3507:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3508:                     $incourse = 1;
 3509:                     if ($env{'form.forceedit'}) {
 3510:                         $forceview = 1;
 3511:                     } else {
 3512:                         $forceedit = 1;
 3513:                     }
 3514:                     $cfile = $resurl;
 3515:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3516:                     $incourse = 1;
 3517:                     if ($env{'form.forceedit'}) {
 3518:                         $forceview = 1;
 3519:                     } else {
 3520:                         $forceedit = 1;
 3521:                     }
 3522:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3523:                 }
 3524:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3525:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3526:                 if (&is_on_map($template)) { 
 3527:                     $incourse = 1;
 3528:                     $forceview = 1;
 3529:                     $cfile = $template;
 3530:                 }
 3531:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3532:                     $incourse = 1;
 3533:                     if ($env{'form.forceedit'}) {
 3534:                         $forceview = 1;
 3535:                     } else {
 3536:                         $forceedit = 1;
 3537:                     }
 3538:                     $cfile = $resurl;
 3539:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3540:                 $incourse = 1;
 3541:                 if ($env{'form.forceedit'}) {
 3542:                     $forceview = 1;
 3543:                 } else {
 3544:                     $forceedit = 1;
 3545:                 }
 3546:                 $cfile = $resurl;
 3547:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3548:                 $incourse = 1;
 3549:                 $forceview = 1;
 3550:                 if ($symb) {
 3551:                     my ($map,$id,$res)=&decode_symb($symb);
 3552:                     $env{'request.symb'} = $symb;
 3553:                     $cfile = &clutter($res);
 3554:                 } else {
 3555:                     $cfile = $env{'form.suppurl'};
 3556:                     my $escfile = &unescape($cfile);
 3557:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3558:                         $cfile = '/adm/wrapper'.$escfile;
 3559:                     } else {
 3560:                         $escfile =~ s{^http://}{};
 3561:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3562:                     }
 3563:                 }
 3564:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3565:                 if ($env{'form.forceedit'}) {
 3566:                     $forceview = 1;
 3567:                 } else {
 3568:                     $forceedit = 1;
 3569:                 }
 3570:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3571:             }
 3572:         }
 3573:         if ($uploaded || $incourse) {
 3574:             $home=&homeserver($cnum,$cdom);
 3575:         } elsif ($file !~ m{/$}) {
 3576:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3577:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3578:             # Check that the user has permission to edit this resource
 3579:             my $setpriv = 1;
 3580:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3581:             if (defined($cfudom)) {
 3582:                 $home=&homeserver($cfuname,$cfudom);
 3583:                 $cfile=$file;
 3584:             }
 3585:         }
 3586:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3587:             (($home ne '') && ($home ne 'no_host'))) {
 3588:             my @ids=&current_machine_ids();
 3589:             unless (grep(/^\Q$home\E$/,@ids)) {
 3590:                 $switchserver=1;
 3591:             }
 3592:         }
 3593:     }
 3594:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3595: }
 3596: 
 3597: sub is_course_upload {
 3598:     my ($file,$cnum,$cdom) = @_;
 3599:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3600:     $uploadpath =~ s{^\/}{};
 3601:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3602:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3603:         return 1;
 3604:     }
 3605:     return;
 3606: }
 3607: 
 3608: sub in_course {
 3609:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3610:     if ($hideprivileged) {
 3611:         my $skipuser;
 3612:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3613:         my @possdoms = ($cdom);  
 3614:         if ($coursehash{'checkforpriv'}) { 
 3615:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3616:         }
 3617:         if (&privileged($uname,$udom,\@possdoms)) {
 3618:             $skipuser = 1;
 3619:             if ($coursehash{'nothideprivileged'}) {
 3620:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3621:                     my $user;
 3622:                     if ($item =~ /:/) {
 3623:                         $user = $item;
 3624:                     } else {
 3625:                         $user = join(':',split(/[\@]/,$item));
 3626:                     }
 3627:                     if ($user eq $uname.':'.$udom) {
 3628:                         undef($skipuser);
 3629:                         last;
 3630:                     }
 3631:                 }
 3632:             }
 3633:             if ($skipuser) {
 3634:                 return 0;
 3635:             }
 3636:         }
 3637:     }
 3638:     $type ||= 'any';
 3639:     if (!defined($cdom) || !defined($cnum)) {
 3640:         my $cid  = $env{'request.course.id'};
 3641:         $cdom = $env{'course.'.$cid.'.domain'};
 3642:         $cnum = $env{'course.'.$cid.'.num'};
 3643:     }
 3644:     my $typesref;
 3645:     if (($type eq 'any') || ($type eq 'all')) {
 3646:         $typesref = ['active','previous','future'];
 3647:     } elsif ($type eq 'previous' || $type eq 'future') {
 3648:         $typesref = [$type];
 3649:     }
 3650:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3651:                               $typesref,undef,[$cdom]);
 3652:     my ($tmp) = keys(%roles);
 3653:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3654:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3655:     if (@course_roles > 0) {
 3656:         return 1;
 3657:     }
 3658:     return 0;
 3659: }
 3660: 
 3661: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3662: # input: action, courseID, current domain, intended
 3663: #        path to file, source of file, instruction to parse file for objects,
 3664: #        ref to hash for embedded objects,
 3665: #        ref to hash for codebase of java objects.
 3666: #        reference to scalar to accommodate mime type determined
 3667: #          from File::MMagic if $parser = parse.
 3668: #
 3669: # output: url to file (if action was uploaddoc), 
 3670: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3671: #
 3672: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3673: # course.
 3674: #
 3675: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3676: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3677: #          course's home server.
 3678: #
 3679: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3680: #          be copied from $source (current location) to 
 3681: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3682: #         and will then be copied to
 3683: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3684: #         course's home server.
 3685: #
 3686: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3687: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3688: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3689: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3690: #         in course's home server.
 3691: #
 3692: 
 3693: sub process_coursefile {
 3694:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3695:         $mimetype)=@_;
 3696:     my $fetchresult;
 3697:     my $home=&homeserver($docuname,$docudom);
 3698:     if ($action eq 'propagate') {
 3699:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3700: 			     $home);
 3701:     } else {
 3702:         my $fpath = '';
 3703:         my $fname = $file;
 3704:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3705:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3706:         my $filepath = &build_filepath($fpath);
 3707:         if ($action eq 'copy') {
 3708:             if ($source eq '') {
 3709:                 $fetchresult = 'no source file';
 3710:                 return $fetchresult;
 3711:             } else {
 3712:                 my $destination = $filepath.'/'.$fname;
 3713:                 rename($source,$destination);
 3714:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3715:                                  $home);
 3716:             }
 3717:         } elsif ($action eq 'uploaddoc') {
 3718:             open(my $fh,'>',$filepath.'/'.$fname);
 3719:             print $fh $env{'form.'.$source};
 3720:             close($fh);
 3721:             if ($parser eq 'parse') {
 3722:                 my $mm = new File::MMagic;
 3723:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3724:                 if ($type eq 'text/html') {
 3725:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3726:                     unless ($parse_result eq 'ok') {
 3727:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3728:                     }
 3729:                 }
 3730:                 if (ref($mimetype)) {
 3731:                     $$mimetype = $type;
 3732:                 } 
 3733:             }
 3734:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3735:                                  $home);
 3736:             if ($fetchresult eq 'ok') {
 3737:                 return '/uploaded/'.$fpath.'/'.$fname;
 3738:             } else {
 3739:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3740:                         ' to host '.$home.': '.$fetchresult);
 3741:                 return '/adm/notfound.html';
 3742:             }
 3743:         }
 3744:     }
 3745:     unless ( $fetchresult eq 'ok') {
 3746:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3747:              ' to host '.$home.': '.$fetchresult);
 3748:     }
 3749:     return $fetchresult;
 3750: }
 3751: 
 3752: sub build_filepath {
 3753:     my ($fpath) = @_;
 3754:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3755:     unless ($fpath eq '') {
 3756:         my @parts=split('/',$fpath);
 3757:         foreach my $part (@parts) {
 3758:             $filepath.= '/'.$part;
 3759:             if ((-e $filepath)!=1) {
 3760:                 mkdir($filepath,0777);
 3761:             }
 3762:         }
 3763:     }
 3764:     return $filepath;
 3765: }
 3766: 
 3767: sub store_edited_file {
 3768:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3769:     my $file = $primary_url;
 3770:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3771:     my $fpath = '';
 3772:     my $fname = $file;
 3773:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3774:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3775:     my $filepath = &build_filepath($fpath);
 3776:     open(my $fh,'>',$filepath.'/'.$fname);
 3777:     print $fh $content;
 3778:     close($fh);
 3779:     my $home=&homeserver($docuname,$docudom);
 3780:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3781: 			  $home);
 3782:     if ($$fetchresult eq 'ok') {
 3783:         return '/uploaded/'.$fpath.'/'.$fname;
 3784:     } else {
 3785:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3786: 		 ' to host '.$home.': '.$$fetchresult);
 3787:         return '/adm/notfound.html';
 3788:     }
 3789: }
 3790: 
 3791: sub clean_filename {
 3792:     my ($fname,$args)=@_;
 3793: # Replace Windows backslashes by forward slashes
 3794:     $fname=~s/\\/\//g;
 3795:     if (!$args->{'keep_path'}) {
 3796:         # Get rid of everything but the actual filename
 3797: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3798:     }
 3799: # Replace spaces by underscores
 3800:     $fname=~s/\s+/\_/g;
 3801: # Replace all other weird characters by nothing
 3802:     $fname=~s{[^/\w\.\-]}{}g;
 3803: # Replace all .\d. sequences with _\d. so they no longer look like version
 3804: # numbers
 3805:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3806:     return $fname;
 3807: }
 3808: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3809: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3810: # image with the same aspect ratio as the original, but with dimensions which do 
 3811: # not exceed $resizewidth and $resizeheight.
 3812:  
 3813: sub resizeImage {
 3814:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3815:     my $ima = Image::Magick->new;
 3816:     my $resized;
 3817:     if (-e $img_path) {
 3818:         $ima->Read($img_path);
 3819:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3820:             my $width = $ima->Get('width');
 3821:             my $height = $ima->Get('height');
 3822:             if ($width > $resizewidth) {
 3823: 	        my $factor = $width/$resizewidth;
 3824:                 my $newheight = $height/$factor;
 3825:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3826:                 $resized = 1;
 3827:             }
 3828:         }
 3829:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3830:             my $width = $ima->Get('width');
 3831:             my $height = $ima->Get('height');
 3832:             if ($height > $resizeheight) {
 3833:                 my $factor = $height/$resizeheight;
 3834:                 my $newwidth = $width/$factor;
 3835:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3836:                 $resized = 1;
 3837:             }
 3838:         }
 3839:         if ($resized) {
 3840:             $ima->Write($img_path);
 3841:         }
 3842:     }
 3843:     return;
 3844: }
 3845: 
 3846: # --------------- Take an uploaded file and put it into the userfiles directory
 3847: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3848: #                    the desired filename is in $env{"form.$formname.filename"}
 3849: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3850: #                                    canceloverwrite, or ''. 
 3851: #                   if 'coursedoc': upload to the current course
 3852: #                   if 'existingfile': write file to tmp/overwrites directory 
 3853: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3854: #                   $context is passed as argument to &finishuserfileupload
 3855: #        $subdir - directory in userfile to store the file into
 3856: #        $parser - instruction to parse file for objects ($parser = parse)    
 3857: #        $allfiles - reference to hash for embedded objects
 3858: #        $codebase - reference to hash for codebase of java objects
 3859: #        $desuname - username for permanent storage of uploaded file
 3860: #        $dsetudom - domain for permanaent storage of uploaded file
 3861: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3862: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3863: #        $resizewidth - width (pixels) to which to resize uploaded image
 3864: #        $resizeheight - height (pixels) to which to resize uploaded image
 3865: #        $mimetype - reference to scalar to accommodate mime type determined
 3866: #                    from File::MMagic.
 3867: # 
 3868: # output: url of file in userspace, or error: <message> 
 3869: #             or /adm/notfound.html if failure to upload occurse
 3870: 
 3871: sub userfileupload {
 3872:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3873:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3874:     if (!defined($subdir)) { $subdir='unknown'; }
 3875:     my $fname=$env{'form.'.$formname.'.filename'};
 3876:     $fname=&clean_filename($fname);
 3877:     # See if there is anything left
 3878:     unless ($fname) { return 'error: no uploaded file'; }
 3879:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3880:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3881:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3882:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3883:         my $now = time;
 3884:         my $filepath;
 3885:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3886:              $filepath = 'tmp/helprequests/'.$now;
 3887:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3888:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3889:                          '_'.$env{'user.domain'}.'/pending';
 3890:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3891:             my ($docuname,$docudom);
 3892:             if ($destudom =~ /^$match_domain$/) {
 3893:                 $docudom = $destudom;
 3894:             } else {
 3895:                 $docudom = $env{'user.domain'};
 3896:             }
 3897:             if ($destuname =~ /^$match_username$/) {
 3898:                 $docuname = $destuname;
 3899:             } else {
 3900:                 $docuname = $env{'user.name'};
 3901:             }
 3902:             if (exists($env{'form.group'})) {
 3903:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3904:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3905:             }
 3906:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3907:             if ($context eq 'canceloverwrite') {
 3908:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3909:                 if (-e  $tempfile) {
 3910:                     my @info = stat($tempfile);
 3911:                     if ($info[9] eq $env{'form.timestamp'}) {
 3912:                         unlink($tempfile);
 3913:                     }
 3914:                 }
 3915:                 return;
 3916:             }
 3917:         }
 3918:         # Create the directory if not present
 3919:         my @parts=split(/\//,$filepath);
 3920:         my $fullpath = $perlvar{'lonDaemons'};
 3921:         for (my $i=0;$i<@parts;$i++) {
 3922:             $fullpath .= '/'.$parts[$i];
 3923:             if ((-e $fullpath)!=1) {
 3924:                 mkdir($fullpath,0777);
 3925:             }
 3926:         }
 3927:         open(my $fh,'>',$fullpath.'/'.$fname);
 3928:         print $fh $env{'form.'.$formname};
 3929:         close($fh);
 3930:         if ($context eq 'existingfile') {
 3931:             my @info = stat($fullpath.'/'.$fname);
 3932:             return ($fullpath.'/'.$fname,$info[9]);
 3933:         } else {
 3934:             return $fullpath.'/'.$fname;
 3935:         }
 3936:     }
 3937:     if ($subdir eq 'scantron') {
 3938:         $fname = 'scantron_orig_'.$fname;
 3939:     } else {
 3940:         $fname="$subdir/$fname";
 3941:     }
 3942:     if ($context eq 'coursedoc') {
 3943: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3944: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3945:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3946:             return &finishuserfileupload($docuname,$docudom,
 3947: 					 $formname,$fname,$parser,$allfiles,
 3948: 					 $codebase,$thumbwidth,$thumbheight,
 3949:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3950:         } else {
 3951:             if ($env{'form.folder'}) {
 3952:                 $fname=$env{'form.folder'}.'/'.$fname;
 3953:             }
 3954:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3955: 				       $fname,$formname,$parser,
 3956: 				       $allfiles,$codebase,$mimetype);
 3957:         }
 3958:     } elsif (defined($destuname)) {
 3959:         my $docuname=$destuname;
 3960:         my $docudom=$destudom;
 3961: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3962: 				     $parser,$allfiles,$codebase,
 3963:                                      $thumbwidth,$thumbheight,
 3964:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3965:     } else {
 3966:         my $docuname=$env{'user.name'};
 3967:         my $docudom=$env{'user.domain'};
 3968:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3969:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3970:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3971:         }
 3972: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3973: 				     $parser,$allfiles,$codebase,
 3974:                                      $thumbwidth,$thumbheight,
 3975:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3976:     }
 3977: }
 3978: 
 3979: sub finishuserfileupload {
 3980:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3981:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3982:     my $path=$docudom.'/'.$docuname.'/';
 3983:     my $filepath=$perlvar{'lonDocRoot'};
 3984:   
 3985:     my ($fnamepath,$file,$fetchthumb);
 3986:     $file=$fname;
 3987:     if ($fname=~m|/|) {
 3988:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3989: 	$path.=$fnamepath.'/';
 3990:     }
 3991:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3992:     my $count;
 3993:     for ($count=4;$count<=$#parts;$count++) {
 3994:         $filepath.="/$parts[$count]";
 3995:         if ((-e $filepath)!=1) {
 3996: 	    mkdir($filepath,0777);
 3997:         }
 3998:     }
 3999: 
 4000: # Save the file
 4001:     {
 4002: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4003: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4004: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4005: 	    return '/adm/notfound.html';
 4006: 	}
 4007:         if ($context eq 'overwrite') {
 4008:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4009:             my $target = $filepath.'/'.$file;
 4010:             if (-e $source) {
 4011:                 my @info = stat($source);
 4012:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4013:                     unless (&File::Copy::move($source,$target)) {
 4014:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4015:                         return "Moving from $source failed";
 4016:                     }
 4017:                 } else {
 4018:                     return "Temporary file: $source had unexpected date/time for last modification";
 4019:                 }
 4020:             } else {
 4021:                 return "Temporary file: $source missing";
 4022:             }
 4023:         } elsif (!print FH ($env{'form.'.$formname})) {
 4024: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4025: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4026: 	    return '/adm/notfound.html';
 4027: 	}
 4028: 	close(FH);
 4029:         if ($resizewidth && $resizeheight) {
 4030:             my $mm = new File::MMagic;
 4031:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4032:             if ($mime_type =~ m{^image/}) {
 4033: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4034:             }  
 4035: 	}
 4036:     }
 4037:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4038:         if (ref($mimetype)) {
 4039:             if ($$mimetype eq '') {
 4040:                 my $mm = new File::MMagic;
 4041:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4042:                 $$mimetype = $type;
 4043:             }
 4044:         }
 4045:     }
 4046:     if ($parser eq 'parse') {
 4047:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4048:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4049:                                                        $allfiles,$codebase);
 4050:             unless ($parse_result eq 'ok') {
 4051:                 &logthis('Failed to parse '.$filepath.$file.
 4052: 	   	         ' for embedded media: '.$parse_result); 
 4053:             }
 4054:         }
 4055:     }
 4056:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4057:         my $input = $filepath.'/'.$file;
 4058:         my $output = $filepath.'/'.'tn-'.$file;
 4059:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4060:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4061:         system({$args[0]} @args);
 4062:         if (-e $filepath.'/'.'tn-'.$file) {
 4063:             $fetchthumb  = 1; 
 4064:         }
 4065:     }
 4066:  
 4067: # Notify homeserver to grep it
 4068: #
 4069:     my $docuhome=&homeserver($docuname,$docudom);	
 4070:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4071:     if ($fetchresult eq 'ok') {
 4072:         if ($fetchthumb) {
 4073:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4074:             if ($thumbresult ne 'ok') {
 4075:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4076:                          $docuhome.': '.$thumbresult);
 4077:             }
 4078:         }
 4079: #
 4080: # Return the URL to it
 4081:         return '/uploaded/'.$path.$file;
 4082:     } else {
 4083:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4084: 		 ': '.$fetchresult);
 4085:         return '/adm/notfound.html';
 4086:     }
 4087: }
 4088: 
 4089: sub extract_embedded_items {
 4090:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4091:     my @state = ();
 4092:     my (%lastids,%related,%shockwave,%flashvars);
 4093:     my %javafiles = (
 4094:                       codebase => '',
 4095:                       code => '',
 4096:                       archive => ''
 4097:                     );
 4098:     my %mediafiles = (
 4099:                       src => '',
 4100:                       movie => '',
 4101:                      );
 4102:     my $p;
 4103:     if ($content) {
 4104:         $p = HTML::LCParser->new($content);
 4105:     } else {
 4106:         $p = HTML::LCParser->new($fullpath);
 4107:     }
 4108:     while (my $t=$p->get_token()) {
 4109: 	if ($t->[0] eq 'S') {
 4110: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4111: 	    push(@state, $tagname);
 4112:             if (lc($tagname) eq 'allow') {
 4113:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4114:             }
 4115: 	    if (lc($tagname) eq 'img') {
 4116: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4117: 	    }
 4118: 	    if (lc($tagname) eq 'a') {
 4119:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4120:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4121:                 }
 4122: 	    }
 4123:             if (lc($tagname) eq 'script') {
 4124:                 my $src;
 4125:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4126:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4127:                 } else {
 4128:                     if ($attr->{'src'} ne '') {
 4129:                         $src = $attr->{'src'};
 4130:                         &add_filetype($allfiles,$src,'src');
 4131:                     }
 4132:                 }
 4133:                 my $text = $p->get_trimmed_text();
 4134:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4135:                     my @swfargs = split(/,/,$1);
 4136:                     foreach my $item (@swfargs) {
 4137:                         $item =~ s/["']//g;
 4138:                         $item =~ s/^\s+//;
 4139:                         $item =~ s/\s+$//;
 4140:                     }
 4141:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4142:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4143:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4144:                         } else {
 4145:                             $related{$swfargs[0]} = [$swfargs[2]];
 4146:                         }
 4147:                     }
 4148:                 }
 4149:             }
 4150:             if (lc($tagname) eq 'link') {
 4151:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4152:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4153:                 }
 4154:             }
 4155: 	    if (lc($tagname) eq 'object' ||
 4156: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4157: 		foreach my $item (keys(%javafiles)) {
 4158: 		    $javafiles{$item} = '';
 4159: 		}
 4160:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4161:                     $lastids{lc($tagname)} = $attr->{'id'};
 4162:                 }
 4163: 	    }
 4164: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4165: 		my $name = lc($attr->{'name'});
 4166: 		foreach my $item (keys(%javafiles)) {
 4167: 		    if ($name eq $item) {
 4168: 			$javafiles{$item} = $attr->{'value'};
 4169: 			last;
 4170: 		    }
 4171: 		}
 4172:                 my $pathfrom;
 4173: 		foreach my $item (keys(%mediafiles)) {
 4174: 		    if ($name eq $item) {
 4175:                         $pathfrom = $attr->{'value'};
 4176:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4177: 			&add_filetype($allfiles,$pathfrom,$name);
 4178: 			last;
 4179: 		    }
 4180: 		}
 4181:                 if ($name eq 'flashvars') {
 4182:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4183:                 }
 4184:                 if ($pathfrom ne '') {
 4185:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4186:                                          $pathfrom);
 4187:                 }
 4188: 	    }
 4189: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4190: 		foreach my $item (keys(%javafiles)) {
 4191: 		    if ($attr->{$item}) {
 4192: 			$javafiles{$item} = $attr->{$item};
 4193: 			last;
 4194: 		    }
 4195: 		}
 4196: 		foreach my $item (keys(%mediafiles)) {
 4197: 		    if ($attr->{$item}) {
 4198: 			&add_filetype($allfiles,$attr->{$item},$item);
 4199: 			last;
 4200: 		    }
 4201: 		}
 4202:                 if (lc($tagname) eq 'embed') {
 4203:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4204:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4205:                                              $attr->{'src'});
 4206:                     }
 4207:                 }
 4208: 	    }
 4209:             if (lc($tagname) eq 'iframe') {
 4210:                 my $src = $attr->{'src'} ;
 4211:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4212:                     &add_filetype($allfiles,$src,'src');
 4213:                 } elsif ($src =~ m{^/}) {
 4214:                     if ($env{'request.course.id'}) {
 4215:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4216:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4217:                         my $url = &hreflocation('',$fullpath);
 4218:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4219:                             my $relpath = $1;
 4220:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4221:                                 &add_filetype($allfiles,$1,'src');
 4222:                             }
 4223:                         }
 4224:                     }
 4225:                 }
 4226:             }
 4227:             if ($t->[4] =~ m{/>$}) {
 4228:                 pop(@state);
 4229:             }
 4230: 	} elsif ($t->[0] eq 'E') {
 4231: 	    my ($tagname) = ($t->[1]);
 4232: 	    if ($javafiles{'codebase'} ne '') {
 4233: 		$javafiles{'codebase'} .= '/';
 4234: 	    }  
 4235: 	    if (lc($tagname) eq 'applet' ||
 4236: 		lc($tagname) eq 'object' ||
 4237: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4238: 		) {
 4239: 		foreach my $item (keys(%javafiles)) {
 4240: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4241: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4242: 			&add_filetype($allfiles,$file,$item);
 4243: 		    }
 4244: 		}
 4245: 	    } 
 4246: 	    pop @state;
 4247: 	}
 4248:     }
 4249:     foreach my $id (sort(keys(%flashvars))) {
 4250:         if ($shockwave{$id} ne '') {
 4251:             my @pairs = split(/\&/,$flashvars{$id});
 4252:             foreach my $pair (@pairs) {
 4253:                 my ($key,$value) = split(/\=/,$pair);
 4254:                 if ($key eq 'thumb') {
 4255:                     &add_filetype($allfiles,$value,$key);
 4256:                 } elsif ($key eq 'content') {
 4257:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4258:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4259:                     if ($ext ne '') {
 4260:                         &add_filetype($allfiles,$path.$value,$ext);
 4261:                     }
 4262:                 }
 4263:             }
 4264:         }
 4265:     }
 4266:     return 'ok';
 4267: }
 4268: 
 4269: sub add_filetype {
 4270:     my ($allfiles,$file,$type)=@_;
 4271:     if (exists($allfiles->{$file})) {
 4272: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4273: 	    push(@{$allfiles->{$file}}, &escape($type));
 4274: 	}
 4275:     } else {
 4276: 	@{$allfiles->{$file}} = (&escape($type));
 4277:     }
 4278: }
 4279: 
 4280: sub embedded_dependency {
 4281:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4282:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4283:         if (($identifier ne '') &&
 4284:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4285:             ($pathfrom ne '')) {
 4286:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4287:             foreach my $dep (@{$related->{$identifier}}) {
 4288:                 &add_filetype($allfiles,$path.$dep,'object');
 4289:             }
 4290:         }
 4291:     }
 4292:     return;
 4293: }
 4294: 
 4295: sub removeuploadedurl {
 4296:     my ($url)=@_;	
 4297:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4298:     return &removeuserfile($uname,$udom,$fname);
 4299: }
 4300: 
 4301: sub removeuserfile {
 4302:     my ($docuname,$docudom,$fname)=@_;
 4303:     my $home=&homeserver($docuname,$docudom);    
 4304:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4305:     if ($result eq 'ok') {	
 4306:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4307:             my $metafile = $fname.'.meta';
 4308:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4309: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4310:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4311:             my $sqlresult = 
 4312:                 &update_portfolio_table($docuname,$docudom,$file,
 4313:                                         'portfolio_metadata',$group,
 4314:                                         'delete');
 4315:         }
 4316:     }
 4317:     return $result;
 4318: }
 4319: 
 4320: sub mkdiruserfile {
 4321:     my ($docuname,$docudom,$dir)=@_;
 4322:     my $home=&homeserver($docuname,$docudom);
 4323:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4324: }
 4325: 
 4326: sub renameuserfile {
 4327:     my ($docuname,$docudom,$old,$new)=@_;
 4328:     my $home=&homeserver($docuname,$docudom);
 4329:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4330:                         &escape("$old").':'.&escape("$new"),$home);
 4331:     if ($result eq 'ok') {
 4332:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4333:             my $oldmeta = $old.'.meta';
 4334:             my $newmeta = $new.'.meta';
 4335:             my $metaresult = 
 4336:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4337: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4338:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4339:             my $sqlresult = 
 4340:                 &update_portfolio_table($docuname,$docudom,$file,
 4341:                                         'portfolio_metadata',$group,
 4342:                                         'delete');
 4343:         }
 4344:     }
 4345:     return $result;
 4346: }
 4347: 
 4348: # ------------------------------------------------------------------------- Log
 4349: 
 4350: sub log {
 4351:     my ($dom,$nam,$hom,$what)=@_;
 4352:     return critical("log:$dom:$nam:$what",$hom);
 4353: }
 4354: 
 4355: # ------------------------------------------------------------------ Course Log
 4356: #
 4357: # This routine flushes several buffers of non-mission-critical nature
 4358: #
 4359: 
 4360: sub flushcourselogs {
 4361:     &logthis('Flushing log buffers');
 4362: #
 4363: # course logs
 4364: # This is a log of all transactions in a course, which can be used
 4365: # for data mining purposes
 4366: #
 4367: # It also collects the courseid database, which lists last transaction
 4368: # times and course titles for all courseids
 4369: #
 4370:     my %courseidbuffer=();
 4371:     foreach my $crsid (keys(%courselogs)) {
 4372:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4373: 		          &escape($courselogs{$crsid}),
 4374: 		          $coursehombuf{$crsid}) eq 'ok') {
 4375: 	    delete $courselogs{$crsid};
 4376:         } else {
 4377:             &logthis('Failed to flush log buffer for '.$crsid);
 4378:             if (length($courselogs{$crsid})>40000) {
 4379:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4380:                         " exceeded maximum size, deleting.</font>");
 4381:                delete $courselogs{$crsid};
 4382:             }
 4383:         }
 4384:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4385:             'description' => $coursedescrbuf{$crsid},
 4386:             'inst_code'    => $courseinstcodebuf{$crsid},
 4387:             'type'        => $coursetypebuf{$crsid},
 4388:             'owner'       => $courseownerbuf{$crsid},
 4389:         };
 4390:     }
 4391: #
 4392: # Write course id database (reverse lookup) to homeserver of courses 
 4393: # Is used in pickcourse
 4394: #
 4395:     foreach my $crs_home (keys(%courseidbuffer)) {
 4396:         my $response = &courseidput(&host_domain($crs_home),
 4397:                                     $courseidbuffer{$crs_home},
 4398:                                     $crs_home,'timeonly');
 4399:     }
 4400: #
 4401: # File accesses
 4402: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4403: #
 4404:     foreach my $entry (keys(%accesshash)) {
 4405:         if ($entry =~ /___count$/) {
 4406:             my ($dom,$name);
 4407:             ($dom,$name,undef)=
 4408: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4409:             if (! defined($dom) || $dom eq '' || 
 4410:                 ! defined($name) || $name eq '') {
 4411:                 my $cid = $env{'request.course.id'};
 4412:                 $dom  = $env{'request.'.$cid.'.domain'};
 4413:                 $name = $env{'request.'.$cid.'.num'};
 4414:             }
 4415:             my $value = $accesshash{$entry};
 4416:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4417:             my %temphash=($url => $value);
 4418:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4419:             if ($result eq 'ok') {
 4420:                 delete $accesshash{$entry};
 4421:             }
 4422:         } else {
 4423:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4424:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4425:             my %temphash=($entry => $accesshash{$entry});
 4426:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4427:                 delete $accesshash{$entry};
 4428:             }
 4429:         }
 4430:     }
 4431: #
 4432: # Roles
 4433: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4434: #
 4435:     foreach my $entry (keys(%userrolehash)) {
 4436:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4437: 	    split(/\:/,$entry);
 4438:         if (&Apache::lonnet::put('nohist_userroles',
 4439:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4440:                 $rudom,$runame) eq 'ok') {
 4441: 	    delete $userrolehash{$entry};
 4442:         }
 4443:     }
 4444: #
 4445: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4446: #
 4447:     my %domrolebuffer = ();
 4448:     foreach my $entry (keys(%domainrolehash)) {
 4449:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4450:         if ($domrolebuffer{$rudom}) {
 4451:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4452:                       '='.&escape($domainrolehash{$entry});
 4453:         } else {
 4454:             $domrolebuffer{$rudom}.=&escape($entry).
 4455:                       '='.&escape($domainrolehash{$entry});
 4456:         }
 4457:         delete $domainrolehash{$entry};
 4458:     }
 4459:     foreach my $dom (keys(%domrolebuffer)) {
 4460: 	my %servers;
 4461: 	if (defined(&domain($dom,'primary'))) {
 4462: 	    my $primary=&domain($dom,'primary');
 4463: 	    my $hostname=&hostname($primary);
 4464: 	    $servers{$primary} = $hostname;
 4465: 	} else { 
 4466: 	    %servers = &get_servers($dom,'library');
 4467: 	}
 4468: 	foreach my $tryserver (keys(%servers)) {
 4469: 	    if (&reply('domroleput:'.$dom.':'.
 4470: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4471: 		last;
 4472: 	    } else {  
 4473: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4474: 	    }
 4475:         }
 4476:     }
 4477:     $dumpcount++;
 4478: }
 4479: 
 4480: sub courselog {
 4481:     my $what=shift;
 4482:     $what=time.':'.$what;
 4483:     unless ($env{'request.course.id'}) { return ''; }
 4484:     $coursedombuf{$env{'request.course.id'}}=
 4485:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4486:     $coursenumbuf{$env{'request.course.id'}}=
 4487:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4488:     $coursehombuf{$env{'request.course.id'}}=
 4489:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4490:     $coursedescrbuf{$env{'request.course.id'}}=
 4491:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4492:     $courseinstcodebuf{$env{'request.course.id'}}=
 4493:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4494:     $courseownerbuf{$env{'request.course.id'}}=
 4495:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4496:     $coursetypebuf{$env{'request.course.id'}}=
 4497:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4498:     if (defined $courselogs{$env{'request.course.id'}}) {
 4499: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4500:     } else {
 4501: 	$courselogs{$env{'request.course.id'}}.=$what;
 4502:     }
 4503:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4504: 	&flushcourselogs();
 4505:     }
 4506: }
 4507: 
 4508: sub courseacclog {
 4509:     my $fnsymb=shift;
 4510:     unless ($env{'request.course.id'}) { return ''; }
 4511:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4512:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4513:         $what.=':POST';
 4514:         # FIXME: Probably ought to escape things....
 4515: 	foreach my $key (keys(%env)) {
 4516:             if ($key=~/^form\.(.*)/) {
 4517:                 my $formitem = $1;
 4518:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4519:                     $what.=':'.$formitem.'='.$env{$key};
 4520:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4521:                     $what.=':'.$formitem.'='.$env{$key};
 4522:                 }
 4523:             }
 4524:         }
 4525:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4526:         # FIXME: We should not be depending on a form parameter that someone
 4527:         # editing lonsearchcat.pm might change in the future.
 4528:         if ($env{'form.phase'} eq 'course_search') {
 4529:             $what.= ':POST';
 4530:             # FIXME: Probably ought to escape things....
 4531:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4532:                                  'crsdiscuss') {
 4533:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4534:             }
 4535:         }
 4536:     }
 4537:     &courselog($what);
 4538: }
 4539: 
 4540: sub countacc {
 4541:     my $url=&declutter(shift);
 4542:     return if (! defined($url) || $url eq '');
 4543:     unless ($env{'request.course.id'}) { return ''; }
 4544: #
 4545: # Mark that this url was used in this course
 4546: #
 4547:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4548: #
 4549: # Increase the access count for this resource in this child process
 4550: #
 4551:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4552:     $accesshash{$key}++;
 4553: }
 4554: 
 4555: sub linklog {
 4556:     my ($from,$to)=@_;
 4557:     $from=&declutter($from);
 4558:     $to=&declutter($to);
 4559:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4560:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4561: }
 4562: 
 4563: sub statslog {
 4564:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4565:     if ($users<2) { return; }
 4566:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4567:             'course'       => $env{'request.course.id'},
 4568:             'sections'     => '"all"',
 4569:             'num_students' => $users,
 4570:             'part'         => $part,
 4571:             'symb'         => $symb,
 4572:             'mean_tries'   => $av_attempts,
 4573:             'deg_of_diff'  => $degdiff});
 4574:     foreach my $key (keys(%dynstore)) {
 4575:         $accesshash{$key}=$dynstore{$key};
 4576:     }
 4577: }
 4578:   
 4579: sub userrolelog {
 4580:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4581:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4582:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4583:        $userrolehash
 4584:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4585:                     =$tend.':'.$tstart;
 4586:     }
 4587:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4588:        $userrolehash
 4589:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4590:                     =$tend.':'.$tstart;
 4591:     }
 4592:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4593:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4594:        $domainrolehash
 4595:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4596:                     = $tend.':'.$tstart;
 4597:     }
 4598: }
 4599: 
 4600: sub courserolelog {
 4601:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4602:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4603:         my $cdom = $1;
 4604:         my $cnum = $2;
 4605:         my $sec = $3;
 4606:         my $namespace = 'rolelog';
 4607:         my %storehash = (
 4608:                            role    => $trole,
 4609:                            start   => $tstart,
 4610:                            end     => $tend,
 4611:                            selfenroll => $selfenroll,
 4612:                            context    => $context,
 4613:                         );
 4614:         if ($trole eq 'gr') {
 4615:             $namespace = 'groupslog';
 4616:             $storehash{'group'} = $sec;
 4617:         } else {
 4618:             $storehash{'section'} = $sec;
 4619:         }
 4620:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4621:                    $domain,$cnum,$cdom);
 4622:         if (($trole ne 'st') || ($sec ne '')) {
 4623:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4624:         }
 4625:     }
 4626:     return;
 4627: }
 4628: 
 4629: sub domainrolelog {
 4630:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4631:     if ($area =~ m{^/($match_domain)/$}) {
 4632:         my $cdom = $1;
 4633:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4634:         my $namespace = 'rolelog';
 4635:         my %storehash = (
 4636:                            role    => $trole,
 4637:                            start   => $tstart,
 4638:                            end     => $tend,
 4639:                            context => $context,
 4640:                         );
 4641:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4642:                    $domain,$domconfiguser,$cdom);
 4643:     }
 4644:     return;
 4645: 
 4646: }
 4647: 
 4648: sub coauthorrolelog {
 4649:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4650:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4651:         my $audom = $1;
 4652:         my $auname = $2;
 4653:         my $namespace = 'rolelog';
 4654:         my %storehash = (
 4655:                            role    => $trole,
 4656:                            start   => $tstart,
 4657:                            end     => $tend,
 4658:                            context => $context,
 4659:                         );
 4660:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4661:                    $domain,$auname,$audom);
 4662:     }
 4663:     return;
 4664: }
 4665: 
 4666: sub get_course_adv_roles {
 4667:     my ($cid,$codes) = @_;
 4668:     $cid=$env{'request.course.id'} unless (defined($cid));
 4669:     my %coursehash=&coursedescription($cid);
 4670:     my $crstype = &Apache::loncommon::course_type($cid);
 4671:     my %nothide=();
 4672:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4673:         if ($user !~ /:/) {
 4674: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4675:         } else {
 4676:             $nothide{$user}=1;
 4677:         }
 4678:     }
 4679:     my @possdoms = ($coursehash{'domain'});
 4680:     if ($coursehash{'checkforpriv'}) {
 4681:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4682:     }
 4683:     my %returnhash=();
 4684:     my %dumphash=
 4685:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4686:     my $now=time;
 4687:     my %privileged;
 4688:     foreach my $entry (keys(%dumphash)) {
 4689: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4690:         if (($tstart) && ($tstart<0)) { next; }
 4691:         if (($tend) && ($tend<$now)) { next; }
 4692:         if (($tstart) && ($now<$tstart)) { next; }
 4693:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4694: 	if ($username eq '' || $domain eq '') { next; }
 4695:         if ((&privileged($username,$domain,\@possdoms)) &&
 4696:             (!$nothide{$username.':'.$domain})) { next; }
 4697: 	if ($role eq 'cr') { next; }
 4698:         if ($codes) {
 4699:             if ($section) { $role .= ':'.$section; }
 4700:             if ($returnhash{$role}) {
 4701:                 $returnhash{$role}.=','.$username.':'.$domain;
 4702:             } else {
 4703:                 $returnhash{$role}=$username.':'.$domain;
 4704:             }
 4705:         } else {
 4706:             my $key=&plaintext($role,$crstype);
 4707:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4708:             if ($returnhash{$key}) {
 4709: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4710:             } else {
 4711:                 $returnhash{$key}=$username.':'.$domain;
 4712:             }
 4713:         }
 4714:     }
 4715:     return %returnhash;
 4716: }
 4717: 
 4718: sub get_my_roles {
 4719:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4720:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4721:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4722:     my (%dumphash,%nothide);
 4723:     if ($context eq 'userroles') {
 4724:         %dumphash = &dump('roles',$udom,$uname);
 4725:     } else {
 4726:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4727:         if ($hidepriv) {
 4728:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4729:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4730:                 if ($user !~ /:/) {
 4731:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4732:                 } else {
 4733:                     $nothide{$user} = 1;
 4734:                 }
 4735:             }
 4736:         }
 4737:     }
 4738:     my %returnhash=();
 4739:     my $now=time;
 4740:     my %privileged;
 4741:     foreach my $entry (keys(%dumphash)) {
 4742:         my ($role,$tend,$tstart);
 4743:         if ($context eq 'userroles') {
 4744:             next if ($entry =~ /^rolesdef/);
 4745: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4746:         } else {
 4747:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4748:         }
 4749:         if (($tstart) && ($tstart<0)) { next; }
 4750:         my $status = 'active';
 4751:         if (($tend) && ($tend<=$now)) {
 4752:             $status = 'previous';
 4753:         } 
 4754:         if (($tstart) && ($now<$tstart)) {
 4755:             $status = 'future';
 4756:         }
 4757:         if (ref($types) eq 'ARRAY') {
 4758:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4759:                 next;
 4760:             } 
 4761:         } else {
 4762:             if ($status ne 'active') {
 4763:                 next;
 4764:             }
 4765:         }
 4766:         my ($rolecode,$username,$domain,$section,$area);
 4767:         if ($context eq 'userroles') {
 4768:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4769:             (undef,$domain,$username,$section) = split(/\//,$area);
 4770:         } else {
 4771:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4772:         }
 4773:         if (ref($roledoms) eq 'ARRAY') {
 4774:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4775:                 next;
 4776:             }
 4777:         }
 4778:         if (ref($roles) eq 'ARRAY') {
 4779:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4780:                 if ($role =~ /^cr\//) {
 4781:                     if (!grep(/^cr$/,@{$roles})) {
 4782:                         next;
 4783:                     }
 4784:                 } elsif ($role =~ /^gr\//) {
 4785:                     if (!grep(/^gr$/,@{$roles})) {
 4786:                         next;
 4787:                     }
 4788:                 } else {
 4789:                     next;
 4790:                 }
 4791:             }
 4792:         }
 4793:         if ($hidepriv) {
 4794:             my @privroles = ('dc','su');
 4795:             if ($context eq 'userroles') {
 4796:                 next if (grep(/^\Q$role\E$/,@privroles));
 4797:             } else {
 4798:                 my $possdoms = [$domain];
 4799:                 if (ref($roledoms) eq 'ARRAY') {
 4800:                    push(@{$possdoms},@{$roledoms}); 
 4801:                 }
 4802:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4803:                     if (!$nothide{$username.':'.$domain}) {
 4804:                         next;
 4805:                     }
 4806:                 }
 4807:             }
 4808:         }
 4809:         if ($withsec) {
 4810:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4811:                 $tstart.':'.$tend;
 4812:         } else {
 4813:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4814:         }
 4815:     }
 4816:     return %returnhash;
 4817: }
 4818: 
 4819: sub get_all_adhocroles {
 4820:     my ($dom) = @_;
 4821:     my @roles_by_num = ();
 4822:     my %domdefaults = &get_domain_defaults($dom);
 4823:     my (%description,%access_in_dom,%access_info);
 4824:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4825:         my $count = 0;
 4826:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4827:         my %ordered;
 4828:         foreach my $role (sort(keys(%domcurrent))) {
 4829:             my ($order,$desc,$access_in_dom);
 4830:             if (ref($domcurrent{$role}) eq 'HASH') {
 4831:                 $order = $domcurrent{$role}{'order'};
 4832:                 $desc = $domcurrent{$role}{'desc'};
 4833:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4834:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4835:             }
 4836:             if ($order eq '') {
 4837:                 $order = $count;
 4838:             }
 4839:             $ordered{$order} = $role;
 4840:             if ($desc ne '') {
 4841:                 $description{$role} = $desc;
 4842:             } else {
 4843:                 $description{$role}= $role;
 4844:             }
 4845:             $count++;
 4846:         }
 4847:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4848:             push(@roles_by_num,$ordered{$item});
 4849:         }
 4850:     }
 4851:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4852: }
 4853: 
 4854: sub get_my_adhocroles {
 4855:     my ($cid,$checkreg) = @_;
 4856:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4857:     if ($env{'request.course.id'} eq $cid) {
 4858:         $cdom = $env{'course.'.$cid.'.domain'};
 4859:         $cnum = $env{'course.'.$cid.'.num'};
 4860:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4861:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4862:         $cdom = $1;
 4863:         $cnum = $2;
 4864:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4865:                                      $cdom,$cnum);
 4866:     }
 4867:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4868:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4869:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4870:         if ($rosterhash{$user} ne '') {
 4871:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4872:             return ([],{}) if ($type eq 'auto');
 4873:         }
 4874:     }
 4875:     if (($cdom ne '') && ($cnum ne ''))  {
 4876:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4877:             my $then=$env{'user.login.time'};
 4878:             my $update=$env{'user.update.time'};
 4879:             if (!$update) {
 4880:                 $update = $then;
 4881:             }
 4882:             my @liveroles;
 4883:             foreach my $role ('dh','da') {
 4884:                 if ($env{"user.role.$role./$cdom/"}) {
 4885:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4886:                     my $limit = $update;
 4887:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4888:                         $limit = $then;
 4889:                     }
 4890:                     my $activerole = 1;
 4891:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4892:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4893:                     if ($activerole) {
 4894:                         push(@liveroles,$role);
 4895:                     }
 4896:                 }
 4897:             }
 4898:             if (@liveroles) {
 4899:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4900:                     my ($accessref,$accessinfo,%access_in_dom);
 4901:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4902:                     if (ref($roles_by_num) eq 'ARRAY') {
 4903:                         if (@{$roles_by_num}) {
 4904:                             my %settings;
 4905:                             if ($env{'request.course.id'} eq $cid) {
 4906:                                 foreach my $envkey (keys(%env)) {
 4907:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4908:                                         $settings{$1} = $env{$envkey};
 4909:                                     }
 4910:                                 }
 4911:                             } else {
 4912:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4913:                             }
 4914:                             my %setincrs;
 4915:                             if ($settings{'internal.adhocaccess'}) {
 4916:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4917:                             }
 4918:                             my @statuses;
 4919:                             if ($env{'environment.inststatus'}) {
 4920:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4921:                             }
 4922:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4923:                             if (ref($accessref) eq 'HASH') {
 4924:                                 %access_in_dom = %{$accessref};
 4925:                             }
 4926:                             foreach my $role (@{$roles_by_num}) {
 4927:                                 my ($curraccess,@okstatus,@personnel);
 4928:                                 if ($setincrs{$role}) {
 4929:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4930:                                     if ($curraccess eq 'status') {
 4931:                                         @okstatus = split(/\&/,$rest);
 4932:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4933:                                         @personnel = split(/\&/,$rest);
 4934:                                     }
 4935:                                 } else {
 4936:                                     $curraccess = $access_in_dom{$role};
 4937:                                     if (ref($accessinfo) eq 'HASH') {
 4938:                                         if ($curraccess eq 'status') {
 4939:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4940:                                                 @okstatus = @{$accessinfo->{$role}};
 4941:                                             }
 4942:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4943:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4944:                                                 @personnel = @{$accessinfo->{$role}};
 4945:                                             }
 4946:                                         }
 4947:                                     }
 4948:                                 }
 4949:                                 if ($curraccess eq 'none') {
 4950:                                     next;
 4951:                                 } elsif ($curraccess eq 'all') {
 4952:                                     push(@possroles,$role);
 4953:                                 } elsif ($curraccess eq 'dh') {
 4954:                                     if (grep(/^dh$/,@liveroles)) {
 4955:                                         push(@possroles,$role);
 4956:                                     } else {
 4957:                                         next;
 4958:                                     }
 4959:                                 } elsif ($curraccess eq 'da') {
 4960:                                     if (grep(/^da$/,@liveroles)) {
 4961:                                         push(@possroles,$role);
 4962:                                     } else {
 4963:                                         next;
 4964:                                     }
 4965:                                 } elsif ($curraccess eq 'status') {
 4966:                                     if (@okstatus) {
 4967:                                         if (!@statuses) {
 4968:                                             if (grep(/^default$/,@okstatus)) {
 4969:                                                 push(@possroles,$role);
 4970:                                             }
 4971:                                         } else {
 4972:                                             foreach my $status (@okstatus) {
 4973:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4974:                                                     push(@possroles,$role);
 4975:                                                     last;
 4976:                                                 }
 4977:                                             }
 4978:                                         }
 4979:                                     }
 4980:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4981:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4982:                                         if ($curraccess eq 'exc') {
 4983:                                             push(@possroles,$role);
 4984:                                         }
 4985:                                     } elsif ($curraccess eq 'inc') {
 4986:                                         push(@possroles,$role);
 4987:                                     }
 4988:                                 }
 4989:                             }
 4990:                         }
 4991:                     }
 4992:                 }
 4993:             }
 4994:         }
 4995:     }
 4996:     unless (ref($description) eq 'HASH') {
 4997:         if (ref($roles_by_num) eq 'ARRAY') {
 4998:             my %desc;
 4999:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5000:             $description = \%desc;
 5001:         } else {
 5002:             $description = {};
 5003:         }
 5004:     }
 5005:     return (\@possroles,$description);
 5006: }
 5007: 
 5008: # ----------------------------------------------------- Frontpage Announcements
 5009: #
 5010: #
 5011: 
 5012: sub postannounce {
 5013:     my ($server,$text)=@_;
 5014:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5015:     unless ($text=~/\w/) { $text=''; }
 5016:     return &reply('setannounce:'.&escape($text),$server);
 5017: }
 5018: 
 5019: sub getannounce {
 5020: 
 5021:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5022: 	my $announcement='';
 5023: 	while (my $line = <$fh>) { $announcement .= $line; }
 5024: 	close($fh);
 5025: 	if ($announcement=~/\w/) { 
 5026: 	    return 
 5027:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5028:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5029: 	} else {
 5030: 	    return '';
 5031: 	}
 5032:     } else {
 5033: 	return '';
 5034:     }
 5035: }
 5036: 
 5037: # ---------------------------------------------------------- Course ID routines
 5038: # Deal with domain's nohist_courseid.db files
 5039: #
 5040: 
 5041: sub courseidput {
 5042:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5043:     return unless (ref($storehash) eq 'HASH');
 5044:     my $outcome;
 5045:     if ($caller eq 'timeonly') {
 5046:         my $cids = '';
 5047:         foreach my $item (keys(%$storehash)) {
 5048:             $cids.=&escape($item).'&';
 5049:         }
 5050:         $cids=~s/\&$//;
 5051:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5052:                           $coursehome);       
 5053:     } else {
 5054:         my $items = '';
 5055:         foreach my $item (keys(%$storehash)) {
 5056:             $items.= &escape($item).'='.
 5057:                      &freeze_escape($$storehash{$item}).'&';
 5058:         }
 5059:         $items=~s/\&$//;
 5060:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5061:                           $coursehome);
 5062:     }
 5063:     if ($outcome eq 'unknown_cmd') {
 5064:         my $what;
 5065:         foreach my $cid (keys(%$storehash)) {
 5066:             $what .= &escape($cid).'=';
 5067:             foreach my $item ('description','inst_code','owner','type') {
 5068:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5069:             }
 5070:             $what =~ s/\:$/&/;
 5071:         }
 5072:         $what =~ s/\&$//;  
 5073:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5074:     } else {
 5075:         return $outcome;
 5076:     }
 5077: }
 5078: 
 5079: sub courseiddump {
 5080:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5081:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5082:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5083:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5084:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5085:     my $as_hash = 1;
 5086:     my %returnhash;
 5087:     if (!$domfilter) { $domfilter=''; }
 5088:     my %libserv = &all_library();
 5089:     foreach my $tryserver (keys(%libserv)) {
 5090:         if ( (  $hostidflag == 1 
 5091: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5092: 	     || (!defined($hostidflag)) ) {
 5093: 
 5094: 	    if (($domfilter eq '') ||
 5095: 		(&host_domain($tryserver) eq $domfilter)) {
 5096:                 my $rep;
 5097:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5098:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5099:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5100:                                 &escape($descfilter), &escape($instcodefilter), 
 5101:                                 &escape($ownerfilter), &escape($coursefilter),
 5102:                                 &escape($typefilter), &escape($regexp_ok), 
 5103:                                 $as_hash, &escape($selfenrollonly), 
 5104:                                 &escape($catfilter), $showhidden, $caller, 
 5105:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5106:                                 &escape($createdbefore), &escape($createdafter), 
 5107:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5108:                                 $reqcrsdom,&escape($reqinstcode))));
 5109:                 } else {
 5110:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5111:                              $sincefilter.':'.&escape($descfilter).':'.
 5112:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5113:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5114:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5115:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5116:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5117:                              &escape($cc_clone).':'.$cloneonly.':'.
 5118:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5119:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5120:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5121:                 }
 5122:                      
 5123:                 my @pairs=split(/\&/,$rep);
 5124:                 foreach my $item (@pairs) {
 5125:                     my ($key,$value)=split(/\=/,$item,2);
 5126:                     $key = &unescape($key);
 5127:                     next if ($key =~ /^error: 2 /);
 5128:                     my $result = &thaw_unescape($value);
 5129:                     if (ref($result) eq 'HASH') {
 5130:                         $returnhash{$key}=$result;
 5131:                     } else {
 5132:                         my @responses = split(/:/,$value);
 5133:                         my @items = ('description','inst_code','owner','type');
 5134:                         for (my $i=0; $i<@responses; $i++) {
 5135:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5136:                         }
 5137:                     }
 5138:                 }
 5139:             }
 5140:         }
 5141:     }
 5142:     return %returnhash;
 5143: }
 5144: 
 5145: sub courselastaccess {
 5146:     my ($cdom,$cnum,$hostidref) = @_;
 5147:     my %returnhash;
 5148:     if ($cdom && $cnum) {
 5149:         my $chome = &homeserver($cnum,$cdom);
 5150:         if ($chome ne 'no_host') {
 5151:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5152:             &extract_lastaccess(\%returnhash,$rep);
 5153:         }
 5154:     } else {
 5155:         if (!$cdom) { $cdom=''; }
 5156:         my %libserv = &all_library();
 5157:         foreach my $tryserver (keys(%libserv)) {
 5158:             if (ref($hostidref) eq 'ARRAY') {
 5159:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5160:             } 
 5161:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5162:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5163:                 &extract_lastaccess(\%returnhash,$rep);
 5164:             }
 5165:         }
 5166:     }
 5167:     return %returnhash;
 5168: }
 5169: 
 5170: sub extract_lastaccess {
 5171:     my ($returnhash,$rep) = @_;
 5172:     if (ref($returnhash) eq 'HASH') {
 5173:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5174:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5175:                  $rep eq '') {
 5176:             my @pairs=split(/\&/,$rep);
 5177:             foreach my $item (@pairs) {
 5178:                 my ($key,$value)=split(/\=/,$item,2);
 5179:                 $key = &unescape($key);
 5180:                 next if ($key =~ /^error: 2 /);
 5181:                 $returnhash->{$key} = &thaw_unescape($value);
 5182:             }
 5183:         }
 5184:     }
 5185:     return;
 5186: }
 5187: 
 5188: # ---------------------------------------------------------- DC e-mail
 5189: 
 5190: sub dcmailput {
 5191:     my ($domain,$msgid,$message,$server)=@_;
 5192:     my $status = &Apache::lonnet::critical(
 5193:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5194:        &escape($message),$server);
 5195:     return $status;
 5196: }
 5197: 
 5198: sub dcmaildump {
 5199:     my ($dom,$startdate,$enddate,$senders) = @_;
 5200:     my %returnhash=();
 5201: 
 5202:     if (defined(&domain($dom,'primary'))) {
 5203:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5204:                                                          &escape($enddate).':';
 5205: 	my @esc_senders=map { &escape($_)} @$senders;
 5206: 	$cmd.=&escape(join('&',@esc_senders));
 5207: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5208:             my ($key,$value) = split(/\=/,$line,2);
 5209:             if (($key) && ($value)) {
 5210:                 $returnhash{&unescape($key)} = &unescape($value);
 5211:             }
 5212:         }
 5213:     }
 5214:     return %returnhash;
 5215: }
 5216: # ---------------------------------------------------------- Domain roles
 5217: 
 5218: sub get_domain_roles {
 5219:     my ($dom,$roles,$startdate,$enddate)=@_;
 5220:     if ((!defined($startdate)) || ($startdate eq '')) {
 5221:         $startdate = '.';
 5222:     }
 5223:     if ((!defined($enddate)) || ($enddate eq '')) {
 5224:         $enddate = '.';
 5225:     }
 5226:     my $rolelist;
 5227:     if (ref($roles) eq 'ARRAY') {
 5228:         $rolelist = join('&',@{$roles});
 5229:     }
 5230:     my %personnel = ();
 5231: 
 5232:     my %servers = &get_servers($dom,'library');
 5233:     foreach my $tryserver (keys(%servers)) {
 5234: 	%{$personnel{$tryserver}}=();
 5235: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5236: 					    &escape($startdate).':'.
 5237: 					    &escape($enddate).':'.
 5238: 					    &escape($rolelist), $tryserver))) {
 5239: 	    my ($key,$value) = split(/\=/,$line,2);
 5240: 	    if (($key) && ($value)) {
 5241: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5242: 	    }
 5243: 	}
 5244:     }
 5245:     return %personnel;
 5246: }
 5247: 
 5248: sub get_active_domroles {
 5249:     my ($dom,$roles) = @_;
 5250:     return () unless (ref($roles) eq 'ARRAY');
 5251:     my $now = time;
 5252:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5253:     my %domroles;
 5254:     foreach my $server (keys(%dompersonnel)) {
 5255:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5256:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5257:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5258:         }
 5259:     }
 5260:     return %domroles;
 5261: }
 5262: 
 5263: # ----------------------------------------------------------- Interval timing 
 5264: 
 5265: {
 5266: # Caches needed for speedup of navmaps
 5267: # We don't want to cache this for very long at all (5 seconds at most)
 5268: # 
 5269: # The user for whom we cache
 5270: my $cachedkey='';
 5271: # The cached times for this user
 5272: my %cachedtimes=();
 5273: # When this was last done
 5274: my $cachedtime='';
 5275: 
 5276: sub load_all_first_access {
 5277:     my ($uname,$udom,$ignorecache)=@_;
 5278:     if (($cachedkey eq $uname.':'.$udom) &&
 5279:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5280:         (!$ignorecache)) {
 5281:         return;
 5282:     }
 5283:     $cachedtime=time;
 5284:     $cachedkey=$uname.':'.$udom;
 5285:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5286: }
 5287: 
 5288: sub get_first_access {
 5289:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5290:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5291:     if ($argsymb) { $symb=$argsymb; }
 5292:     my ($map,$id,$res)=&decode_symb($symb);
 5293:     if ($argmap) { $map = $argmap; }
 5294:     if ($type eq 'course') {
 5295: 	$res='course';
 5296:     } elsif ($type eq 'map') {
 5297: 	$res=&symbread($map);
 5298:     } else {
 5299: 	$res=$symb;
 5300:     }
 5301:     &load_all_first_access($uname,$udom,$ignorecache);
 5302:     return $cachedtimes{"$courseid\0$res"};
 5303: }
 5304: 
 5305: sub set_first_access {
 5306:     my ($type,$interval)=@_;
 5307:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5308:     my ($map,$id,$res)=&decode_symb($symb);
 5309:     if ($type eq 'course') {
 5310: 	$res='course';
 5311:     } elsif ($type eq 'map') {
 5312: 	$res=&symbread($map);
 5313:     } else {
 5314: 	$res=$symb;
 5315:     }
 5316:     $cachedkey='';
 5317:     my $firstaccess=&get_first_access($type,$symb,$map);
 5318:     if ($firstaccess) {
 5319:         &logthis("First access time already set ($firstaccess) when attempting ".
 5320:                  "to set new value (type: $type, extent: $res) for $uname:$udom ". 
 5321:                  "in $courseid"); 
 5322:         return 'already_set';
 5323:     } else {
 5324:         my $start = time;
 5325: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5326:                           $udom,$uname);
 5327:         if ($putres eq 'ok') {
 5328:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5329:                  $udom,$uname); 
 5330:             &appenv(
 5331:                      {
 5332:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5333:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5334:                      }
 5335:                   );
 5336:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5337:                 $cachedtimes{"$courseid\0$res"} = $start;
 5338:             }
 5339:         } elsif ($putres ne 'refused') {
 5340:             &logthis("Result: $putres when attempting to set first access time ".
 5341:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5342:         }
 5343:         return $putres;
 5344:     }
 5345:     return 'already_set';
 5346: }
 5347: }
 5348: 
 5349: # --------------------------------------------- Set Expire Date for Spreadsheet
 5350: 
 5351: sub expirespread {
 5352:     my ($uname,$udom,$stype,$usymb)=@_;
 5353:     my $cid=$env{'request.course.id'}; 
 5354:     if ($cid) {
 5355:        my $now=time;
 5356:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5357:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5358:                             $env{'course.'.$cid.'.num'}.
 5359: 	        	    ':nohist_expirationdates:'.
 5360:                             &escape($key).'='.$now,
 5361:                             $env{'course.'.$cid.'.home'})
 5362:     }
 5363:     return 'ok';
 5364: }
 5365: 
 5366: # ----------------------------------------------------- Devalidate Spreadsheets
 5367: 
 5368: sub devalidate {
 5369:     my ($symb,$uname,$udom)=@_;
 5370:     my $cid=$env{'request.course.id'}; 
 5371:     if ($cid) {
 5372:         # delete the stored spreadsheets for
 5373:         # - the student level sheet of this user in course's homespace
 5374:         # - the assessment level sheet for this resource 
 5375:         #   for this user in user's homespace
 5376: 	# - current conditional state info
 5377: 	my $key=$uname.':'.$udom.':';
 5378:         my $status=
 5379: 	    &del('nohist_calculatedsheets',
 5380: 		 [$key.'studentcalc:'],
 5381: 		 $env{'course.'.$cid.'.domain'},
 5382: 		 $env{'course.'.$cid.'.num'})
 5383: 		.' '.
 5384: 	    &del('nohist_calculatedsheets_'.$cid,
 5385: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5386:         unless ($status eq 'ok ok') {
 5387:            &logthis('Could not devalidate spreadsheet '.
 5388:                     $uname.' at '.$udom.' for '.
 5389: 		    $symb.': '.$status);
 5390:         }
 5391: 	&delenv('user.state.'.$cid);
 5392:     }
 5393: }
 5394: 
 5395: sub get_scalar {
 5396:     my ($string,$end) = @_;
 5397:     my $value;
 5398:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5399: 	$value = $1;
 5400:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5401: 	$value = $1;
 5402:     }
 5403:     return &unescape($value);
 5404: }
 5405: 
 5406: sub array2str {
 5407:   my (@array) = @_;
 5408:   my $result=&arrayref2str(\@array);
 5409:   $result=~s/^__ARRAY_REF__//;
 5410:   $result=~s/__END_ARRAY_REF__$//;
 5411:   return $result;
 5412: }
 5413: 
 5414: sub arrayref2str {
 5415:   my ($arrayref) = @_;
 5416:   my $result='__ARRAY_REF__';
 5417:   foreach my $elem (@$arrayref) {
 5418:     if(ref($elem) eq 'ARRAY') {
 5419:       $result.=&arrayref2str($elem).'&';
 5420:     } elsif(ref($elem) eq 'HASH') {
 5421:       $result.=&hashref2str($elem).'&';
 5422:     } elsif(ref($elem)) {
 5423:       #print("Got a ref of ".(ref($elem))." skipping.");
 5424:     } else {
 5425:       $result.=&escape($elem).'&';
 5426:     }
 5427:   }
 5428:   $result=~s/\&$//;
 5429:   $result .= '__END_ARRAY_REF__';
 5430:   return $result;
 5431: }
 5432: 
 5433: sub hash2str {
 5434:   my (%hash) = @_;
 5435:   my $result=&hashref2str(\%hash);
 5436:   $result=~s/^__HASH_REF__//;
 5437:   $result=~s/__END_HASH_REF__$//;
 5438:   return $result;
 5439: }
 5440: 
 5441: sub hashref2str {
 5442:   my ($hashref)=@_;
 5443:   my $result='__HASH_REF__';
 5444:   foreach my $key (sort(keys(%$hashref))) {
 5445:     if (ref($key) eq 'ARRAY') {
 5446:       $result.=&arrayref2str($key).'=';
 5447:     } elsif (ref($key) eq 'HASH') {
 5448:       $result.=&hashref2str($key).'=';
 5449:     } elsif (ref($key)) {
 5450:       $result.='=';
 5451:       #print("Got a ref of ".(ref($key))." skipping.");
 5452:     } else {
 5453: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5454:     }
 5455: 
 5456:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5457:       $result.=&arrayref2str($hashref->{$key}).'&';
 5458:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5459:       $result.=&hashref2str($hashref->{$key}).'&';
 5460:     } elsif(ref($hashref->{$key})) {
 5461:        $result.='&';
 5462:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5463:     } else {
 5464:       $result.=&escape($hashref->{$key}).'&';
 5465:     }
 5466:   }
 5467:   $result=~s/\&$//;
 5468:   $result .= '__END_HASH_REF__';
 5469:   return $result;
 5470: }
 5471: 
 5472: sub str2hash {
 5473:     my ($string)=@_;
 5474:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5475:     return %$hash;
 5476: }
 5477: 
 5478: sub str2hashref {
 5479:   my ($string) = @_;
 5480: 
 5481:   my %hash;
 5482: 
 5483:   if($string !~ /^__HASH_REF__/) {
 5484:       if (! ($string eq '' || !defined($string))) {
 5485: 	  $hash{'error'}='Not hash reference';
 5486:       }
 5487:       return (\%hash, $string);
 5488:   }
 5489: 
 5490:   $string =~ s/^__HASH_REF__//;
 5491: 
 5492:   while($string !~ /^__END_HASH_REF__/) {
 5493:       #key
 5494:       my $key='';
 5495:       if($string =~ /^__HASH_REF__/) {
 5496:           ($key, $string)=&str2hashref($string);
 5497:           if(defined($key->{'error'})) {
 5498:               $hash{'error'}='Bad data';
 5499:               return (\%hash, $string);
 5500:           }
 5501:       } elsif($string =~ /^__ARRAY_REF__/) {
 5502:           ($key, $string)=&str2arrayref($string);
 5503:           if($key->[0] eq 'Array reference error') {
 5504:               $hash{'error'}='Bad data';
 5505:               return (\%hash, $string);
 5506:           }
 5507:       } else {
 5508:           $string =~ s/^(.*?)=//;
 5509: 	  $key=&unescape($1);
 5510:       }
 5511:       $string =~ s/^=//;
 5512: 
 5513:       #value
 5514:       my $value='';
 5515:       if($string =~ /^__HASH_REF__/) {
 5516:           ($value, $string)=&str2hashref($string);
 5517:           if(defined($value->{'error'})) {
 5518:               $hash{'error'}='Bad data';
 5519:               return (\%hash, $string);
 5520:           }
 5521:       } elsif($string =~ /^__ARRAY_REF__/) {
 5522:           ($value, $string)=&str2arrayref($string);
 5523:           if($value->[0] eq 'Array reference error') {
 5524:               $hash{'error'}='Bad data';
 5525:               return (\%hash, $string);
 5526:           }
 5527:       } else {
 5528: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5529:       }
 5530:       $string =~ s/^&//;
 5531: 
 5532:       $hash{$key}=$value;
 5533:   }
 5534: 
 5535:   $string =~ s/^__END_HASH_REF__//;
 5536: 
 5537:   return (\%hash, $string);
 5538: }
 5539: 
 5540: sub str2array {
 5541:     my ($string)=@_;
 5542:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5543:     return @$array;
 5544: }
 5545: 
 5546: sub str2arrayref {
 5547:   my ($string) = @_;
 5548:   my @array;
 5549: 
 5550:   if($string !~ /^__ARRAY_REF__/) {
 5551:       if (! ($string eq '' || !defined($string))) {
 5552: 	  $array[0]='Array reference error';
 5553:       }
 5554:       return (\@array, $string);
 5555:   }
 5556: 
 5557:   $string =~ s/^__ARRAY_REF__//;
 5558: 
 5559:   while($string !~ /^__END_ARRAY_REF__/) {
 5560:       my $value='';
 5561:       if($string =~ /^__HASH_REF__/) {
 5562:           ($value, $string)=&str2hashref($string);
 5563:           if(defined($value->{'error'})) {
 5564:               $array[0] ='Array reference error';
 5565:               return (\@array, $string);
 5566:           }
 5567:       } elsif($string =~ /^__ARRAY_REF__/) {
 5568:           ($value, $string)=&str2arrayref($string);
 5569:           if($value->[0] eq 'Array reference error') {
 5570:               $array[0] ='Array reference error';
 5571:               return (\@array, $string);
 5572:           }
 5573:       } else {
 5574: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5575:       }
 5576:       $string =~ s/^&//;
 5577: 
 5578:       push(@array, $value);
 5579:   }
 5580: 
 5581:   $string =~ s/^__END_ARRAY_REF__//;
 5582: 
 5583:   return (\@array, $string);
 5584: }
 5585: 
 5586: # -------------------------------------------------------------------Temp Store
 5587: 
 5588: sub tmpreset {
 5589:   my ($symb,$namespace,$domain,$stuname) = @_;
 5590:   if (!$symb) {
 5591:     $symb=&symbread();
 5592:     if (!$symb) { $symb= $env{'request.url'}; }
 5593:   }
 5594:   $symb=escape($symb);
 5595: 
 5596:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5597:   $namespace=~s/\//\_/g;
 5598:   $namespace=~s/\W//g;
 5599: 
 5600:   if (!$domain) { $domain=$env{'user.domain'}; }
 5601:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5602:   if ($domain eq 'public' && $stuname eq 'public') {
 5603:       $stuname=$ENV{'REMOTE_ADDR'};
 5604:   }
 5605:   my $path=LONCAPA::tempdir();
 5606:   my %hash;
 5607:   if (tie(%hash,'GDBM_File',
 5608: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5609: 	  &GDBM_WRCREAT(),0640)) {
 5610:     foreach my $key (keys(%hash)) {
 5611:       if ($key=~ /:$symb/) {
 5612: 	delete($hash{$key});
 5613:       }
 5614:     }
 5615:   }
 5616: }
 5617: 
 5618: sub tmpstore {
 5619:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5620: 
 5621:   if (!$symb) {
 5622:     $symb=&symbread();
 5623:     if (!$symb) { $symb= $env{'request.url'}; }
 5624:   }
 5625:   $symb=escape($symb);
 5626: 
 5627:   if (!$namespace) {
 5628:     # I don't think we would ever want to store this for a course.
 5629:     # it seems this will only be used if we don't have a course.
 5630:     #$namespace=$env{'request.course.id'};
 5631:     #if (!$namespace) {
 5632:       $namespace=$env{'request.state'};
 5633:     #}
 5634:   }
 5635:   $namespace=~s/\//\_/g;
 5636:   $namespace=~s/\W//g;
 5637:   if (!$domain) { $domain=$env{'user.domain'}; }
 5638:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5639:   if ($domain eq 'public' && $stuname eq 'public') {
 5640:       $stuname=$ENV{'REMOTE_ADDR'};
 5641:   }
 5642:   my $now=time;
 5643:   my %hash;
 5644:   my $path=LONCAPA::tempdir();
 5645:   if (tie(%hash,'GDBM_File',
 5646: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5647: 	  &GDBM_WRCREAT(),0640)) {
 5648:     $hash{"version:$symb"}++;
 5649:     my $version=$hash{"version:$symb"};
 5650:     my $allkeys=''; 
 5651:     foreach my $key (keys(%$storehash)) {
 5652:       $allkeys.=$key.':';
 5653:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5654:     }
 5655:     $hash{"$version:$symb:timestamp"}=$now;
 5656:     $allkeys.='timestamp';
 5657:     $hash{"$version:keys:$symb"}=$allkeys;
 5658:     if (untie(%hash)) {
 5659:       return 'ok';
 5660:     } else {
 5661:       return "error:$!";
 5662:     }
 5663:   } else {
 5664:     return "error:$!";
 5665:   }
 5666: }
 5667: 
 5668: # -----------------------------------------------------------------Temp Restore
 5669: 
 5670: sub tmprestore {
 5671:   my ($symb,$namespace,$domain,$stuname) = @_;
 5672: 
 5673:   if (!$symb) {
 5674:     $symb=&symbread();
 5675:     if (!$symb) { $symb= $env{'request.url'}; }
 5676:   }
 5677:   $symb=escape($symb);
 5678: 
 5679:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5680: 
 5681:   if (!$domain) { $domain=$env{'user.domain'}; }
 5682:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5683:   if ($domain eq 'public' && $stuname eq 'public') {
 5684:       $stuname=$ENV{'REMOTE_ADDR'};
 5685:   }
 5686:   my %returnhash;
 5687:   $namespace=~s/\//\_/g;
 5688:   $namespace=~s/\W//g;
 5689:   my %hash;
 5690:   my $path=LONCAPA::tempdir();
 5691:   if (tie(%hash,'GDBM_File',
 5692: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5693: 	  &GDBM_READER(),0640)) {
 5694:     my $version=$hash{"version:$symb"};
 5695:     $returnhash{'version'}=$version;
 5696:     my $scope;
 5697:     for ($scope=1;$scope<=$version;$scope++) {
 5698:       my $vkeys=$hash{"$scope:keys:$symb"};
 5699:       my @keys=split(/:/,$vkeys);
 5700:       my $key;
 5701:       $returnhash{"$scope:keys"}=$vkeys;
 5702:       foreach $key (@keys) {
 5703: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5704: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5705:       }
 5706:     }
 5707:     if (!(untie(%hash))) {
 5708:       return "error:$!";
 5709:     }
 5710:   } else {
 5711:     return "error:$!";
 5712:   }
 5713:   return %returnhash;
 5714: }
 5715: 
 5716: # ----------------------------------------------------------------------- Store
 5717: 
 5718: sub store {
 5719:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5720:     my $home='';
 5721: 
 5722:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5723: 
 5724:     $symb=&symbclean($symb);
 5725:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5726: 
 5727:     if (!$domain) { $domain=$env{'user.domain'}; }
 5728:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5729: 
 5730:     &devalidate($symb,$stuname,$domain);
 5731: 
 5732:     $symb=escape($symb);
 5733:     if (!$namespace) { 
 5734:        unless ($namespace=$env{'request.course.id'}) { 
 5735:           return ''; 
 5736:        } 
 5737:     }
 5738:     if (!$home) { $home=$env{'user.home'}; }
 5739: 
 5740:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5741:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5742: 
 5743:     my $namevalue='';
 5744:     foreach my $key (keys(%$storehash)) {
 5745:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5746:     }
 5747:     $namevalue=~s/\&$//;
 5748:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5749:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5750: }
 5751: 
 5752: # -------------------------------------------------------------- Critical Store
 5753: 
 5754: sub cstore {
 5755:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5756:     my $home='';
 5757: 
 5758:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5759: 
 5760:     $symb=&symbclean($symb);
 5761:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5762: 
 5763:     if (!$domain) { $domain=$env{'user.domain'}; }
 5764:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5765: 
 5766:     &devalidate($symb,$stuname,$domain);
 5767: 
 5768:     $symb=escape($symb);
 5769:     if (!$namespace) { 
 5770:        unless ($namespace=$env{'request.course.id'}) { 
 5771:           return ''; 
 5772:        } 
 5773:     }
 5774:     if (!$home) { $home=$env{'user.home'}; }
 5775: 
 5776:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5777:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5778: 
 5779:     my $namevalue='';
 5780:     foreach my $key (keys(%$storehash)) {
 5781:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5782:     }
 5783:     $namevalue=~s/\&$//;
 5784:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5785:     return critical
 5786:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5787: }
 5788: 
 5789: # --------------------------------------------------------------------- Restore
 5790: 
 5791: sub restore {
 5792:     my ($symb,$namespace,$domain,$stuname) = @_;
 5793:     my $home='';
 5794: 
 5795:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5796: 
 5797:     if (!$symb) {
 5798:         return if ($namespace eq 'courserequests');
 5799:         unless ($symb=escape(&symbread())) { return ''; }
 5800:     } else {
 5801:         unless ($namespace eq 'courserequests') {
 5802:             $symb=&escape(&symbclean($symb));
 5803:         }
 5804:     }
 5805:     if (!$namespace) { 
 5806:        unless ($namespace=$env{'request.course.id'}) { 
 5807:           return ''; 
 5808:        } 
 5809:     }
 5810:     if (!$domain) { $domain=$env{'user.domain'}; }
 5811:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5812:     if (!$home) { $home=$env{'user.home'}; }
 5813:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5814: 
 5815:     my %returnhash=();
 5816:     foreach my $line (split(/\&/,$answer)) {
 5817: 	my ($name,$value)=split(/\=/,$line);
 5818:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5819:     }
 5820:     my $version;
 5821:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5822:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5823:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5824:        }
 5825:     }
 5826:     return %returnhash;
 5827: }
 5828: 
 5829: # ---------------------------------------------------------- Course Description
 5830: #
 5831: #  
 5832: 
 5833: sub coursedescription {
 5834:     my ($courseid,$args)=@_;
 5835:     $courseid=~s/^\///;
 5836:     $courseid=~s/\_/\//g;
 5837:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5838:     my $chome=&homeserver($cnum,$cdomain);
 5839:     my $normalid=$cdomain.'_'.$cnum;
 5840:     # need to always cache even if we get errors otherwise we keep 
 5841:     # trying and trying and trying to get the course description.
 5842:     my %envhash=();
 5843:     my %returnhash=();
 5844:     
 5845:     my $expiretime=600;
 5846:     if ($env{'request.course.id'} eq $normalid) {
 5847: 	$expiretime=120;
 5848:     }
 5849: 
 5850:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5851:     if (!$args->{'freshen_cache'}
 5852: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5853: 	foreach my $key (keys(%env)) {
 5854: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5855: 	    my ($setting) = $1;
 5856: 	    $returnhash{$setting} = $env{$key};
 5857: 	}
 5858: 	return %returnhash;
 5859:     }
 5860: 
 5861:     # get the data again
 5862: 
 5863:     if (!$args->{'one_time'}) {
 5864: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5865:     }
 5866: 
 5867:     if ($chome ne 'no_host') {
 5868:        %returnhash=&dump('environment',$cdomain,$cnum);
 5869:        if (!exists($returnhash{'con_lost'})) {
 5870: 	   my $username = $env{'user.name'}; # Defult username
 5871: 	   if(defined $args->{'user'}) {
 5872: 	       $username = $args->{'user'};
 5873: 	   }
 5874:            $returnhash{'home'}= $chome;
 5875: 	   $returnhash{'domain'} = $cdomain;
 5876: 	   $returnhash{'num'} = $cnum;
 5877:            if (!defined($returnhash{'type'})) {
 5878:                $returnhash{'type'} = 'Course';
 5879:            }
 5880:            while (my ($name,$value) = each %returnhash) {
 5881:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5882:            }
 5883:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5884:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5885: 	       $username.'_'.$cdomain.'_'.$cnum;
 5886:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5887:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5888:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5889:        }
 5890:     }
 5891:     if (!$args->{'one_time'}) {
 5892: 	&appenv(\%envhash);
 5893:     }
 5894:     return %returnhash;
 5895: }
 5896: 
 5897: sub update_released_required {
 5898:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5899:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5900:         $cid = $env{'request.course.id'};
 5901:         $cdom = $env{'course.'.$cid.'.domain'};
 5902:         $cnum = $env{'course.'.$cid.'.num'};
 5903:         $chome = $env{'course.'.$cid.'.home'};
 5904:     }
 5905:     if ($needsrelease) {
 5906:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5907:         my $needsupdate;
 5908:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5909:             $needsupdate = 1;
 5910:         } else {
 5911:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5912:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5913:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5914:                 $needsupdate = 1;
 5915:             }
 5916:         }
 5917:         if ($needsupdate) {
 5918:             my %needshash = (
 5919:                              'internal.releaserequired' => $needsrelease,
 5920:                             );
 5921:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5922:             if ($putresult eq 'ok') {
 5923:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5924:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5925:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5926:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5927:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5928:                 }
 5929:             }
 5930:         }
 5931:     }
 5932:     return;
 5933: }
 5934: 
 5935: # -------------------------------------------------See if a user is privileged
 5936: 
 5937: sub privileged {
 5938:     my ($username,$domain,$possdomains,$possroles)=@_;
 5939:     my $now = time;
 5940:     my $roles;
 5941:     if (ref($possroles) eq 'ARRAY') {
 5942:         $roles = $possroles; 
 5943:     } else {
 5944:         $roles = ['dc','su'];
 5945:     }
 5946:     if (ref($possdomains) eq 'ARRAY') {
 5947:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5948:         foreach my $dom (@{$possdomains}) {
 5949:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5950:                 (ref($privileged{$dom}) eq 'HASH')) {
 5951:                 foreach my $role (@{$roles}) {
 5952:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5953:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5954:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5955:                             return 1 unless (($end && $end < $now) ||
 5956:                                              ($start && $start > $now));
 5957:                         }
 5958:                     }
 5959:                 }
 5960:             }
 5961:         }
 5962:     } else {
 5963:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5964:         my $now = time;
 5965: 
 5966:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5967:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5968:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5969:                 return 1 unless ($tend && $tend < $now) 
 5970:                         or ($tstart && $tstart > $now);
 5971:             }
 5972:         }
 5973:     }
 5974:     return 0;
 5975: }
 5976: 
 5977: sub privileged_by_domain {
 5978:     my ($domains,$roles) = @_;
 5979:     my %privileged = ();
 5980:     my $cachetime = 60*60*24;
 5981:     my $now = time;
 5982:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5983:         return %privileged;
 5984:     }
 5985:     foreach my $dom (@{$domains}) {
 5986:         next if (ref($privileged{$dom}) eq 'HASH');
 5987:         my $needroles;
 5988:         foreach my $role (@{$roles}) {
 5989:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5990:             if (defined($cached)) {
 5991:                 if (ref($result) eq 'HASH') {
 5992:                     $privileged{$dom}{$role} = $result;
 5993:                 }
 5994:             } else {
 5995:                 $needroles = 1;
 5996:             }
 5997:         }
 5998:         if ($needroles) {
 5999:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6000:             $privileged{$dom} = {};
 6001:             foreach my $server (keys(%dompersonnel)) {
 6002:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6003:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6004:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6005:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6006:                         next if ($end && $end < $now);
 6007:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6008:                             $dompersonnel{$server}{$item};
 6009:                     }
 6010:                 }
 6011:             }
 6012:             if (ref($privileged{$dom}) eq 'HASH') {
 6013:                 foreach my $role (@{$roles}) {
 6014:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6015:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6016:                     } else {
 6017:                         my %hash = ();
 6018:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6019:                     }
 6020:                 }
 6021:             }
 6022:         }
 6023:     }
 6024:     return %privileged;
 6025: }
 6026: 
 6027: # -------------------------------------------------------- Get user privileges
 6028: 
 6029: sub rolesinit {
 6030:     my ($domain, $username) = @_;
 6031:     my %userroles = ('user.login.time' => time);
 6032:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6033: 
 6034:     # firstaccess and timerinterval are related to timed maps/resources. 
 6035:     # also, blocking can be triggered by an activating timer
 6036:     # it's saved in the user's %env.
 6037:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6038:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6039:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6040:         %timerintchk, %timerintenv);
 6041: 
 6042:     foreach my $key (keys(%firstaccess)) {
 6043:         my ($cid, $rest) = split(/\0/, $key);
 6044:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6045:     }
 6046: 
 6047:     foreach my $key (keys(%timerinterval)) {
 6048:         my ($cid,$rest) = split(/\0/,$key);
 6049:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6050:     }
 6051: 
 6052:     my %allroles=();
 6053:     my %allgroups=();
 6054: 
 6055:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6056:         my $role = $rolesdump{$area};
 6057:         $area =~ s/\_\w\w$//;
 6058: 
 6059:         my ($trole, $tend, $tstart, $group_privs);
 6060: 
 6061:         if ($role =~ /^cr/) {
 6062:         # Custom role, defined by a user 
 6063:         # e.g., user.role.cr/msu/smith/mynewrole
 6064:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6065:                 $trole = $1;
 6066:                 ($tend, $tstart) = split('_', $2);
 6067:             } else {
 6068:                 $trole = $role;
 6069:             }
 6070:         } elsif ($role =~ m|^gr/|) {
 6071:         # Role of member in a group, defined within a course/community
 6072:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6073:             ($trole, $tend, $tstart) = split(/_/, $role);
 6074:             next if $tstart eq '-1';
 6075:             ($trole, $group_privs) = split(/\//, $trole);
 6076:             $group_privs = &unescape($group_privs);
 6077:         } else {
 6078:         # Just a normal role, defined in roles.tab
 6079:             ($trole, $tend, $tstart) = split(/_/,$role);
 6080:         }
 6081: 
 6082:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6083:                  $username);
 6084:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6085: 
 6086:         # role expired or not available yet?
 6087:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6088:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6089: 
 6090:         next if $area eq '' or $trole eq '';
 6091: 
 6092:         my $spec = "$trole.$area";
 6093:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6094: 
 6095:         if ($trole =~ /^cr\//) {
 6096:         # Custom role, defined by a user
 6097:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6098:         } elsif ($trole eq 'gr') {
 6099:         # Role of a member in a group, defined within a course/community
 6100:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6101:             next;
 6102:         } else {
 6103:         # Normal role, defined in roles.tab
 6104:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6105:         }
 6106: 
 6107:         my $cid = $tdomain.'_'.$trest;
 6108:         unless ($firstaccchk{$cid}) {
 6109:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6110:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6111:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6112:                         $coursetimerstarts{$cid}{$item}; 
 6113:                 }
 6114:             }
 6115:             $firstaccchk{$cid} = 1;
 6116:         }
 6117:         unless ($timerintchk{$cid}) {
 6118:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6119:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6120:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6121:                        $coursetimerintervals{$cid}{$item};
 6122:                 }
 6123:             }
 6124:             $timerintchk{$cid} = 1;
 6125:         }
 6126:     }
 6127: 
 6128:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6129:                                                           \%allroles, \%allgroups);
 6130:     $env{'user.adv'} = $userroles{'user.adv'};
 6131:     $env{'user.rar'} = $userroles{'user.rar'};
 6132: 
 6133:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6134: }
 6135: 
 6136: sub set_arearole {
 6137:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6138:     unless ($nolog) {
 6139: # log the associated role with the area
 6140:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6141:     }
 6142:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6143: }
 6144: 
 6145: sub custom_roleprivs {
 6146:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6147:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6148:     my $homsvr = &homeserver($rauthor,$rdomain);
 6149:     if (&hostname($homsvr) ne '') {
 6150:         my ($rdummy,$roledef)=
 6151:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6152:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6153:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6154:             if (defined($syspriv)) {
 6155:                 if ($trest =~ /^$match_community$/) {
 6156:                     $syspriv =~ s/bre\&S//; 
 6157:                 }
 6158:                 $$allroles{'cm./'}.=':'.$syspriv;
 6159:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6160:             }
 6161:             if ($tdomain ne '') {
 6162:                 if (defined($dompriv)) {
 6163:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6164:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6165:                 }
 6166:                 if (($trest ne '') && (defined($coursepriv))) {
 6167:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6168:                         my $rolename = $1;
 6169:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6170:                     }
 6171:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6172:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6173:                 }
 6174:             }
 6175:         }
 6176:     }
 6177: }
 6178: 
 6179: sub course_adhocrole_privs {
 6180:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6181:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6182:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6183:         my (%currprivs,%storeprivs);
 6184:         foreach my $item (split(/:/,$coursepriv)) {
 6185:             my ($priv,$restrict) = split(/\&/,$item);
 6186:             $currprivs{$priv} = $restrict;
 6187:         }
 6188:         my (%possadd,%possremove,%full);
 6189:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6190:             my ($priv,$restrict)=split(/\&/,$item);
 6191:             $full{$priv} = $restrict;
 6192:         }
 6193:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6194:              next if ($item eq '');
 6195:              my ($rule,$rest) = split(/=/,$item);
 6196:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6197:              foreach my $priv (split(/:/,$rest)) {
 6198:                  if ($priv ne '') {
 6199:                      if ($rule eq 'off') {
 6200:                          $possremove{$priv} = 1;
 6201:                      } else {
 6202:                          $possadd{$priv} = 1;
 6203:                      }
 6204:                  }
 6205:              }
 6206:          }
 6207:          foreach my $priv (sort(keys(%full))) {
 6208:              if (exists($currprivs{$priv})) {
 6209:                  unless (exists($possremove{$priv})) {
 6210:                      $storeprivs{$priv} = $currprivs{$priv};
 6211:                  }
 6212:              } elsif (exists($possadd{$priv})) {
 6213:                  $storeprivs{$priv} = $full{$priv};
 6214:              }
 6215:          }
 6216:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6217:      }
 6218:      return $coursepriv;
 6219: }
 6220: 
 6221: sub group_roleprivs {
 6222:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6223:     my $access = 1;
 6224:     my $now = time;
 6225:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6226:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6227:     if ($access) {
 6228:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6229:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6230:     }
 6231: }
 6232: 
 6233: sub standard_roleprivs {
 6234:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6235:     if (defined($pr{$trole.':s'})) {
 6236:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6237:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6238:     }
 6239:     if ($tdomain ne '') {
 6240:         if (defined($pr{$trole.':d'})) {
 6241:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6242:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6243:         }
 6244:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6245:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6246:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6247:         }
 6248:     }
 6249: }
 6250: 
 6251: sub set_userprivs {
 6252:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6253:     my $author=0;
 6254:     my $adv=0;
 6255:     my $rar=0;
 6256:     my %grouproles = ();
 6257:     if (keys(%{$allgroups}) > 0) {
 6258:         my @groupkeys; 
 6259:         foreach my $role (keys(%{$allroles})) {
 6260:             push(@groupkeys,$role);
 6261:         }
 6262:         if (ref($groups_roles) eq 'HASH') {
 6263:             foreach my $key (keys(%{$groups_roles})) {
 6264:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6265:                     push(@groupkeys,$key);
 6266:                 }
 6267:             }
 6268:         }
 6269:         if (@groupkeys > 0) {
 6270:             foreach my $role (@groupkeys) {
 6271:                 my ($trole,$area,$sec,$extendedarea);
 6272:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6273:                     $trole = $1;
 6274:                     $area = $2;
 6275:                     $sec = $3;
 6276:                     $extendedarea = $area.$sec;
 6277:                     if (exists($$allgroups{$area})) {
 6278:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6279:                             my $spec = $trole.'.'.$extendedarea;
 6280:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6281:                                                 $$allgroups{$area}{$group};
 6282:                         }
 6283:                     }
 6284:                 }
 6285:             }
 6286:         }
 6287:     }
 6288:     foreach my $group (keys(%grouproles)) {
 6289:         $$allroles{$group} = $grouproles{$group};
 6290:     }
 6291:     foreach my $role (keys(%{$allroles})) {
 6292:         my %thesepriv;
 6293:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6294:         foreach my $item (split(/:/,$$allroles{$role})) {
 6295:             if ($item ne '') {
 6296:                 my ($privilege,$restrictions)=split(/&/,$item);
 6297:                 if ($restrictions eq '') {
 6298:                     $thesepriv{$privilege}='F';
 6299:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6300:                     $thesepriv{$privilege}.=$restrictions;
 6301:                 }
 6302:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6303:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6304:             }
 6305:         }
 6306:         my $thesestr='';
 6307:         foreach my $priv (sort(keys(%thesepriv))) {
 6308: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6309: 	}
 6310:         $userroles->{'user.priv.'.$role} = $thesestr;
 6311:     }
 6312:     return ($author,$adv,$rar);
 6313: }
 6314: 
 6315: sub role_status {
 6316:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6317:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6318:         my ($one,$two) = split(m{\./},$rolekey,2);
 6319:         (undef,undef,$$role) = split(/\./,$one,3);
 6320:         unless (!defined($$role) || $$role eq '') {
 6321:             $$where = '/'.$two;
 6322:             $$trolecode=$$role.'.'.$$where;
 6323:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6324:             $$tstatus='is';
 6325:             if ($$tstart && $$tstart>$update) {
 6326:                 $$tstatus='future';
 6327:                 if ($$tstart<$now) {
 6328:                     if ($$tstart && $$tstart>$refresh) {
 6329:                         if (($$where ne '') && ($$role ne '')) {
 6330:                             my (%allroles,%allgroups,$group_privs,
 6331:                                 %groups_roles,@rolecodes);
 6332:                             my %userroles = (
 6333:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6334:                             );
 6335:                             @rolecodes = ('cm'); 
 6336:                             my $spec=$$role.'.'.$$where;
 6337:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6338:                             if ($$role =~ /^cr\//) {
 6339:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6340:                                 push(@rolecodes,'cr');
 6341:                             } elsif ($$role eq 'gr') {
 6342:                                 push(@rolecodes,$$role);
 6343:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6344:                                                     $env{'user.name'});
 6345:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6346:                                 (undef,my $group_privs) = split(/\//,$trole);
 6347:                                 $group_privs = &unescape($group_privs);
 6348:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6349:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6350:                                 &get_groups_roles($tdomain,$trest,
 6351:                                                   \%course_roles,\@rolecodes,
 6352:                                                   \%groups_roles);
 6353:                             } else {
 6354:                                 push(@rolecodes,$$role);
 6355:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6356:                             }
 6357:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6358:                                                                    \%groups_roles);
 6359:                             &appenv(\%userroles,\@rolecodes);
 6360:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6361:                         }
 6362:                     }
 6363:                     $$tstatus = 'is';
 6364:                 }
 6365:             }
 6366:             if ($$tend) {
 6367:                 if ($$tend<$update) {
 6368:                     $$tstatus='expired';
 6369:                 } elsif ($$tend<$now) {
 6370:                     $$tstatus='will_not';
 6371:                 }
 6372:             }
 6373:         }
 6374:     }
 6375: }
 6376: 
 6377: sub get_groups_roles {
 6378:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6379:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6380:                   (ref($rolecodes) eq 'ARRAY') && 
 6381:                   (ref($groups_roles) eq 'HASH')); 
 6382:     if (keys(%{$cdom_courseroles}) > 0) {
 6383:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6384:         if ($cdom ne '' && $cnum ne '') {
 6385:             foreach my $key (keys(%{$cdom_courseroles})) {
 6386:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6387:                     my $crsrole = $1;
 6388:                     my $crssec = $2;
 6389:                     if ($crsrole =~ /^cr/) {
 6390:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6391:                             push(@{$rolecodes},'cr');
 6392:                         }
 6393:                     } else {
 6394:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6395:                             push(@{$rolecodes},$crsrole);
 6396:                         }
 6397:                     }
 6398:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6399:                     if ($crssec ne '') {
 6400:                         $rolekey .= "/$crssec";
 6401:                     }
 6402:                     $rolekey .= './';
 6403:                     $groups_roles->{$rolekey} = $rolecodes;
 6404:                 }
 6405:             }
 6406:         }
 6407:     }
 6408:     return;
 6409: }
 6410: 
 6411: sub delete_env_groupprivs {
 6412:     my ($where,$courseroles,$possroles) = @_;
 6413:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6414:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6415:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6416:         %{$courseroles->{$udom}} =
 6417:             &get_my_roles('','','userroles',['active'],
 6418:                           $possroles,[$udom],1);
 6419:     }
 6420:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6421:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6422:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6423:             my $area = '/'.$cdom.'/'.$cnum;
 6424:             my $privkey = "user.priv.$crsrole.$area";
 6425:             if ($crssec ne '') {
 6426:                 $privkey .= '/'.$crssec;
 6427:             }
 6428:             $privkey .= ".$area/$group";
 6429:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6430:         }
 6431:     }
 6432:     return;
 6433: }
 6434: 
 6435: sub check_adhoc_privs {
 6436:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6437:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6438:     if ($sec) {
 6439:         $cckey .= '/'.$sec;
 6440:     } 
 6441:     my $setprivs;
 6442:     if ($env{$cckey}) {
 6443:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6444:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6445:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6446:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6447:             $setprivs = 1;
 6448:         }
 6449:     } else {
 6450:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6451:         $setprivs = 1;
 6452:     }
 6453:     return $setprivs;
 6454: }
 6455: 
 6456: sub set_adhoc_privileges {
 6457: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6458:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6459:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6460:     if ($sec ne '') {
 6461:         $area .= '/'.$sec;
 6462:     }
 6463:     my $spec = $role.'.'.$area;
 6464:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6465:                                   $env{'user.name'},1);
 6466:     my %rolehash = ();
 6467:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6468:         my $rolename = $1;
 6469:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6470:         my %domdef = &get_domain_defaults($dcdom);
 6471:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6472:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6473:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6474:             }
 6475:         }
 6476:     } else {
 6477:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6478:     }
 6479:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6480:     &appenv(\%userroles,[$role,'cm']);
 6481:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6482:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6483:         &appenv( {'request.role'        => $spec,
 6484:                   'request.role.domain' => $dcdom,
 6485:                   'request.course.sec'  => $sec,
 6486:                  }
 6487:                );
 6488:         my $tadv=0;
 6489:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6490:         &appenv({'request.role.adv'    => $tadv});
 6491:     }
 6492: }
 6493: 
 6494: # --------------------------------------------------------------- get interface
 6495: 
 6496: sub get {
 6497:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6498:    my $items='';
 6499:    foreach my $item (@$storearr) {
 6500:        $items.=&escape($item).'&';
 6501:    }
 6502:    $items=~s/\&$//;
 6503:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6504:    if (!$uname) { $uname=$env{'user.name'}; }
 6505:    my $uhome=&homeserver($uname,$udomain);
 6506: 
 6507:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6508:    my @pairs=split(/\&/,$rep);
 6509:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6510:      return @pairs;
 6511:    }
 6512:    my %returnhash=();
 6513:    my $i=0;
 6514:    foreach my $item (@$storearr) {
 6515:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6516:       $i++;
 6517:    }
 6518:    return %returnhash;
 6519: }
 6520: 
 6521: # --------------------------------------------------------------- del interface
 6522: 
 6523: sub del {
 6524:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6525:    my $items='';
 6526:    foreach my $item (@$storearr) {
 6527:        $items.=&escape($item).'&';
 6528:    }
 6529: 
 6530:    $items=~s/\&$//;
 6531:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6532:    if (!$uname) { $uname=$env{'user.name'}; }
 6533:    my $uhome=&homeserver($uname,$udomain);
 6534:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6535: }
 6536: 
 6537: # -------------------------------------------------------------- dump interface
 6538: 
 6539: sub unserialize {
 6540:     my ($rep, $escapedkeys) = @_;
 6541: 
 6542:     return {} if $rep =~ /^error/;
 6543: 
 6544:     my %returnhash=();
 6545: 	foreach my $item (split(/\&/,$rep)) {
 6546: 	    my ($key, $value) = split(/=/, $item, 2);
 6547: 	    $key = unescape($key) unless $escapedkeys;
 6548: 	    next if $key =~ /^error: 2 /;
 6549: 	    $returnhash{$key} = &thaw_unescape($value);
 6550: 	}
 6551:     #return %returnhash;
 6552:     return \%returnhash;
 6553: }        
 6554: 
 6555: # see Lond::dump_with_regexp
 6556: # if $escapedkeys hash keys won't get unescaped.
 6557: sub dump {
 6558:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6559:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6560:     if (!$uname) { $uname=$env{'user.name'}; }
 6561:     my $uhome=&homeserver($uname,$udomain);
 6562: 
 6563:     if ($regexp) {
 6564:         $regexp=&escape($regexp);
 6565:     } else {
 6566:         $regexp='.';
 6567:     }
 6568:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6569:         # user is hosted on this machine
 6570:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6571:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6572:         return %{unserialize($reply, $escapedkeys)};
 6573:     }
 6574:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6575:     my @pairs=split(/\&/,$rep);
 6576:     my %returnhash=();
 6577:     if (!($rep =~ /^error/ )) {
 6578: 	foreach my $item (@pairs) {
 6579: 	    my ($key,$value)=split(/=/,$item,2);
 6580:         $key = unescape($key) unless $escapedkeys;
 6581:         #$key = &unescape($key);
 6582: 	    next if ($key =~ /^error: 2 /);
 6583: 	    $returnhash{$key}=&thaw_unescape($value);
 6584: 	}
 6585:     }
 6586:     return %returnhash;
 6587: }
 6588: 
 6589: 
 6590: # --------------------------------------------------------- dumpstore interface
 6591: 
 6592: sub dumpstore {
 6593:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6594:    # same as dump but keys must be escaped. They may contain colon separated
 6595:    # lists of values that may themself contain colons (e.g. symbs).
 6596:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6597: }
 6598: 
 6599: # -------------------------------------------------------------- keys interface
 6600: 
 6601: sub getkeys {
 6602:    my ($namespace,$udomain,$uname)=@_;
 6603:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6604:    if (!$uname) { $uname=$env{'user.name'}; }
 6605:    my $uhome=&homeserver($uname,$udomain);
 6606:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6607:    my @keyarray=();
 6608:    foreach my $key (split(/\&/,$rep)) {
 6609:       next if ($key =~ /^error: 2 /);
 6610:       push(@keyarray,&unescape($key));
 6611:    }
 6612:    return @keyarray;
 6613: }
 6614: 
 6615: # --------------------------------------------------------------- currentdump
 6616: sub currentdump {
 6617:    my ($courseid,$sdom,$sname)=@_;
 6618:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6619:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6620:    $sname    = $env{'user.name'}         if (! defined($sname));
 6621:    my $uhome = &homeserver($sname,$sdom);
 6622:    my $rep;
 6623: 
 6624:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6625:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6626:                    $courseid)));
 6627:    } else {
 6628:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6629:    }
 6630: 
 6631:    return if ($rep =~ /^(error:|no_such_host)/);
 6632:    #
 6633:    my %returnhash=();
 6634:    #
 6635:    if ($rep eq 'unknown_cmd') {
 6636:        # an old lond will not know currentdump
 6637:        # Do a dump and make it look like a currentdump
 6638:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6639:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6640:        my %hash = @tmp;
 6641:        @tmp=();
 6642:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6643:    } else {
 6644:        my @pairs=split(/\&/,$rep);
 6645:        foreach my $pair (@pairs) {
 6646:            my ($key,$value)=split(/=/,$pair,2);
 6647:            my ($symb,$param) = split(/:/,$key);
 6648:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6649:                                                         &thaw_unescape($value);
 6650:        }
 6651:    }
 6652:    return %returnhash;
 6653: }
 6654: 
 6655: sub convert_dump_to_currentdump{
 6656:     my %hash = %{shift()};
 6657:     my %returnhash;
 6658:     # Code ripped from lond, essentially.  The only difference
 6659:     # here is the unescaping done by lonnet::dump().  Conceivably
 6660:     # we might run in to problems with parameter names =~ /^v\./
 6661:     while (my ($key,$value) = each(%hash)) {
 6662:         my ($v,$symb,$param) = split(/:/,$key);
 6663: 	$symb  = &unescape($symb);
 6664: 	$param = &unescape($param);
 6665:         next if ($v eq 'version' || $symb eq 'keys');
 6666:         next if (exists($returnhash{$symb}) &&
 6667:                  exists($returnhash{$symb}->{$param}) &&
 6668:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6669:         $returnhash{$symb}->{$param}=$value;
 6670:         $returnhash{$symb}->{'v.'.$param}=$v;
 6671:     }
 6672:     #
 6673:     # Remove all of the keys in the hashes which keep track of
 6674:     # the version of the parameter.
 6675:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6676:         # use a foreach because we are going to delete from the hash.
 6677:         foreach my $key (keys(%$param_hash)) {
 6678:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6679:         }
 6680:     }
 6681:     return \%returnhash;
 6682: }
 6683: 
 6684: # ------------------------------------------------------ critical inc interface
 6685: 
 6686: sub cinc {
 6687:     return &inc(@_,'critical');
 6688: }
 6689: 
 6690: # --------------------------------------------------------------- inc interface
 6691: 
 6692: sub inc {
 6693:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6694:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6695:     if (!$uname) { $uname=$env{'user.name'}; }
 6696:     my $uhome=&homeserver($uname,$udomain);
 6697:     my $items='';
 6698:     if (! ref($store)) {
 6699:         # got a single value, so use that instead
 6700:         $items = &escape($store).'=&';
 6701:     } elsif (ref($store) eq 'SCALAR') {
 6702:         $items = &escape($$store).'=&';        
 6703:     } elsif (ref($store) eq 'ARRAY') {
 6704:         $items = join('=&',map {&escape($_);} @{$store});
 6705:     } elsif (ref($store) eq 'HASH') {
 6706:         while (my($key,$value) = each(%{$store})) {
 6707:             $items.= &escape($key).'='.&escape($value).'&';
 6708:         }
 6709:     }
 6710:     $items=~s/\&$//;
 6711:     if ($critical) {
 6712: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6713:     } else {
 6714: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6715:     }
 6716: }
 6717: 
 6718: # --------------------------------------------------------------- put interface
 6719: 
 6720: sub put {
 6721:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6722:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6723:    if (!$uname) { $uname=$env{'user.name'}; }
 6724:    my $uhome=&homeserver($uname,$udomain);
 6725:    my $items='';
 6726:    foreach my $item (keys(%$storehash)) {
 6727:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6728:    }
 6729:    $items=~s/\&$//;
 6730:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6731: }
 6732: 
 6733: # ------------------------------------------------------------ newput interface
 6734: 
 6735: sub newput {
 6736:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6737:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6738:    if (!$uname) { $uname=$env{'user.name'}; }
 6739:    my $uhome=&homeserver($uname,$udomain);
 6740:    my $items='';
 6741:    foreach my $key (keys(%$storehash)) {
 6742:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6743:    }
 6744:    $items=~s/\&$//;
 6745:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6746: }
 6747: 
 6748: # ---------------------------------------------------------  putstore interface
 6749: 
 6750: sub putstore {
 6751:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6752:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6753:    if (!$uname) { $uname=$env{'user.name'}; }
 6754:    my $uhome=&homeserver($uname,$udomain);
 6755:    my $items='';
 6756:    foreach my $key (keys(%$storehash)) {
 6757:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6758:    }
 6759:    $items=~s/\&$//;
 6760:    my $esc_symb=&escape($symb);
 6761:    my $esc_v=&escape($version);
 6762:    my $reply =
 6763:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6764: 	      $uhome);
 6765:    if (($tolog) && ($reply eq 'ok')) {
 6766:        my $namevalue='';
 6767:        foreach my $key (keys(%{$storehash})) {
 6768:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6769:        }
 6770:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6771:                      '&host='.&escape($perlvar{'lonHostID'}).
 6772:                      '&version='.$esc_v.
 6773:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6774:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6775:    }
 6776:    if ($reply eq 'unknown_cmd') {
 6777:        # gfall back to way things use to be done
 6778:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6779: 			    $uname);
 6780:    }
 6781:    return $reply;
 6782: }
 6783: 
 6784: sub old_putstore {
 6785:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6786:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6787:     if (!$uname) { $uname=$env{'user.name'}; }
 6788:     my $uhome=&homeserver($uname,$udomain);
 6789:     my %newstorehash;
 6790:     foreach my $item (keys(%$storehash)) {
 6791: 	my $key = $version.':'.&escape($symb).':'.$item;
 6792: 	$newstorehash{$key} = $storehash->{$item};
 6793:     }
 6794:     my $items='';
 6795:     my %allitems = ();
 6796:     foreach my $item (keys(%newstorehash)) {
 6797: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6798: 	    my $key = $1.':keys:'.$2;
 6799: 	    $allitems{$key} .= $3.':';
 6800: 	}
 6801: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6802:     }
 6803:     foreach my $item (keys(%allitems)) {
 6804: 	$allitems{$item} =~ s/\:$//;
 6805: 	$items.= $item.'='.$allitems{$item}.'&';
 6806:     }
 6807:     $items=~s/\&$//;
 6808:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6809: }
 6810: 
 6811: # ------------------------------------------------------ critical put interface
 6812: 
 6813: sub cput {
 6814:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6815:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6816:    if (!$uname) { $uname=$env{'user.name'}; }
 6817:    my $uhome=&homeserver($uname,$udomain);
 6818:    my $items='';
 6819:    foreach my $item (keys(%$storehash)) {
 6820:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6821:    }
 6822:    $items=~s/\&$//;
 6823:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6824: }
 6825: 
 6826: # -------------------------------------------------------------- eget interface
 6827: 
 6828: sub eget {
 6829:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6830:    my $items='';
 6831:    foreach my $item (@$storearr) {
 6832:        $items.=&escape($item).'&';
 6833:    }
 6834:    $items=~s/\&$//;
 6835:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6836:    if (!$uname) { $uname=$env{'user.name'}; }
 6837:    my $uhome=&homeserver($uname,$udomain);
 6838:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6839:    my @pairs=split(/\&/,$rep);
 6840:    my %returnhash=();
 6841:    my $i=0;
 6842:    foreach my $item (@$storearr) {
 6843:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6844:       $i++;
 6845:    }
 6846:    return %returnhash;
 6847: }
 6848: 
 6849: # ------------------------------------------------------------ tmpput interface
 6850: sub tmpput {
 6851:     my ($storehash,$server,$context)=@_;
 6852:     my $items='';
 6853:     foreach my $item (keys(%$storehash)) {
 6854: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6855:     }
 6856:     $items=~s/\&$//;
 6857:     if (defined($context)) {
 6858:         $items .= ':'.&escape($context);
 6859:     }
 6860:     return &reply("tmpput:$items",$server);
 6861: }
 6862: 
 6863: # ------------------------------------------------------------ tmpget interface
 6864: sub tmpget {
 6865:     my ($token,$server)=@_;
 6866:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6867:     my $rep=&reply("tmpget:$token",$server);
 6868:     my %returnhash;
 6869:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6870:         return %returnhash;
 6871:     }
 6872:     foreach my $item (split(/\&/,$rep)) {
 6873: 	my ($key,$value)=split(/=/,$item);
 6874: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6875:     }
 6876:     return %returnhash;
 6877: }
 6878: 
 6879: # ------------------------------------------------------------ tmpdel interface
 6880: sub tmpdel {
 6881:     my ($token,$server)=@_;
 6882:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6883:     return &reply("tmpdel:$token",$server);
 6884: }
 6885: 
 6886: # ------------------------------------------------------------ get_timebased_id 
 6887: 
 6888: sub get_timebased_id {
 6889:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6890:         $maxtries) = @_;
 6891:     my ($newid,$error,$dellock);
 6892:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6893:         return ('','ok','invalid call to get suffix');
 6894:     }
 6895: 
 6896: # set defaults for any optional args for which values were not supplied
 6897:     if ($who eq '') {
 6898:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6899:     }
 6900:     if (!$locktries) {
 6901:         $locktries = 3;
 6902:     }
 6903:     if (!$maxtries) {
 6904:         $maxtries = 10;
 6905:     }
 6906:     
 6907:     if (($cdom eq '') || ($cnum eq '')) {
 6908:         if ($env{'request.course.id'}) {
 6909:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6910:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6911:         }
 6912:         if (($cdom eq '') || ($cnum eq '')) {
 6913:             return ('','ok','call to get suffix not in course context');
 6914:         }
 6915:     }
 6916: 
 6917: # construct locking item
 6918:     my $lockhash = {
 6919:                       $prefix."\0".'locked_'.$keyid => $who,
 6920:                    };
 6921:     my $tries = 0;
 6922: 
 6923: # attempt to get lock on nohist_$namespace file
 6924:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6925:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6926:         $tries ++;
 6927:         sleep 1;
 6928:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6929:     }
 6930: 
 6931: # attempt to get unique identifier, based on current timestamp
 6932:     if ($gotlock eq 'ok') {
 6933:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6934:         my $id = time;
 6935:         $newid = $id;
 6936:         if ($idtype eq 'addcode') {
 6937:             $newid .= &sixnum_code();
 6938:         }
 6939:         my $idtries = 0;
 6940:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6941:             if ($idtype eq 'concat') {
 6942:                 $newid = $id.$idtries;
 6943:             } elsif ($idtype eq 'addcode') {
 6944:                 $newid = $newid.&sixnum_code();
 6945:             } else {
 6946:                 $newid ++;
 6947:             }
 6948:             $idtries ++;
 6949:         }
 6950:         if (!exists($inuse{$prefix."\0".$newid})) {
 6951:             my %new_item =  (
 6952:                               $prefix."\0".$newid => $who,
 6953:                             );
 6954:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6955:                                                  $cdom,$cnum);
 6956:             if ($putresult ne 'ok') {
 6957:                 undef($newid);
 6958:                 $error = 'error saving new item: '.$putresult;
 6959:             }
 6960:         } else {
 6961:              undef($newid);
 6962:              $error = ('error: no unique suffix available for the new item ');
 6963:         }
 6964: #  remove lock
 6965:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6966:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6967:     } else {
 6968:         $error = "error: could not obtain lockfile\n";
 6969:         $dellock = 'ok';
 6970:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6971:             $dellock = 'nolock';
 6972:         }
 6973:     }
 6974:     return ($newid,$dellock,$error);
 6975: }
 6976: 
 6977: sub sixnum_code {
 6978:     my $code;
 6979:     for (0..6) {
 6980:         $code .= int( rand(9) );
 6981:     }
 6982:     return $code;
 6983: }
 6984: 
 6985: # -------------------------------------------------- portfolio access checking
 6986: 
 6987: sub portfolio_access {
 6988:     my ($requrl,$clientip) = @_;
 6989:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6990:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6991:     if ($result) {
 6992:         my %setters;
 6993:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6994:             my ($startblock,$endblock) =
 6995:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6996:             if ($startblock && $endblock) {
 6997:                 return 'B';
 6998:             }
 6999:         } else {
 7000:             my ($startblock,$endblock) =
 7001:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7002:             if ($startblock && $endblock) {
 7003:                 return 'B';
 7004:             }
 7005:         }
 7006:     }
 7007:     if ($result eq 'ok') {
 7008:        return 'F';
 7009:     } elsif ($result =~ /^[^:]+:guest_/) {
 7010:        return 'A';
 7011:     }
 7012:     return '';
 7013: }
 7014: 
 7015: sub get_portfolio_access {
 7016:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7017: 
 7018:     if (!ref($access_hash)) {
 7019: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7020: 	my %access_controls = &get_access_controls($current_perms,$group,
 7021: 						   $file_name);
 7022: 	$access_hash = $access_controls{$file_name};
 7023:     }
 7024: 
 7025:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7026:     my $now = time;
 7027:     if (ref($access_hash) eq 'HASH') {
 7028:         foreach my $key (keys(%{$access_hash})) {
 7029:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7030:             if ($start > $now) {
 7031:                 next;
 7032:             }
 7033:             if ($end && $end<$now) {
 7034:                 next;
 7035:             }
 7036:             if ($scope eq 'public') {
 7037:                 $public = $key;
 7038:                 last;
 7039:             } elsif ($scope eq 'guest') {
 7040:                 $guest = $key;
 7041:             } elsif ($scope eq 'domains') {
 7042:                 push(@domains,$key);
 7043:             } elsif ($scope eq 'users') {
 7044:                 push(@users,$key);
 7045:             } elsif ($scope eq 'course') {
 7046:                 push(@courses,$key);
 7047:             } elsif ($scope eq 'group') {
 7048:                 push(@groups,$key);
 7049:             } elsif ($scope eq 'ip') {
 7050:                 push(@ips,$key);
 7051:             }
 7052:         }
 7053:         if ($public) {
 7054:             return 'ok';
 7055:         } elsif (@ips > 0) {
 7056:             my $allowed;
 7057:             foreach my $ipkey (@ips) {
 7058:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7059:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7060:                         $allowed = 1;
 7061:                         last; 
 7062:                     }
 7063:                 }
 7064:             }
 7065:             if ($allowed) {
 7066:                 return 'ok';
 7067:             }
 7068:         }
 7069:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7070:             if ($guest) {
 7071:                 return $guest;
 7072:             }
 7073:         } else {
 7074:             if (@domains > 0) {
 7075:                 foreach my $domkey (@domains) {
 7076:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7077:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7078:                             return 'ok';
 7079:                         }
 7080:                     }
 7081:                 }
 7082:             }
 7083:             if (@users > 0) {
 7084:                 foreach my $userkey (@users) {
 7085:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7086:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7087:                             if (ref($item) eq 'HASH') {
 7088:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7089:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7090:                                     return 'ok';
 7091:                                 }
 7092:                             }
 7093:                         }
 7094:                     } 
 7095:                 }
 7096:             }
 7097:             my %roleshash;
 7098:             my @courses_and_groups = @courses;
 7099:             push(@courses_and_groups,@groups); 
 7100:             if (@courses_and_groups > 0) {
 7101:                 my (%allgroups,%allroles); 
 7102:                 my ($start,$end,$role,$sec,$group);
 7103:                 foreach my $envkey (%env) {
 7104:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7105:                         my $cid = $2.'_'.$3; 
 7106:                         if ($1 eq 'gr') {
 7107:                             $group = $4;
 7108:                             $allgroups{$cid}{$group} = $env{$envkey};
 7109:                         } else {
 7110:                             if ($4 eq '') {
 7111:                                 $sec = 'none';
 7112:                             } else {
 7113:                                 $sec = $4;
 7114:                             }
 7115:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7116:                         }
 7117:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7118:                         my $cid = $2.'_'.$3;
 7119:                         if ($4 eq '') {
 7120:                             $sec = 'none';
 7121:                         } else {
 7122:                             $sec = $4;
 7123:                         }
 7124:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7125:                     }
 7126:                 }
 7127:                 if (keys(%allroles) == 0) {
 7128:                     return;
 7129:                 }
 7130:                 foreach my $key (@courses_and_groups) {
 7131:                     my %content = %{$$access_hash{$key}};
 7132:                     my $cnum = $content{'number'};
 7133:                     my $cdom = $content{'domain'};
 7134:                     my $cid = $cdom.'_'.$cnum;
 7135:                     if (!exists($allroles{$cid})) {
 7136:                         next;
 7137:                     }    
 7138:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7139:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7140:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7141:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7142:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7143:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7144:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7145:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7146:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7147:                                         if (grep/^all$/,@sections) {
 7148:                                             return 'ok';
 7149:                                         } else {
 7150:                                             if (grep/^$sec$/,@sections) {
 7151:                                                 return 'ok';
 7152:                                             }
 7153:                                         }
 7154:                                     }
 7155:                                 }
 7156:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7157:                                     if (grep/^none$/,@groups) {
 7158:                                         return 'ok';
 7159:                                     }
 7160:                                 } else {
 7161:                                     if (grep/^all$/,@groups) {
 7162:                                         return 'ok';
 7163:                                     } 
 7164:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7165:                                         if (grep/^$group$/,@groups) {
 7166:                                             return 'ok';
 7167:                                         }
 7168:                                     }
 7169:                                 } 
 7170:                             }
 7171:                         }
 7172:                     }
 7173:                 }
 7174:             }
 7175:             if ($guest) {
 7176:                 return $guest;
 7177:             }
 7178:         }
 7179:     }
 7180:     return;
 7181: }
 7182: 
 7183: sub course_group_datechecker {
 7184:     my ($dates,$now,$status) = @_;
 7185:     my ($start,$end) = split(/\./,$dates);
 7186:     if (!$start && !$end) {
 7187:         return 'ok';
 7188:     }
 7189:     if (grep/^active$/,@{$status}) {
 7190:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7191:             return 'ok';
 7192:         }
 7193:     }
 7194:     if (grep/^previous$/,@{$status}) {
 7195:         if ($end > $now ) {
 7196:             return 'ok';
 7197:         }
 7198:     }
 7199:     if (grep/^future$/,@{$status}) {
 7200:         if ($start > $now) {
 7201:             return 'ok';
 7202:         }
 7203:     }
 7204:     return; 
 7205: }
 7206: 
 7207: sub parse_portfolio_url {
 7208:     my ($url) = @_;
 7209: 
 7210:     my ($type,$udom,$unum,$group,$file_name);
 7211:     
 7212:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7213: 	$type = 1;
 7214:         $udom = $1;
 7215:         $unum = $2;
 7216:         $file_name = $3;
 7217:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7218: 	$type = 2;
 7219:         $udom = $1;
 7220:         $unum = $2;
 7221:         $group = $3;
 7222:         $file_name = $3.'/'.$4;
 7223:     }
 7224:     if (wantarray) {
 7225: 	return ($type,$udom,$unum,$file_name,$group);
 7226:     }
 7227:     return $type;
 7228: }
 7229: 
 7230: sub is_portfolio_url {
 7231:     my ($url) = @_;
 7232:     return scalar(&parse_portfolio_url($url));
 7233: }
 7234: 
 7235: sub is_portfolio_file {
 7236:     my ($file) = @_;
 7237:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7238:         return 1;
 7239:     }
 7240:     return;
 7241: }
 7242: 
 7243: sub usertools_access {
 7244:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7245:     my ($access,%tools);
 7246:     if ($context eq '') {
 7247:         $context = 'tools';
 7248:     }
 7249:     if ($context eq 'requestcourses') {
 7250:         %tools = (
 7251:                       official   => 1,
 7252:                       unofficial => 1,
 7253:                       community  => 1,
 7254:                       textbook   => 1,
 7255:                       placement  => 1,
 7256:                       lti        => 1,
 7257:                  );
 7258:     } elsif ($context eq 'requestauthor') {
 7259:         %tools = (
 7260:                       requestauthor => 1,
 7261:                  );
 7262:     } else {
 7263:         %tools = (
 7264:                       aboutme   => 1,
 7265:                       blog      => 1,
 7266:                       webdav    => 1,
 7267:                       portfolio => 1,
 7268:                  );
 7269:     }
 7270:     return if (!defined($tools{$tool}));
 7271: 
 7272:     if (($udom eq '') || ($uname eq '')) {
 7273:         $udom = $env{'user.domain'};
 7274:         $uname = $env{'user.name'};
 7275:     }
 7276: 
 7277:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7278:         if ($action ne 'reload') {
 7279:             if ($context eq 'requestcourses') {
 7280:                 return $env{'environment.canrequest.'.$tool};
 7281:             } elsif ($context eq 'requestauthor') {
 7282:                 return $env{'environment.canrequest.author'};
 7283:             } else {
 7284:                 return $env{'environment.availabletools.'.$tool};
 7285:             }
 7286:         }
 7287:     }
 7288: 
 7289:     my ($toolstatus,$inststatus,$envkey);
 7290:     if ($context eq 'requestauthor') {
 7291:         $envkey = $context; 
 7292:     } else {
 7293:         $envkey = $context.'.'.$tool;
 7294:     }
 7295: 
 7296:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7297:          ($action ne 'reload')) {
 7298:         $toolstatus = $env{'environment.'.$envkey};
 7299:         $inststatus = $env{'environment.inststatus'};
 7300:     } else {
 7301:         if (ref($userenvref) eq 'HASH') {
 7302:             $toolstatus = $userenvref->{$envkey};
 7303:             $inststatus = $userenvref->{'inststatus'};
 7304:         } else {
 7305:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7306:             $toolstatus = $userenv{$envkey};
 7307:             $inststatus = $userenv{'inststatus'};
 7308:         }
 7309:     }
 7310: 
 7311:     if ($toolstatus ne '') {
 7312:         if ($toolstatus) {
 7313:             $access = 1;
 7314:         } else {
 7315:             $access = 0;
 7316:         }
 7317:         return $access;
 7318:     }
 7319: 
 7320:     my ($is_adv,%domdef);
 7321:     if (ref($is_advref) eq 'HASH') {
 7322:         $is_adv = $is_advref->{'is_adv'};
 7323:     } else {
 7324:         $is_adv = &is_advanced_user($udom,$uname);
 7325:     }
 7326:     if (ref($domdefref) eq 'HASH') {
 7327:         %domdef = %{$domdefref};
 7328:     } else {
 7329:         %domdef = &get_domain_defaults($udom);
 7330:     }
 7331:     if (ref($domdef{$tool}) eq 'HASH') {
 7332:         if ($is_adv) {
 7333:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7334:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7335:                     $access = 1;
 7336:                 } else {
 7337:                     $access = 0;
 7338:                 }
 7339:                 return $access;
 7340:             }
 7341:         }
 7342:         if ($inststatus ne '') {
 7343:             my ($hasaccess,$hasnoaccess);
 7344:             foreach my $affiliation (split(/:/,$inststatus)) {
 7345:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7346:                     if ($domdef{$tool}{$affiliation}) {
 7347:                         $hasaccess = 1;
 7348:                     } else {
 7349:                         $hasnoaccess = 1;
 7350:                     }
 7351:                 }
 7352:             }
 7353:             if ($hasaccess || $hasnoaccess) {
 7354:                 if ($hasaccess) {
 7355:                     $access = 1;
 7356:                 } elsif ($hasnoaccess) {
 7357:                     $access = 0; 
 7358:                 }
 7359:                 return $access;
 7360:             }
 7361:         } else {
 7362:             if ($domdef{$tool}{'default'} ne '') {
 7363:                 if ($domdef{$tool}{'default'}) {
 7364:                     $access = 1;
 7365:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7366:                     $access = 0;
 7367:                 }
 7368:                 return $access;
 7369:             }
 7370:         }
 7371:     } else {
 7372:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7373:             $access = 1;
 7374:         } else {
 7375:             $access = 0;
 7376:         }
 7377:         return $access;
 7378:     }
 7379: }
 7380: 
 7381: sub is_course_owner {
 7382:     my ($cdom,$cnum,$udom,$uname) = @_;
 7383:     if (($udom eq '') || ($uname eq '')) {
 7384:         $udom = $env{'user.domain'};
 7385:         $uname = $env{'user.name'};
 7386:     }
 7387:     unless (($udom eq '') || ($uname eq '')) {
 7388:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7389:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7390:                 return 1;
 7391:             } else {
 7392:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7393:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7394:                     return 1;
 7395:                 }
 7396:             }
 7397:         }
 7398:     }
 7399:     return;
 7400: }
 7401: 
 7402: sub is_advanced_user {
 7403:     my ($udom,$uname) = @_;
 7404:     if ($udom ne '' && $uname ne '') {
 7405:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7406:             if (wantarray) {
 7407:                 return ($env{'user.adv'},$env{'user.author'});
 7408:             } else {
 7409:                 return $env{'user.adv'};
 7410:             }
 7411:         }
 7412:     }
 7413:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7414:     my %allroles;
 7415:     my ($is_adv,$is_author);
 7416:     foreach my $role (keys(%roleshash)) {
 7417:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7418:         my $area = '/'.$tdomain.'/'.$trest;
 7419:         if ($sec ne '') {
 7420:             $area .= '/'.$sec;
 7421:         }
 7422:         if (($area ne '') && ($trole ne '')) {
 7423:             my $spec=$trole.'.'.$area;
 7424:             if ($trole =~ /^cr\//) {
 7425:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7426:             } elsif ($trole ne 'gr') {
 7427:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7428:             }
 7429:             if ($trole eq 'au') {
 7430:                 $is_author = 1;
 7431:             }
 7432:         }
 7433:     }
 7434:     foreach my $role (keys(%allroles)) {
 7435:         last if ($is_adv);
 7436:         foreach my $item (split(/:/,$allroles{$role})) {
 7437:             if ($item ne '') {
 7438:                 my ($privilege,$restrictions)=split(/&/,$item);
 7439:                 if ($privilege eq 'adv') {
 7440:                     $is_adv = 1;
 7441:                     last;
 7442:                 }
 7443:             }
 7444:         }
 7445:     }
 7446:     if (wantarray) {
 7447:         return ($is_adv,$is_author);
 7448:     }
 7449:     return $is_adv;
 7450: }
 7451: 
 7452: sub check_can_request {
 7453:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7454:     my $canreq = 0;
 7455:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7456:         $uname = $env{'user.name'};
 7457:         $udom = $env{'user.domain'};
 7458:     }
 7459:     my ($types,$typename) = &Apache::loncommon::course_types();
 7460:     my @options = ('approval','validate','autolimit');
 7461:     my $optregex = join('|',@options);
 7462:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7463:         foreach my $type (@{$types}) {
 7464:             if (&usertools_access($uname,$udom,$type,undef,
 7465:                                   'requestcourses')) {
 7466:                 $canreq ++;
 7467:                 if (ref($request_domains) eq 'HASH') {
 7468:                     push(@{$request_domains->{$type}},$udom);
 7469:                 }
 7470:                 if ($dom eq $udom) {
 7471:                     $can_request->{$type} = 1;
 7472:                 }
 7473:             }
 7474:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7475:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7476:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7477:                 if (@curr > 0) {
 7478:                     foreach my $item (@curr) {
 7479:                         if (ref($request_domains) eq 'HASH') {
 7480:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7481:                             if ($otherdom ne '') {
 7482:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7483:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7484:                                         push(@{$request_domains->{$type}},$otherdom);
 7485:                                     }
 7486:                                 } else {
 7487:                                     push(@{$request_domains->{$type}},$otherdom);
 7488:                                 }
 7489:                             }
 7490:                         }
 7491:                     }
 7492:                     unless ($dom eq $env{'user.domain'}) {
 7493:                         $canreq ++;
 7494:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7495:                             $can_request->{$type} = 1;
 7496:                         }
 7497:                     }
 7498:                 }
 7499:             }
 7500:         }
 7501:     }
 7502:     return $canreq;
 7503: }
 7504: 
 7505: # ---------------------------------------------- Custom access rule evaluation
 7506: 
 7507: sub customaccess {
 7508:     my ($priv,$uri)=@_;
 7509:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7510:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7511:     $udom = &LONCAPA::clean_domain($udom);
 7512:     $ucrs = &LONCAPA::clean_username($ucrs);
 7513:     my $access=0;
 7514:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7515: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7516: 	if ($type eq 'user') {
 7517: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7518: 		my ($tdom,$tuname)=split(m{/},$scope);
 7519: 		if ($tdom) {
 7520: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7521: 		}
 7522: 		if ($tuname) {
 7523: 		    if ($tuname ne $env{'user.name'}) { next; }
 7524: 		}
 7525: 		$access=($effect eq 'allow');
 7526: 		last;
 7527: 	    }
 7528: 	} else {
 7529: 	    if ($role) {
 7530: 		if ($role ne $urole) { next; }
 7531: 	    }
 7532: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7533: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7534: 		if ($tdom) {
 7535: 		    if ($tdom ne $udom) { next; }
 7536: 		}
 7537: 		if ($tcrs) {
 7538: 		    if ($tcrs ne $ucrs) { next; }
 7539: 		}
 7540: 		if ($tsec) {
 7541: 		    if ($tsec ne $usec) { next; }
 7542: 		}
 7543: 		$access=($effect eq 'allow');
 7544: 		last;
 7545: 	    }
 7546: 	    if ($realm eq '' && $role eq '') {
 7547: 		$access=($effect eq 'allow');
 7548: 	    }
 7549: 	}
 7550:     }
 7551:     return $access;
 7552: }
 7553: 
 7554: # ------------------------------------------------- Check for a user privilege
 7555: 
 7556: sub allowed {
 7557:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7558:     my $ver_orguri=$uri;
 7559:     $uri=&deversion($uri);
 7560:     my $orguri=$uri;
 7561:     $uri=&declutter($uri);
 7562: 
 7563:     if ($priv eq 'evb') {
 7564: # Evade communication block restrictions for specified role in a course
 7565:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7566:             return $1;
 7567:         } else {
 7568:             return;
 7569:         }
 7570:     }
 7571: 
 7572:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7573: # Free bre access to adm and meta resources
 7574:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7575: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7576: 	&& ($priv eq 'bre')) {
 7577: 	return 'F';
 7578:     }
 7579: 
 7580: # Free bre access to user's own portfolio contents
 7581:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7582:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7583: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7584:         my %setters;
 7585:         my ($startblock,$endblock) = 
 7586:             &Apache::loncommon::blockcheck(\%setters,'port');
 7587:         if ($startblock && $endblock) {
 7588:             return 'B';
 7589:         } else {
 7590:             return 'F';
 7591:         }
 7592:     }
 7593: 
 7594: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7595:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7596:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7597:         if (exists($env{'request.course.id'})) {
 7598:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7599:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7600:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7601:                 my $courseprivid=$env{'request.course.id'};
 7602:                 $courseprivid=~s/\_/\//;
 7603:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7604:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7605:                     return $1; 
 7606:                 } else {
 7607:                     if ($env{'request.course.sec'}) {
 7608:                         $courseprivid.='/'.$env{'request.course.sec'};
 7609:                     }
 7610:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7611:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7612:                         return $2;
 7613:                     }
 7614:                 }
 7615:             }
 7616:         }
 7617:     }
 7618: 
 7619: # Free bre to public access
 7620: 
 7621:     if ($priv eq 'bre') {
 7622:         my $copyright;
 7623:         unless ($uri =~ /ext\.tool/) {
 7624:             $copyright=&metadata($uri,'copyright');
 7625:         }
 7626: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7627:            return 'F'; 
 7628:         }
 7629:         if ($copyright eq 'priv') {
 7630:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7631: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7632: 		return '';
 7633:             }
 7634:         }
 7635:         if ($copyright eq 'domain') {
 7636:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7637: 	    unless (($env{'user.domain'} eq $1) ||
 7638:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7639: 		return '';
 7640:             }
 7641:         }
 7642:         if ($env{'request.role'}=~ /li\.\//) {
 7643:             # Library role, so allow browsing of resources in this domain.
 7644:             return 'F';
 7645:         }
 7646:         if ($copyright eq 'custom') {
 7647: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7648:         }
 7649:     }
 7650:     # Domain coordinator is trying to create a course
 7651:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7652:         # uri is the requested domain in this case.
 7653:         # comparison to 'request.role.domain' shows if the user has selected
 7654:         # a role of dc for the domain in question.
 7655:         return 'F' if ($uri eq $env{'request.role.domain'});
 7656:     }
 7657: 
 7658:     my $thisallowed='';
 7659:     my $statecond=0;
 7660:     my $courseprivid='';
 7661: 
 7662:     my $ownaccess;
 7663:     # Community Coordinator or Assistant Co-author browsing resource space.
 7664:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7665:         if ($uri eq '') {
 7666:             $ownaccess = 1;
 7667:         } else {
 7668:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7669:                 my $udom = $env{'user.domain'};
 7670:                 my $uname = $env{'user.name'};
 7671:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7672:                     $ownaccess = 1;
 7673:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7674:                     unless ($uri =~ m{\.\./}) {
 7675:                         $ownaccess = 1;
 7676:                     }
 7677:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7678:                     my $now = time;
 7679:                     if ($uri =~ m{^([^/]+)/?$}) {
 7680:                         my $adom = $1;
 7681:                         foreach my $key (keys(%env)) {
 7682:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7683:                                 my ($start,$end) = split('.',$env{$key});
 7684:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7685:                                     $ownaccess = 1;
 7686:                                     last;
 7687:                                 }
 7688:                             }
 7689:                         }
 7690:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7691:                         my $adom = $1;
 7692:                         my $aname = $2;
 7693:                         foreach my $role ('ca','aa') { 
 7694:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7695:                                 my ($start,$end) =
 7696:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7697:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7698:                                     $ownaccess = 1;
 7699:                                     last;
 7700:                                 }
 7701:                             }
 7702:                         }
 7703:                     }
 7704:                 }
 7705:             }
 7706:         }
 7707:     }
 7708: 
 7709: # Course
 7710: 
 7711:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7712:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7713:             $thisallowed.=$1;
 7714:         }
 7715:     }
 7716: 
 7717: # Domain
 7718: 
 7719:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7720:        =~/\Q$priv\E\&([^\:]*)/) {
 7721:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7722:             $thisallowed.=$1;
 7723:         }
 7724:     }
 7725: 
 7726: # User who is not author or co-author might still be able to edit
 7727: # resource of an author in the domain (e.g., if Domain Coordinator).
 7728:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7729:         (&allowed('mdc',$env{'request.course.id'}))) {
 7730:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7731:             $thisallowed.=$1;
 7732:         }
 7733:     }
 7734: 
 7735: # Course: uri itself is a course
 7736:     my $courseuri=$uri;
 7737:     $courseuri=~s/\_(\d)/\/$1/;
 7738:     $courseuri=~s/^([^\/])/\/$1/;
 7739: 
 7740:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7741:        =~/\Q$priv\E\&([^\:]*)/) {
 7742:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7743:             $thisallowed.=$1;
 7744:         }
 7745:     }
 7746: 
 7747: # URI is an uploaded document for this course, default permissions don't matter
 7748: # not allowing 'edit' access (editupload) to uploaded course docs
 7749:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7750: 	$thisallowed='';
 7751:         my ($match)=&is_on_map($uri);
 7752:         if ($match) {
 7753:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7754:                   =~/\Q$priv\E\&([^\:]*)/) {
 7755:                 my $value = $1;
 7756:                 if ($noblockcheck) {
 7757:                     $thisallowed.=$value;
 7758:                 } else {
 7759:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7760:                     if (@blockers > 0) {
 7761:                         $thisallowed = 'B';
 7762:                     } else {
 7763:                         $thisallowed.=$value;
 7764:                     }
 7765:                 }
 7766:             }
 7767:         } else {
 7768:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7769:             if ($refuri) {
 7770:                 if ($refuri =~ m|^/adm/|) {
 7771:                     $thisallowed='F';
 7772:                 } else {
 7773:                     $refuri=&declutter($refuri);
 7774:                     my ($match) = &is_on_map($refuri);
 7775:                     if ($match) {
 7776:                         if ($noblockcheck) {
 7777:                             $thisallowed='F';
 7778:                         } else {
 7779:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7780:                             if (@blockers > 0) {
 7781:                                 $thisallowed = 'B';
 7782:                             } else {
 7783:                                 $thisallowed='F';
 7784:                             }
 7785:                         }
 7786:                     }
 7787:                 }
 7788:             }
 7789:         }
 7790:     }
 7791: 
 7792:     if ($priv eq 'bre'
 7793: 	&& $thisallowed ne 'F' 
 7794: 	&& $thisallowed ne '2'
 7795: 	&& &is_portfolio_url($uri)) {
 7796: 	$thisallowed = &portfolio_access($uri,$clientip);
 7797:     }
 7798: 
 7799: # Full access at system, domain or course-wide level? Exit.
 7800:     if ($thisallowed=~/F/) {
 7801: 	return 'F';
 7802:     }
 7803: 
 7804: # If this is generating or modifying users, exit with special codes
 7805: 
 7806:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7807: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7808: 	    my ($audom,$auname)=split('/',$uri);
 7809: # no author name given, so this just checks on the general right to make a co-author in this domain
 7810: 	    unless ($auname) { return $thisallowed; }
 7811: # an author name is given, so we are about to actually make a co-author for a certain account
 7812: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7813: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7814: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7815: 	}
 7816: 	return $thisallowed;
 7817:     }
 7818: #
 7819: # Gathered so far: system, domain and course wide privileges
 7820: #
 7821: # Course: See if uri or referer is an individual resource that is part of 
 7822: # the course
 7823: 
 7824:     if ($env{'request.course.id'}) {
 7825: 
 7826:        $courseprivid=$env{'request.course.id'};
 7827:        if ($env{'request.course.sec'}) {
 7828:           $courseprivid.='/'.$env{'request.course.sec'};
 7829:        }
 7830:        $courseprivid=~s/\_/\//;
 7831:        my $checkreferer=1;
 7832:        my ($match,$cond)=&is_on_map($uri);
 7833:        if ($match) {
 7834:            $statecond=$cond;
 7835:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7836:                =~/\Q$priv\E\&([^\:]*)/) {
 7837:                my $value = $1;
 7838:                if ($priv eq 'bre') {
 7839:                    if ($noblockcheck) {
 7840:                        $thisallowed.=$value;
 7841:                    } else {
 7842:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7843:                        if (@blockers > 0) {
 7844:                            $thisallowed = 'B';
 7845:                        } else {
 7846:                            $thisallowed.=$value;
 7847:                        }
 7848:                    }
 7849:                } else {
 7850:                    $thisallowed.=$value;
 7851:                }
 7852:                $checkreferer=0;
 7853:            }
 7854:        }
 7855:        
 7856:        if ($checkreferer) {
 7857: 	  my $refuri=$env{'httpref.'.$orguri};
 7858:             unless ($refuri) {
 7859:                 foreach my $key (keys(%env)) {
 7860: 		    if ($key=~/^httpref\..*\*/) {
 7861: 			my $pattern=$key;
 7862:                         $pattern=~s/^httpref\.\/res\///;
 7863:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7864:                         $pattern=~s/\//\\\//g;
 7865:                         if ($orguri=~/$pattern/) {
 7866: 			    $refuri=$env{$key};
 7867:                         }
 7868:                     }
 7869:                 }
 7870:             }
 7871: 
 7872:          if ($refuri) { 
 7873: 	  $refuri=&declutter($refuri);
 7874:           my ($match,$cond)=&is_on_map($refuri);
 7875:             if ($match) {
 7876:               my $refstatecond=$cond;
 7877:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7878:                   =~/\Q$priv\E\&([^\:]*)/) {
 7879:                   my $value = $1;
 7880:                   if ($priv eq 'bre') {
 7881:                       if ($noblockcheck) {
 7882:                           $thisallowed.=$value;
 7883:                       } else {
 7884:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7885:                           if (@blockers > 0) {
 7886:                               $thisallowed = 'B';
 7887:                           } else {
 7888:                               $thisallowed.=$value;
 7889:                           }
 7890:                       }
 7891:                   } else {
 7892:                       $thisallowed.=$value;
 7893:                   }
 7894:                   $uri=$refuri;
 7895:                   $statecond=$refstatecond;
 7896:               }
 7897:           }
 7898:         }
 7899:        }
 7900:    }
 7901: 
 7902: #
 7903: # Gathered now: all privileges that could apply, and condition number
 7904: # 
 7905: #
 7906: # Full or no access?
 7907: #
 7908: 
 7909:     if ($thisallowed=~/F/) {
 7910: 	return 'F';
 7911:     }
 7912: 
 7913:     unless ($thisallowed) {
 7914:         return '';
 7915:     }
 7916: 
 7917: # Restrictions exist, deal with them
 7918: #
 7919: #   C:according to course preferences
 7920: #   R:according to resource settings
 7921: #   L:unless locked
 7922: #   X:according to user session state
 7923: #
 7924: 
 7925: # Possibly locked functionality, check all courses
 7926: # Locks might take effect only after 10 minutes cache expiration for other
 7927: # courses, and 2 minutes for current course
 7928: 
 7929:     my $envkey;
 7930:     if ($thisallowed=~/L/) {
 7931:         foreach $envkey (keys(%env)) {
 7932:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7933:                my $courseid=$2;
 7934:                my $roleid=$1.'.'.$2;
 7935:                $courseid=~s/^\///;
 7936:                my $expiretime=600;
 7937:                if ($env{'request.role'} eq $roleid) {
 7938: 		  $expiretime=120;
 7939:                }
 7940: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7941:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7942:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7943: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7944:                }
 7945:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7946:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7947: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7948:                        &log($env{'user.domain'},$env{'user.name'},
 7949:                             $env{'user.home'},
 7950:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7951:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7952:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7953: 		       return '';
 7954:                    }
 7955:                }
 7956:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7957:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7958: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7959:                        &log($env{'user.domain'},$env{'user.name'},
 7960:                             $env{'user.home'},
 7961:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7962:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7963:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7964: 		       return '';
 7965:                    }
 7966:                }
 7967: 	   }
 7968:        }
 7969:     }
 7970:    
 7971: #
 7972: # Rest of the restrictions depend on selected course
 7973: #
 7974: 
 7975:     unless ($env{'request.course.id'}) {
 7976: 	if ($thisallowed eq 'A') {
 7977: 	    return 'A';
 7978:         } elsif ($thisallowed eq 'B') {
 7979:             return 'B';
 7980: 	} else {
 7981: 	    return '1';
 7982: 	}
 7983:     }
 7984: 
 7985: #
 7986: # Now user is definitely in a course
 7987: #
 7988: 
 7989: 
 7990: # Course preferences
 7991: 
 7992:    if ($thisallowed=~/C/) {
 7993:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7994:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7995:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7996: 	   =~/\Q$rolecode\E/) {
 7997: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7998: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7999: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8000: 			$env{'request.course.id'});
 8001: 	   }
 8002:            return '';
 8003:        }
 8004: 
 8005:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8006: 	   =~/\Q$unamedom\E/) {
 8007: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8008: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8009: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8010: 			$env{'request.course.id'});
 8011: 	   }
 8012:            return '';
 8013:        }
 8014:    }
 8015: 
 8016: # Resource preferences
 8017: 
 8018:    if ($thisallowed=~/R/) {
 8019:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8020:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8021: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8022: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8023: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8024: 	   }
 8025: 	   return '';
 8026:        }
 8027:    }
 8028: 
 8029: # Restricted by state or randomout?
 8030: 
 8031:    if ($thisallowed=~/X/) {
 8032:       if ($env{'acc.randomout'}) {
 8033: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8034:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8035:             return ''; 
 8036:          }
 8037:       }
 8038:       if (&condval($statecond)) {
 8039: 	 return '2';
 8040:       } else {
 8041:          return '';
 8042:       }
 8043:    }
 8044: 
 8045:     if ($thisallowed eq 'A') {
 8046: 	return 'A';
 8047:     } elsif ($thisallowed eq 'B') {
 8048:         return 'B';
 8049:     }
 8050:    return 'F';
 8051: }
 8052: 
 8053: # ------------------------------------------- Check construction space access
 8054: 
 8055: sub constructaccess {
 8056:     my ($url,$setpriv)=@_;
 8057: 
 8058: # We do not allow editing of previous versions of files
 8059:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8060: 
 8061: # Get username and domain from URL
 8062:     my ($ownername,$ownerdomain,$ownerhome);
 8063: 
 8064:     ($ownerdomain,$ownername) =
 8065:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8066: 
 8067: # The URL does not really point to any authorspace, forget it
 8068:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8069: 
 8070: # Now we need to see if the user has access to the authorspace of
 8071: # $ownername at $ownerdomain
 8072: 
 8073:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8074: # Real author for this?
 8075:        $ownerhome = $env{'user.home'};
 8076:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8077:           return ($ownername,$ownerdomain,$ownerhome);
 8078:        }
 8079:     } else {
 8080: # Co-author for this?
 8081:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8082:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8083:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8084:             return ($ownername,$ownerdomain,$ownerhome);
 8085:         }
 8086:         if ($env{'request.course.id'}) {
 8087:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8088:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8089:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8090:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8091:                     return ($ownername,$ownerdomain,$ownerhome);
 8092:                 }
 8093:             }
 8094:         }
 8095:     }
 8096: 
 8097: # We don't have any access right now. If we are not possibly going to do anything about this,
 8098: # we might as well leave
 8099:    unless ($setpriv) { return ''; }
 8100: 
 8101: # Backdoor access?
 8102:     my $allowed=&allowed('eco',$ownerdomain);
 8103: # Nope
 8104:     unless ($allowed) { return ''; }
 8105: # Looks like we may have access, but could be locked by the owner of the construction space
 8106:     if ($allowed eq 'U') {
 8107:         my %blocked=&get('environment',['domcoord.author'],
 8108:                          $ownerdomain,$ownername);
 8109: # Is blocked by owner
 8110:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8111:     }
 8112:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8113: # Grant temporary access
 8114:         my $then=$env{'user.login.time'};
 8115:         my $update=$env{'user.update.time'};
 8116:         if (!$update) { $update = $then; }
 8117:         my $refresh=$env{'user.refresh.time'};
 8118:         if (!$refresh) { $refresh = $update; }
 8119:         my $now = time;
 8120:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8121:                            $now,'ca','constructaccess');
 8122:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8123:         return($ownername,$ownerdomain,$ownerhome);
 8124:     }
 8125: # No business here
 8126:     return '';
 8127: }
 8128: 
 8129: # ----------------------------------------------------------- Content Blocking
 8130: 
 8131: {
 8132: # Caches for faster Course Contents display where content blocking
 8133: # is in operation (i.e., interval param set) for timed quiz.
 8134: #
 8135: # User for whom data are being temporarily cached.
 8136: my $cacheduser='';
 8137: # Cached blockers for this user (a hash of blocking items). 
 8138: my %cachedblockers=();
 8139: # When the data were last cached.
 8140: my $cachedlast='';
 8141: 
 8142: sub load_all_blockers {
 8143:     my ($uname,$udom,$blocks)=@_;
 8144:     if (($uname ne '') && ($udom ne '')) { 
 8145:         if (($cacheduser eq $uname.':'.$udom) &&
 8146:             (abs($cachedlast-time)<5)) {
 8147:             return;
 8148:         }
 8149:     }
 8150:     $cachedlast=time;
 8151:     $cacheduser=$uname.':'.$udom;
 8152:     %cachedblockers = &get_commblock_resources($blocks);
 8153: }
 8154: 
 8155: sub get_comm_blocks {
 8156:     my ($cdom,$cnum) = @_;
 8157:     if ($cdom eq '' || $cnum eq '') {
 8158:         return unless ($env{'request.course.id'});
 8159:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8160:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8161:     }
 8162:     my %commblocks;
 8163:     my $hashid=$cdom.'_'.$cnum;
 8164:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8165:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8166:         %commblocks = %{$blocksref};
 8167:     } else {
 8168:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8169:         my $cachetime = 600;
 8170:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8171:     }
 8172:     return %commblocks;
 8173: }
 8174: 
 8175: sub get_commblock_resources {
 8176:     my ($blocks) = @_;
 8177:     my %blockers = ();
 8178:     return %blockers unless ($env{'request.course.id'});
 8179:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8180:     my %commblocks;
 8181:     if (ref($blocks) eq 'HASH') {
 8182:         %commblocks = %{$blocks};
 8183:     } else {
 8184:         %commblocks = &get_comm_blocks();
 8185:     }
 8186:     return %blockers unless (keys(%commblocks) > 0); 
 8187:     my $navmap = Apache::lonnavmaps::navmap->new();
 8188:     return %blockers unless (ref($navmap));
 8189:     my $now = time;
 8190:     foreach my $block (keys(%commblocks)) {
 8191:         if ($block =~ /^(\d+)____(\d+)$/) {
 8192:             my ($start,$end) = ($1,$2);
 8193:             if ($start <= $now && $end >= $now) {
 8194:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8195:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8196:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8197:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8198:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8199:                             }
 8200:                         }
 8201:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8202:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8203:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8204:                             }
 8205:                         }
 8206:                     }
 8207:                 }
 8208:             }
 8209:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8210:             my $item = $1;
 8211:             my @to_test;
 8212:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8213:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8214:                     my @interval;
 8215:                     my $type = 'map';
 8216:                     if ($item eq 'course') {
 8217:                         $type = 'course';
 8218:                         @interval=&EXT("resource.0.interval");
 8219:                     } else {
 8220:                         if ($item =~ /___\d+___/) {
 8221:                             $type = 'resource';
 8222:                             @interval=&EXT("resource.0.interval",$item);
 8223:                             if (ref($navmap)) {                        
 8224:                                 my $res = $navmap->getBySymb($item); 
 8225:                                 push(@to_test,$res);
 8226:                             }
 8227:                         } else {
 8228:                             my $mapsymb = &symbread($item,1);
 8229:                             if ($mapsymb) {
 8230:                                 if (ref($navmap)) {
 8231:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8232:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8233:                                     foreach my $res (@to_test) {
 8234:                                         my $symb = $res->symb();
 8235:                                         next if ($symb eq $mapsymb);
 8236:                                         if ($symb ne '') {
 8237:                                             @interval=&EXT("resource.0.interval",$symb);
 8238:                                             if ($interval[1] eq 'map') {
 8239:                                                 last;
 8240:                                             }
 8241:                                         }
 8242:                                     }
 8243:                                 }
 8244:                             }
 8245:                         }
 8246:                     }
 8247:                     if ($interval[0] =~ /^(\d+)/) {
 8248:                         my $timelimit = $1; 
 8249:                         my $first_access;
 8250:                         if ($type eq 'resource') {
 8251:                             $first_access=&get_first_access($interval[1],$item);
 8252:                         } elsif ($type eq 'map') {
 8253:                             $first_access=&get_first_access($interval[1],undef,$item);
 8254:                         } else {
 8255:                             $first_access=&get_first_access($interval[1]);
 8256:                         }
 8257:                         if ($first_access) {
 8258:                             my $timesup = $first_access+$timelimit;
 8259:                             if ($timesup > $now) {
 8260:                                 my $activeblock;
 8261:                                 foreach my $res (@to_test) {
 8262:                                     if ($res->answerable()) {
 8263:                                         $activeblock = 1;
 8264:                                         last;
 8265:                                     }
 8266:                                 }
 8267:                                 if ($activeblock) {
 8268:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8269:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8270:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8271:                                          }
 8272:                                     }
 8273:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8274:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8275:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8276:                                         }
 8277:                                     }
 8278:                                 }
 8279:                             }
 8280:                         }
 8281:                     }
 8282:                 }
 8283:             }
 8284:         }
 8285:     }
 8286:     return %blockers;
 8287: }
 8288: 
 8289: sub has_comm_blocking {
 8290:     my ($priv,$symb,$uri,$blocks) = @_;
 8291:     my @blockers;
 8292:     return unless ($env{'request.course.id'});
 8293:     return unless ($priv eq 'bre');
 8294:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8295:     return if ($env{'request.state'} eq 'construct');
 8296:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8297:     return unless (keys(%cachedblockers) > 0);
 8298:     my (%possibles,@symbs);
 8299:     if (!$symb) {
 8300:         $symb = &symbread($uri,1,1,1,\%possibles);
 8301:     }
 8302:     if ($symb) {
 8303:         @symbs = ($symb);
 8304:     } elsif (keys(%possibles)) { 
 8305:         @symbs = keys(%possibles);
 8306:     }
 8307:     my $noblock;
 8308:     foreach my $symb (@symbs) {
 8309:         last if ($noblock);
 8310:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8311:         foreach my $block (keys(%cachedblockers)) {
 8312:             if ($block =~ /^firstaccess____(.+)$/) {
 8313:                 my $item = $1;
 8314:                 if (($item eq $map) || ($item eq $symb)) {
 8315:                     $noblock = 1;
 8316:                     last;
 8317:                 }
 8318:             }
 8319:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8320:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8321:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8322:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8323:                             push(@blockers,$block);
 8324:                         }
 8325:                     }
 8326:                 }
 8327:             }
 8328:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8329:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8330:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8331:                         push(@blockers,$block);
 8332:                     }
 8333:                 }
 8334:             }
 8335:         }
 8336:     }
 8337:     return if ($noblock);
 8338:     return @blockers;
 8339: }
 8340: }
 8341: 
 8342: # -------------------------------- Deversion and split uri into path an filename   
 8343: 
 8344: #
 8345: #   Removes the version from a URI and
 8346: #   splits it in to its filename and path to the filename.
 8347: #   Seems like File::Basename could have done this more clearly.
 8348: #   Parameters:
 8349: #      $uri   - input URI
 8350: #   Returns:
 8351: #     Two element list consisting of 
 8352: #     $pathname  - the URI up to and excluding the trailing /
 8353: #     $filename  - The part of the URI following the last /
 8354: #  NOTE:
 8355: #    Another realization of this is simply:
 8356: #    use File::Basename;
 8357: #    ...
 8358: #    $uri = shift;
 8359: #    $filename = basename($uri);
 8360: #    $path     = dirname($uri);
 8361: #    return ($filename, $path);
 8362: #
 8363: #     The implementation below is probably faster however.
 8364: #
 8365: sub split_uri_for_cond {
 8366:     my $uri=&deversion(&declutter(shift));
 8367:     my @uriparts=split(/\//,$uri);
 8368:     my $filename=pop(@uriparts);
 8369:     my $pathname=join('/',@uriparts);
 8370:     return ($pathname,$filename);
 8371: }
 8372: # --------------------------------------------------- Is a resource on the map?
 8373: 
 8374: sub is_on_map {
 8375:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8376:     #Trying to find the conditional for the file
 8377:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8378: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8379:     if ($match) {
 8380: 	return (1,$1);
 8381:     } else {
 8382: 	return (0,0);
 8383:     }
 8384: }
 8385: 
 8386: # --------------------------------------------------------- Get symb from alias
 8387: 
 8388: sub get_symb_from_alias {
 8389:     my $symb=shift;
 8390:     my ($map,$resid,$url)=&decode_symb($symb);
 8391: # Already is a symb
 8392:     if ($url) { return $symb; }
 8393: # Must be an alias
 8394:     my $aliassymb='';
 8395:     my %bighash;
 8396:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8397:                             &GDBM_READER(),0640)) {
 8398:         my $rid=$bighash{'mapalias_'.$symb};
 8399: 	if ($rid) {
 8400: 	    my ($mapid,$resid)=split(/\./,$rid);
 8401: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8402: 				    $resid,$bighash{'src_'.$rid});
 8403: 	}
 8404:         untie %bighash;
 8405:     }
 8406:     return $aliassymb;
 8407: }
 8408: 
 8409: # ----------------------------------------------------------------- Define Role
 8410: 
 8411: sub definerole {
 8412:   if (allowed('mcr','/')) {
 8413:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8414:     foreach my $role (split(':',$sysrole)) {
 8415: 	my ($crole,$cqual)=split(/\&/,$role);
 8416:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8417:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8418: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8419:                return "refused:s:$crole&$cqual"; 
 8420:             }
 8421:         }
 8422:     }
 8423:     foreach my $role (split(':',$domrole)) {
 8424: 	my ($crole,$cqual)=split(/\&/,$role);
 8425:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8426:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8427: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8428:                return "refused:d:$crole&$cqual"; 
 8429:             }
 8430:         }
 8431:     }
 8432:     foreach my $role (split(':',$courole)) {
 8433: 	my ($crole,$cqual)=split(/\&/,$role);
 8434:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8435:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8436: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8437:                return "refused:c:$crole&$cqual"; 
 8438:             }
 8439:         }
 8440:     }
 8441:     my $uhome;
 8442:     if (($uname ne '') && ($udom ne '')) {
 8443:         $uhome = &homeserver($uname,$udom);
 8444:         return $uhome if ($uhome eq 'no_host');
 8445:     } else {
 8446:         $uname = $env{'user.name'};
 8447:         $udom = $env{'user.domain'};
 8448:         $uhome = $env{'user.home'};
 8449:     }
 8450:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8451:                 "$udom:$uname:rolesdef_$rolename=".
 8452:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8453:     return reply($command,$uhome);
 8454:   } else {
 8455:     return 'refused';
 8456:   }
 8457: }
 8458: 
 8459: # ---------------- Make a metadata query against the network of library servers
 8460: 
 8461: sub metadata_query {
 8462:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8463:     my %rhash;
 8464:     my %libserv = &all_library();
 8465:     my @server_list = (defined($server_array) ? @$server_array
 8466:                                               : keys(%libserv) );
 8467:     for my $server (@server_list) {
 8468:         my $domains = ''; 
 8469:         if (ref($domains_hash) eq 'HASH') {
 8470:             $domains = $domains_hash->{$server}; 
 8471:         }
 8472: 	unless ($custom or $customshow) {
 8473: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8474: 	    $rhash{$server}=$reply;
 8475: 	}
 8476: 	else {
 8477: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8478: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8479: 			     $server);
 8480: 	    $rhash{$server}=$reply;
 8481: 	}
 8482:     }
 8483:     return \%rhash;
 8484: }
 8485: 
 8486: # ----------------------------------------- Send log queries and wait for reply
 8487: 
 8488: sub log_query {
 8489:     my ($uname,$udom,$query,%filters)=@_;
 8490:     my $uhome=&homeserver($uname,$udom);
 8491:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8492:     my $uhost=&hostname($uhome);
 8493:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8494:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8495:                        $uhome);
 8496:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8497:     return get_query_reply($queryid);
 8498: }
 8499: 
 8500: # -------------------------- Update MySQL table for portfolio file
 8501: 
 8502: sub update_portfolio_table {
 8503:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8504:     if ($group ne '') {
 8505:         $file_name =~s /^\Q$group\E//;
 8506:     }
 8507:     my $homeserver = &homeserver($uname,$udom);
 8508:     my $queryid=
 8509:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8510:                ':'.&escape($file_name).':'.$action,$homeserver);
 8511:     my $reply = &get_query_reply($queryid);
 8512:     return $reply;
 8513: }
 8514: 
 8515: # -------------------------- Update MySQL allusers table
 8516: 
 8517: sub update_allusers_table {
 8518:     my ($uname,$udom,$names) = @_;
 8519:     my $homeserver = &homeserver($uname,$udom);
 8520:     my $queryid=
 8521:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8522:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8523:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8524:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8525:                'generation='.&escape($names->{'generation'}).'%%'.
 8526:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8527:                'id='.&escape($names->{'id'}),$homeserver);
 8528:     return;
 8529: }
 8530: 
 8531: # ------- Request retrieval of institutional classlists for course(s)
 8532: 
 8533: sub fetch_enrollment_query {
 8534:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8535:     my ($homeserver,$sleep,$loopmax);
 8536:     my $maxtries = 1;
 8537:     if ($context eq 'automated') {
 8538:         $homeserver = $perlvar{'lonHostID'};
 8539:         $sleep = 2;
 8540:         $loopmax = 100;
 8541:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8542:     } else {
 8543:         $homeserver = &homeserver($cnum,$dom);
 8544:     }
 8545:     my $host=&hostname($homeserver);
 8546:     my $cmd = '';
 8547:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8548:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8549:     }
 8550:     $cmd =~ s/%%$//;
 8551:     $cmd = &escape($cmd);
 8552:     my $query = 'fetchenrollment';
 8553:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8554:     unless ($queryid=~/^\Q$host\E\_/) { 
 8555:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8556:         return 'error: '.$queryid;
 8557:     }
 8558:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8559:     my $tries = 1;
 8560:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8561:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8562:         $tries ++;
 8563:     }
 8564:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8565:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8566:     } else {
 8567:         my @responses = split(/:/,$reply);
 8568:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8569:             foreach my $line (@responses) {
 8570:                 my ($key,$value) = split(/=/,$line,2);
 8571:                 $$replyref{$key} = $value;
 8572:             }
 8573:         } else {
 8574:             my $pathname = LONCAPA::tempdir();
 8575:             foreach my $line (@responses) {
 8576:                 my ($key,$value) = split(/=/,$line);
 8577:                 $$replyref{$key} = $value;
 8578:                 if ($value > 0) {
 8579:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8580:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8581:                         my $destname = $pathname.'/'.$filename;
 8582:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8583:                         if ($xml_classlist =~ /^error/) {
 8584:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8585:                         } else {
 8586:                             if ( open(FILE,">",$destname) ) {
 8587:                                 print FILE &unescape($xml_classlist);
 8588:                                 close(FILE);
 8589:                             } else {
 8590:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8591:                             }
 8592:                         }
 8593:                     }
 8594:                 }
 8595:             }
 8596:         }
 8597:         return 'ok';
 8598:     }
 8599:     return 'error';
 8600: }
 8601: 
 8602: sub get_query_reply {
 8603:     my ($queryid,$sleep,$loopmax) = @_;;
 8604:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8605:         $sleep = 0.2;
 8606:     }
 8607:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8608:         $loopmax = 100;
 8609:     }
 8610:     my $replyfile=LONCAPA::tempdir().$queryid;
 8611:     my $reply='';
 8612:     for (1..$loopmax) {
 8613: 	sleep($sleep);
 8614:         if (-e $replyfile.'.end') {
 8615: 	    if (open(my $fh,"<",$replyfile)) {
 8616: 		$reply = join('',<$fh>);
 8617: 		close($fh);
 8618: 	   } else { return 'error: reply_file_error'; }
 8619:            return &unescape($reply);
 8620: 	}
 8621:     }
 8622:     return 'timeout:'.$queryid;
 8623: }
 8624: 
 8625: sub courselog_query {
 8626: #
 8627: # possible filters:
 8628: # url: url or symb
 8629: # username
 8630: # domain
 8631: # action: view, submit, grade
 8632: # start: timestamp
 8633: # end: timestamp
 8634: #
 8635:     my (%filters)=@_;
 8636:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8637:     if ($filters{'url'}) {
 8638: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8639:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8640:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8641:     }
 8642:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8643:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8644:     return &log_query($cname,$cdom,'courselog',%filters);
 8645: }
 8646: 
 8647: sub userlog_query {
 8648: #
 8649: # possible filters:
 8650: # action: log check role
 8651: # start: timestamp
 8652: # end: timestamp
 8653: #
 8654:     my ($uname,$udom,%filters)=@_;
 8655:     return &log_query($uname,$udom,'userlog',%filters);
 8656: }
 8657: 
 8658: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8659: 
 8660: sub auto_run {
 8661:     my ($cnum,$cdom) = @_;
 8662:     my $response = 0;
 8663:     my $settings;
 8664:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8665:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8666:         $settings = $domconfig{'autoenroll'};
 8667:         if ($settings->{'run'} eq '1') {
 8668:             $response = 1;
 8669:         }
 8670:     } else {
 8671:         my $homeserver;
 8672:         if (&is_course($cdom,$cnum)) {
 8673:             $homeserver = &homeserver($cnum,$cdom);
 8674:         } else {
 8675:             $homeserver = &domain($cdom,'primary');
 8676:         }
 8677:         if ($homeserver ne 'no_host') {
 8678:             $response = &reply('autorun:'.$cdom,$homeserver);
 8679:         }
 8680:     }
 8681:     return $response;
 8682: }
 8683: 
 8684: sub auto_get_sections {
 8685:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8686:     my $homeserver;
 8687:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8688:         $homeserver = &homeserver($cnum,$cdom);
 8689:     }
 8690:     if (!defined($homeserver)) { 
 8691:         if ($cdom =~ /^$match_domain$/) {
 8692:             $homeserver = &domain($cdom,'primary');
 8693:         }
 8694:     }
 8695:     my @secs;
 8696:     if (defined($homeserver)) {
 8697:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8698:         unless ($response eq 'refused') {
 8699:             @secs = split(/:/,$response);
 8700:         }
 8701:     }
 8702:     return @secs;
 8703: }
 8704: 
 8705: sub auto_new_course {
 8706:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8707:     my $homeserver = &homeserver($cnum,$cdom);
 8708:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8709:     return $response;
 8710: }
 8711: 
 8712: sub auto_validate_courseID {
 8713:     my ($cnum,$cdom,$inst_course_id) = @_;
 8714:     my $homeserver = &homeserver($cnum,$cdom);
 8715:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8716:     return $response;
 8717: }
 8718: 
 8719: sub auto_validate_instcode {
 8720:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8721:     my ($homeserver,$response);
 8722:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8723:         $homeserver = &homeserver($cnum,$cdom);
 8724:     }
 8725:     if (!defined($homeserver)) {
 8726:         if ($cdom =~ /^$match_domain$/) {
 8727:             $homeserver = &domain($cdom,'primary');
 8728:         }
 8729:     }
 8730:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8731:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8732:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8733:     return ($outcome,$description,$defaultcredits);
 8734: }
 8735: 
 8736: sub auto_create_password {
 8737:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8738:     my ($homeserver,$response);
 8739:     my $create_passwd = 0;
 8740:     my $authchk = '';
 8741:     if ($udom =~ /^$match_domain$/) {
 8742:         $homeserver = &domain($udom,'primary');
 8743:     }
 8744:     if ($homeserver eq '') {
 8745:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8746:             $homeserver = &homeserver($cnum,$cdom);
 8747:         }
 8748:     }
 8749:     if ($homeserver eq '') {
 8750:         $authchk = 'nodomain';
 8751:     } else {
 8752:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8753:         if ($response eq 'refused') {
 8754:             $authchk = 'refused';
 8755:         } else {
 8756:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8757:         }
 8758:     }
 8759:     return ($authparam,$create_passwd,$authchk);
 8760: }
 8761: 
 8762: sub auto_photo_permission {
 8763:     my ($cnum,$cdom,$students) = @_;
 8764:     my $homeserver = &homeserver($cnum,$cdom);
 8765:     my ($outcome,$perm_reqd,$conditions) = 
 8766: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8767:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8768: 	return (undef,undef);
 8769:     }
 8770:     return ($outcome,$perm_reqd,$conditions);
 8771: }
 8772: 
 8773: sub auto_checkphotos {
 8774:     my ($uname,$udom,$pid) = @_;
 8775:     my $homeserver = &homeserver($uname,$udom);
 8776:     my ($result,$resulttype);
 8777:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8778: 				   &escape($uname).':'.&escape($pid),
 8779: 				   $homeserver));
 8780:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8781: 	return (undef,undef);
 8782:     }
 8783:     if ($outcome) {
 8784:         ($result,$resulttype) = split(/:/,$outcome);
 8785:     } 
 8786:     return ($result,$resulttype);
 8787: }
 8788: 
 8789: sub auto_photochoice {
 8790:     my ($cnum,$cdom) = @_;
 8791:     my $homeserver = &homeserver($cnum,$cdom);
 8792:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8793: 						       &escape($cdom),
 8794: 						       $homeserver)));
 8795:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8796: 	return (undef,undef);
 8797:     }
 8798:     return ($update,$comment);
 8799: }
 8800: 
 8801: sub auto_photoupdate {
 8802:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8803:     my $homeserver = &homeserver($cnum,$dom);
 8804:     my $host=&hostname($homeserver);
 8805:     my $cmd = '';
 8806:     my $maxtries = 1;
 8807:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8808:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8809:     }
 8810:     $cmd =~ s/%%$//;
 8811:     $cmd = &escape($cmd);
 8812:     my $query = 'institutionalphotos';
 8813:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8814:     unless ($queryid=~/^\Q$host\E\_/) {
 8815:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8816:         return 'error: '.$queryid;
 8817:     }
 8818:     my $reply = &get_query_reply($queryid);
 8819:     my $tries = 1;
 8820:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8821:         $reply = &get_query_reply($queryid);
 8822:         $tries ++;
 8823:     }
 8824:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8825:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8826:     } else {
 8827:         my @responses = split(/:/,$reply);
 8828:         my $outcome = shift(@responses); 
 8829:         foreach my $item (@responses) {
 8830:             my ($key,$value) = split(/=/,$item);
 8831:             $$photo{$key} = $value;
 8832:         }
 8833:         return $outcome;
 8834:     }
 8835:     return 'error';
 8836: }
 8837: 
 8838: sub auto_instcode_format {
 8839:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8840: 	$cat_order) = @_;
 8841:     my $courses = '';
 8842:     my @homeservers;
 8843:     if ($caller eq 'global') {
 8844: 	my %servers = &get_servers($codedom,'library');
 8845: 	foreach my $tryserver (keys(%servers)) {
 8846: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8847: 		push(@homeservers,$tryserver);
 8848: 	    }
 8849:         }
 8850:     } elsif ($caller eq 'requests') {
 8851:         if ($codedom =~ /^$match_domain$/) {
 8852:             my $chome = &domain($codedom,'primary');
 8853:             unless ($chome eq 'no_host') {
 8854:                 push(@homeservers,$chome);
 8855:             }
 8856:         }
 8857:     } else {
 8858:         push(@homeservers,&homeserver($caller,$codedom));
 8859:     }
 8860:     foreach my $code (keys(%{$instcodes})) {
 8861:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8862:     }
 8863:     chop($courses);
 8864:     my $ok_response = 0;
 8865:     my $response;
 8866:     while (@homeservers > 0 && $ok_response == 0) {
 8867:         my $server = shift(@homeservers); 
 8868:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8869:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8870:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8871: 		split(/:/,$response);
 8872:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8873:             push(@{$codetitles},&str2array($codetitles_str));
 8874:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8875:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8876:             $ok_response = 1;
 8877:         }
 8878:     }
 8879:     if ($ok_response) {
 8880:         return 'ok';
 8881:     } else {
 8882:         return $response;
 8883:     }
 8884: }
 8885: 
 8886: sub auto_instcode_defaults {
 8887:     my ($domain,$returnhash,$code_order) = @_;
 8888:     my @homeservers;
 8889: 
 8890:     my %servers = &get_servers($domain,'library');
 8891:     foreach my $tryserver (keys(%servers)) {
 8892: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8893: 	    push(@homeservers,$tryserver);
 8894: 	}
 8895:     }
 8896: 
 8897:     my $response;
 8898:     foreach my $server (@homeservers) {
 8899:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8900:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8901: 	
 8902: 	foreach my $pair (split(/\&/,$response)) {
 8903: 	    my ($name,$value)=split(/\=/,$pair);
 8904: 	    if ($name eq 'code_order') {
 8905: 		@{$code_order} = split(/\&/,&unescape($value));
 8906: 	    } else {
 8907: 		$returnhash->{&unescape($name)}=&unescape($value);
 8908: 	    }
 8909: 	}
 8910: 	return 'ok';
 8911:     }
 8912: 
 8913:     return $response;
 8914: }
 8915: 
 8916: sub auto_possible_instcodes {
 8917:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8918:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8919:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8920:         return;
 8921:     }
 8922:     my (@homeservers,$uhome);
 8923:     if (defined(&domain($domain,'primary'))) {
 8924:         $uhome=&domain($domain,'primary');
 8925:         push(@homeservers,&domain($domain,'primary'));
 8926:     } else {
 8927:         my %servers = &get_servers($domain,'library');
 8928:         foreach my $tryserver (keys(%servers)) {
 8929:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8930:                 push(@homeservers,$tryserver);
 8931:             }
 8932:         }
 8933:     }
 8934:     my $response;
 8935:     foreach my $server (@homeservers) {
 8936:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8937:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8938:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8939:             split(':',$response);
 8940:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8941:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8942:         foreach my $item (split('&',$cat_title)) {   
 8943:             my ($name,$value)=split('=',$item);
 8944:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8945:         }
 8946:         foreach my $item (split('&',$cat_order)) {
 8947:             my ($name,$value)=split('=',$item);
 8948:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8949:         }
 8950:         return 'ok';
 8951:     }
 8952:     return $response;
 8953: }
 8954: 
 8955: sub auto_courserequest_checks {
 8956:     my ($dom) = @_;
 8957:     my ($homeserver,%validations);
 8958:     if ($dom =~ /^$match_domain$/) {
 8959:         $homeserver = &domain($dom,'primary');
 8960:     }
 8961:     unless ($homeserver eq 'no_host') {
 8962:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8963:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8964:             my @items = split(/&/,$response);
 8965:             foreach my $item (@items) {
 8966:                 my ($key,$value) = split('=',$item);
 8967:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8968:             }
 8969:         }
 8970:     }
 8971:     return %validations; 
 8972: }
 8973: 
 8974: sub auto_courserequest_validation {
 8975:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8976:     my ($homeserver,$response);
 8977:     if ($dom =~ /^$match_domain$/) {
 8978:         $homeserver = &domain($dom,'primary');
 8979:     }
 8980:     unless ($homeserver eq 'no_host') {
 8981:         my $customdata;
 8982:         if (ref($custominfo) eq 'HASH') {
 8983:             $customdata = &freeze_escape($custominfo);
 8984:         }
 8985:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8986:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8987:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8988:                                     $customdata,$homeserver));
 8989:     }
 8990:     return $response;
 8991: }
 8992: 
 8993: sub auto_validate_class_sec {
 8994:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8995:     my $homeserver = &homeserver($cnum,$cdom);
 8996:     my $ownerlist;
 8997:     if (ref($owners) eq 'ARRAY') {
 8998:         $ownerlist = join(',',@{$owners});
 8999:     } else {
 9000:         $ownerlist = $owners;
 9001:     }
 9002:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9003:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9004:     return $response;
 9005: }
 9006: 
 9007: sub auto_validate_instclasses {
 9008:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9009:     my ($homeserver,%validations);
 9010:     $homeserver = &homeserver($cnum,$cdom);
 9011:     unless ($homeserver eq 'no_host') {
 9012:         my $ownerlist;
 9013:         if (ref($owners) eq 'ARRAY') {
 9014:             $ownerlist = join(',',@{$owners});
 9015:         } else {
 9016:             $ownerlist = $owners;
 9017:         }
 9018:         if (ref($classesref) eq 'HASH') {
 9019:             my $classes = &freeze_escape($classesref);
 9020:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9021:                                 ':'.$cdom.':'.$classes,$homeserver);
 9022:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9023:                 my @items = split(/&/,$response);
 9024:                 foreach my $item (@items) {
 9025:                     my ($key,$value) = split('=',$item);
 9026:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9027:                 }
 9028:             }
 9029:         }
 9030:     }
 9031:     return %validations;
 9032: }
 9033: 
 9034: sub auto_crsreq_update {
 9035:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9036:         $code,$accessstart,$accessend,$inbound) = @_;
 9037:     my ($homeserver,%crsreqresponse);
 9038:     if ($cdom =~ /^$match_domain$/) {
 9039:         $homeserver = &domain($cdom,'primary');
 9040:     }
 9041:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9042:         my $info;
 9043:         if (ref($inbound) eq 'HASH') {
 9044:             $info = &freeze_escape($inbound);
 9045:         }
 9046:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9047:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9048:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9049:                             &escape($title).':'.&escape($code).':'.
 9050:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9051:                             $homeserver);
 9052:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9053:             my @items = split(/&/,$response);
 9054:             foreach my $item (@items) {
 9055:                 my ($key,$value) = split('=',$item);
 9056:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9057:             }
 9058:         }
 9059:     }
 9060:     return \%crsreqresponse;
 9061: }
 9062: 
 9063: sub auto_export_grades {
 9064:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9065:     my ($homeserver,%exportresponse);
 9066:     if ($cdom =~ /^$match_domain$/) {
 9067:         $homeserver = &domain($cdom,'primary');
 9068:     }
 9069:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9070:         my $info;
 9071:         if (ref($inforef) eq 'HASH') {
 9072:             $info = &freeze_escape($inforef);
 9073:         }
 9074:         if (ref($gradesref) eq 'HASH') {
 9075:             my $grades = &freeze_escape($gradesref);
 9076:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9077:                                 $info.':'.$grades,$homeserver);
 9078:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9079:                 my @items = split(/&/,$response);
 9080:                 foreach my $item (@items) {
 9081:                     my ($key,$value) = split('=',$item);
 9082:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9083:                 }
 9084:             }
 9085:         }
 9086:     }
 9087:     return \%exportresponse;
 9088: }
 9089: 
 9090: sub check_instcode_cloning {
 9091:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9092:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9093:         return;
 9094:     }
 9095:     my $canclone;
 9096:     if (@{$code_order} > 0) {
 9097:         my $instcoderegexp ='^';
 9098:         my @clonecodes = split(/\&/,$cloner);
 9099:         foreach my $item (@{$code_order}) {
 9100:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9101:                 foreach my $pair (@clonecodes) {
 9102:                     my ($key,$val) = split(/\=/,$pair,2);
 9103:                     $val = &unescape($val);
 9104:                     if ($key eq $item) {
 9105:                         $instcoderegexp .= '('.$val.')';
 9106:                         last;
 9107:                     }
 9108:                 }
 9109:             } else {
 9110:                 $instcoderegexp .= $codedefaults->{$item};
 9111:             }
 9112:         }
 9113:         $instcoderegexp .= '$';
 9114:         my (@from,@to);
 9115:         eval {
 9116:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9117:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9118:         };
 9119:         if ((@from > 0) && (@to > 0)) {
 9120:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9121:             if (!@diffs) {
 9122:                 $canclone = 1;
 9123:             }
 9124:         }
 9125:     }
 9126:     return $canclone;
 9127: }
 9128: 
 9129: sub default_instcode_cloning {
 9130:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9131:     my (%codedefaults,@code_order,$canclone);
 9132:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9133:         %codedefaults = %{$codedefaultsref};
 9134:         @code_order = @{$codeorderref};
 9135:     } elsif ($clonedom) {
 9136:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9137:     }
 9138:     if (($domdefclone) && (@code_order)) {
 9139:         my @clonecodes = split(/\+/,$domdefclone);
 9140:         my $instcoderegexp ='^';
 9141:         foreach my $item (@code_order) {
 9142:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9143:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9144:             } else {
 9145:                 $instcoderegexp .= $codedefaults{$item};
 9146:             }
 9147:         }
 9148:         $instcoderegexp .= '$';
 9149:         my (@from,@to);
 9150:         eval {
 9151:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9152:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9153:         };
 9154:         if ((@from > 0) && (@to > 0)) {
 9155:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9156:             if (!@diffs) {
 9157:                 $canclone = 1;
 9158:             }
 9159:         }
 9160:     }
 9161:     return $canclone;
 9162: }
 9163: 
 9164: # ------------------------------------------------------- Course Group routines
 9165: 
 9166: sub get_coursegroups {
 9167:     my ($cdom,$cnum,$group,$namespace) = @_;
 9168:     return(&dump($namespace,$cdom,$cnum,$group));
 9169: }
 9170: 
 9171: sub modify_coursegroup {
 9172:     my ($cdom,$cnum,$groupsettings) = @_;
 9173:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9174: }
 9175: 
 9176: sub toggle_coursegroup_status {
 9177:     my ($cdom,$cnum,$group,$action) = @_;
 9178:     my ($from_namespace,$to_namespace);
 9179:     if ($action eq 'delete') {
 9180:         $from_namespace = 'coursegroups';
 9181:         $to_namespace = 'deleted_groups';
 9182:     } else {
 9183:         $from_namespace = 'deleted_groups';
 9184:         $to_namespace = 'coursegroups';
 9185:     }
 9186:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9187:     if (my $tmp = &error(%curr_group)) {
 9188:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9189:         return ('read error',$tmp);
 9190:     } else {
 9191:         my %savedsettings = %curr_group; 
 9192:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9193:         my $deloutcome;
 9194:         if ($result eq 'ok') {
 9195:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9196:         } else {
 9197:             return ('write error',$result);
 9198:         }
 9199:         if ($deloutcome eq 'ok') {
 9200:             return 'ok';
 9201:         } else {
 9202:             return ('delete error',$deloutcome);
 9203:         }
 9204:     }
 9205: }
 9206: 
 9207: sub modify_group_roles {
 9208:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9209:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9210:     my $role = 'gr/'.&escape($userprivs);
 9211:     my ($uname,$udom) = split(/:/,$user);
 9212:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9213:     if ($result eq 'ok') {
 9214:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9215:     }
 9216:     return $result;
 9217: }
 9218: 
 9219: sub modify_coursegroup_membership {
 9220:     my ($cdom,$cnum,$membership) = @_;
 9221:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9222:     return $result;
 9223: }
 9224: 
 9225: sub get_active_groups {
 9226:     my ($udom,$uname,$cdom,$cnum) = @_;
 9227:     my $now = time;
 9228:     my %groups = ();
 9229:     foreach my $key (keys(%env)) {
 9230:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9231:             my ($start,$end) = split(/\./,$env{$key});
 9232:             if (($end!=0) && ($end<$now)) { next; }
 9233:             if (($start!=0) && ($start>$now)) { next; }
 9234:             if ($1 eq $cdom && $2 eq $cnum) {
 9235:                 $groups{$3} = $env{$key} ;
 9236:             }
 9237:         }
 9238:     }
 9239:     return %groups;
 9240: }
 9241: 
 9242: sub get_group_membership {
 9243:     my ($cdom,$cnum,$group) = @_;
 9244:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9245: }
 9246: 
 9247: sub get_users_groups {
 9248:     my ($udom,$uname,$courseid) = @_;
 9249:     my @usersgroups;
 9250:     my $cachetime=1800;
 9251: 
 9252:     my $hashid="$udom:$uname:$courseid";
 9253:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9254:     if (defined($cached)) {
 9255:         @usersgroups = split(/:/,$grouplist);
 9256:     } else {  
 9257:         $grouplist = '';
 9258:         my $courseurl = &courseid_to_courseurl($courseid);
 9259:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9260:         my $access_end = $env{'course.'.$courseid.
 9261:                               '.default_enrollment_end_date'};
 9262:         my $now = time;
 9263:         foreach my $key (keys(%roleshash)) {
 9264:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9265:                 my $group = $1;
 9266:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9267:                     my $start = $2;
 9268:                     my $end = $1;
 9269:                     if ($start == -1) { next; } # deleted from group
 9270:                     if (($start!=0) && ($start>$now)) { next; }
 9271:                     if (($end!=0) && ($end<$now)) {
 9272:                         if ($access_end && $access_end < $now) {
 9273:                             if ($access_end - $end < 86400) {
 9274:                                 push(@usersgroups,$group);
 9275:                             }
 9276:                         }
 9277:                         next;
 9278:                     }
 9279:                     push(@usersgroups,$group);
 9280:                 }
 9281:             }
 9282:         }
 9283:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9284:         $grouplist = join(':',@usersgroups);
 9285:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9286:     }
 9287:     return @usersgroups;
 9288: }
 9289: 
 9290: sub devalidate_getgroups_cache {
 9291:     my ($udom,$uname,$cdom,$cnum)=@_;
 9292:     my $courseid = $cdom.'_'.$cnum;
 9293: 
 9294:     my $hashid="$udom:$uname:$courseid";
 9295:     &devalidate_cache_new('getgroups',$hashid);
 9296: }
 9297: 
 9298: # ------------------------------------------------------------------ Plain Text
 9299: 
 9300: sub plaintext {
 9301:     my ($short,$type,$cid,$forcedefault) = @_;
 9302:     if ($short =~ m{^cr/}) {
 9303: 	return (split('/',$short))[-1];
 9304:     }
 9305:     if (!defined($cid)) {
 9306:         $cid = $env{'request.course.id'};
 9307:     }
 9308:     my %rolenames = (
 9309:                       Course    => 'std',
 9310:                       Community => 'alt1',
 9311:                       Placement => 'std',
 9312:                     );
 9313:     if ($cid ne '') {
 9314:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9315:             unless ($forcedefault) {
 9316:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9317:                 &Apache::lonlocal::mt_escape(\$roletext);
 9318:                 return &Apache::lonlocal::mt($roletext);
 9319:             }
 9320:         }
 9321:     }
 9322:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9323:         (defined($rolenames{$type})) && 
 9324:         (defined($prp{$short}{$rolenames{$type}}))) {
 9325:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9326:     } elsif ($cid ne '') {
 9327:         my $crstype = $env{'course.'.$cid.'.type'};
 9328:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9329:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9330:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9331:         }
 9332:     }
 9333:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9334: }
 9335: 
 9336: # ----------------------------------------------------------------- Assign Role
 9337: 
 9338: sub assignrole {
 9339:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9340:         $context)=@_;
 9341:     my $mrole;
 9342:     if ($role =~ /^cr\//) {
 9343:         my $cwosec=$url;
 9344:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9345: 	unless (&allowed('ccr',$cwosec)) {
 9346:            my $refused = 1;
 9347:            if ($context eq 'requestcourses') {
 9348:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9349:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9350:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9351:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9352:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9353:                            if ($crsenv{'internal.courseowner'} eq
 9354:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9355:                                $refused = '';
 9356:                            }
 9357:                        }
 9358:                    }
 9359:                }
 9360:            }
 9361:            if ($refused) {
 9362:                &logthis('Refused custom assignrole: '.
 9363:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9364:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9365:                return 'refused';
 9366:            }
 9367:         }
 9368:         $mrole='cr';
 9369:     } elsif ($role =~ /^gr\//) {
 9370:         my $cwogrp=$url;
 9371:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9372:         unless (&allowed('mdg',$cwogrp)) {
 9373:             &logthis('Refused group assignrole: '.
 9374:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9375:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9376:             return 'refused';
 9377:         }
 9378:         $mrole='gr';
 9379:     } else {
 9380:         my $cwosec=$url;
 9381:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9382:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9383:             my $refused;
 9384:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9385:                 if (!(&allowed('c'.$role,$url))) {
 9386:                     $refused = 1;
 9387:                 }
 9388:             } else {
 9389:                 $refused = 1;
 9390:             }
 9391:             if ($refused) {
 9392:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9393:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9394:                     my %crsenv;
 9395:                     if ($role eq 'cc' || $role eq 'co') {
 9396:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9397:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9398:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9399:                                 if ($crsenv{'internal.courseowner'} eq 
 9400:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9401:                                     $refused = '';
 9402:                                 }
 9403:                             }
 9404:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9405:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9406:                                 if ($crsenv{'internal.courseowner'} eq 
 9407:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9408:                                     $refused = '';
 9409:                                 }
 9410:                             }
 9411:                         }
 9412:                     }
 9413:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9414:                     if ($role eq 'st') {
 9415:                         $refused = '';
 9416:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9417:                         $refused = '';
 9418:                     }
 9419:                 } elsif ($context eq 'requestcourses') {
 9420:                     my @possroles = ('st','ta','ep','in','cc','co');
 9421:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9422:                         my $wrongcc;
 9423:                         if ($cnum =~ /^$match_community$/) {
 9424:                             $wrongcc = 1 if ($role eq 'cc');
 9425:                         } else {
 9426:                             $wrongcc = 1 if ($role eq 'co');
 9427:                         }
 9428:                         unless ($wrongcc) {
 9429:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9430:                             if ($crsenv{'internal.courseowner'} eq 
 9431:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9432:                                 $refused = '';
 9433:                             }
 9434:                         }
 9435:                     }
 9436:                 } elsif ($context eq 'requestauthor') {
 9437:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9438:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9439:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9440:                             $refused = '';
 9441:                         } else {
 9442:                             my %domdefaults = &get_domain_defaults($udom);
 9443:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9444:                                 my $checkbystatus;
 9445:                                 if ($env{'user.adv'}) { 
 9446:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9447:                                     if ($disposition eq 'automatic') {
 9448:                                         $refused = '';
 9449:                                     } elsif ($disposition eq '') {
 9450:                                         $checkbystatus = 1;
 9451:                                     } 
 9452:                                 } else {
 9453:                                     $checkbystatus = 1;
 9454:                                 }
 9455:                                 if ($checkbystatus) {
 9456:                                     if ($env{'environment.inststatus'}) {
 9457:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9458:                                         foreach my $type (@inststatuses) {
 9459:                                             if (($type ne '') &&
 9460:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9461:                                                 $refused = '';
 9462:                                             }
 9463:                                         }
 9464:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9465:                                         $refused = '';
 9466:                                     }
 9467:                                 }
 9468:                             }
 9469:                         }
 9470:                     }
 9471:                 }
 9472:                 if ($refused) {
 9473:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9474:                              ' '.$role.' '.$end.' '.$start.' by '.
 9475: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9476:                     return 'refused';
 9477:                 }
 9478:             }
 9479:         } elsif ($role eq 'au') {
 9480:             if ($url ne '/'.$udom.'/') {
 9481:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9482:                          ' to assign author role for '.$uname.':'.$udom.
 9483:                          ' in domain: '.$url.' refused (wrong domain).');
 9484:                 return 'refused';
 9485:             }
 9486:         }
 9487:         $mrole=$role;
 9488:     }
 9489:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9490:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9491:     if ($end) { $command.='_'.$end; }
 9492:     if ($start) {
 9493: 	if ($end) { 
 9494:            $command.='_'.$start; 
 9495:         } else {
 9496:            $command.='_0_'.$start;
 9497:         }
 9498:     }
 9499:     my $origstart = $start;
 9500:     my $origend = $end;
 9501:     my $delflag;
 9502: # actually delete
 9503:     if ($deleteflag) {
 9504: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9505: # modify command to delete the role
 9506:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9507:                 "$udom:$uname:$url".'_'."$mrole";
 9508: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9509: # set start and finish to negative values for userrolelog
 9510:            $start=-1;
 9511:            $end=-1;
 9512:            $delflag = 1;
 9513:         }
 9514:     }
 9515: # send command
 9516:     my $answer=&reply($command,&homeserver($uname,$udom));
 9517: # log new user role if status is ok
 9518:     if ($answer eq 'ok') {
 9519: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9520:         if (($role eq 'cc') || ($role eq 'in') ||
 9521:             ($role eq 'ep') || ($role eq 'ad') ||
 9522:             ($role eq 'ta') || ($role eq 'st') ||
 9523:             ($role=~/^cr/) || ($role eq 'gr') ||
 9524:             ($role eq 'co')) {
 9525: # for course roles, perform group memberships changes triggered by role change.
 9526:             unless ($role =~ /^gr/) {
 9527:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9528:                                                  $origstart,$selfenroll,$context);
 9529:             }
 9530:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9531:                            $selfenroll,$context);
 9532:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9533:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9534:                  ($role eq 'da')) {
 9535:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9536:                            $context);
 9537:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9538:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9539:                              $context); 
 9540:         }
 9541:         if ($role eq 'cc') {
 9542:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9543:         }
 9544:     }
 9545:     return $answer;
 9546: }
 9547: 
 9548: sub autoupdate_coowners {
 9549:     my ($url,$end,$start,$uname,$udom) = @_;
 9550:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9551:     if (($cdom ne '') && ($cnum ne '')) {
 9552:         my $now = time;
 9553:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9554:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9555:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9556:             my $instcode = $coursehash{'internal.coursecode'};
 9557:             if ($instcode ne '') {
 9558:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9559:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9560:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9561:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9562:                         if ($result eq 'valid') {
 9563:                             if ($coursehash{'internal.co-owners'}) {
 9564:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9565:                                     push(@newcoowners,$coowner);
 9566:                                 }
 9567:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9568:                                     push(@newcoowners,$uname.':'.$udom);
 9569:                                 }
 9570:                                 @newcoowners = sort(@newcoowners);
 9571:                             } else {
 9572:                                 push(@newcoowners,$uname.':'.$udom);
 9573:                             }
 9574:                         } else {
 9575:                             if ($coursehash{'internal.co-owners'}) {
 9576:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9577:                                     unless ($coowner eq $uname.':'.$udom) {
 9578:                                         push(@newcoowners,$coowner);
 9579:                                     }
 9580:                                 }
 9581:                                 unless (@newcoowners > 0) {
 9582:                                     $delcoowners = 1;
 9583:                                     $coowners = '';
 9584:                                 }
 9585:                             }
 9586:                         }
 9587:                         if (@newcoowners || $delcoowners) {
 9588:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9589:                                             $delcoowners,@newcoowners);
 9590:                         }
 9591:                     }
 9592:                 }
 9593:             }
 9594:         }
 9595:     }
 9596: }
 9597: 
 9598: sub store_coowners {
 9599:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9600:     my $cid = $cdom.'_'.$cnum;
 9601:     my ($coowners,$delresult,$putresult);
 9602:     if (@newcoowners) {
 9603:         $coowners = join(',',@newcoowners);
 9604:         my %coownershash = (
 9605:                             'internal.co-owners' => $coowners,
 9606:                            );
 9607:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9608:         if ($putresult eq 'ok') {
 9609:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9610:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9611:             }
 9612:         }
 9613:     }
 9614:     if ($delcoowners) {
 9615:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9616:         if ($delresult eq 'ok') {
 9617:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9618:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9619:             }
 9620:         }
 9621:     }
 9622:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9623:         my %crsinfo =
 9624:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9625:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9626:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9627:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9628:         }
 9629:     }
 9630: }
 9631: 
 9632: # -------------------------------------------------- Modify user authentication
 9633: # Overrides without validation
 9634: 
 9635: sub modifyuserauth {
 9636:     my ($udom,$uname,$umode,$upass)=@_;
 9637:     my $uhome=&homeserver($uname,$udom);
 9638:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9639:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9640:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9641:              ' in domain '.$env{'request.role.domain'});  
 9642:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9643: 		     &escape($upass),$uhome);
 9644:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9645:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9646:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9647:     &log($udom,,$uname,$uhome,
 9648:         'Authentication changed by '.$env{'user.domain'}.', '.
 9649:                                      $env{'user.name'}.', '.$umode.
 9650:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9651:     unless ($reply eq 'ok') {
 9652:         &logthis('Authentication mode error: '.$reply);
 9653: 	return 'error: '.$reply;
 9654:     }   
 9655:     return 'ok';
 9656: }
 9657: 
 9658: # --------------------------------------------------------------- Modify a user
 9659: 
 9660: sub modifyuser {
 9661:     my ($udom,    $uname, $uid,
 9662:         $umode,   $upass, $first,
 9663:         $middle,  $last,  $gene,
 9664:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9665:     $udom= &LONCAPA::clean_domain($udom);
 9666:     $uname=&LONCAPA::clean_username($uname);
 9667:     my $showcandelete = 'none';
 9668:     if (ref($candelete) eq 'ARRAY') {
 9669:         if (@{$candelete} > 0) {
 9670:             $showcandelete = join(', ',@{$candelete});
 9671:         }
 9672:     }
 9673:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9674:              $umode.', '.$first.', '.$middle.', '.
 9675: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9676:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9677:                                      ' desiredhome not specified'). 
 9678:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9679:              ' in domain '.$env{'request.role.domain'});
 9680:     my $uhome=&homeserver($uname,$udom,'true');
 9681:     my $newuser;
 9682:     if ($uhome eq 'no_host') {
 9683:         $newuser = 1;
 9684:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9685:                 ($umode eq 'lti')) {
 9686:             return 'error: more information needed to create new user';
 9687:         }
 9688:     }
 9689: # ----------------------------------------------------------------- Create User
 9690:     if (($uhome eq 'no_host') && 
 9691: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9692:         my $unhome='';
 9693:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9694:             $unhome = $desiredhome;
 9695: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9696: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9697:         } else { # load balancing routine for determining $unhome
 9698:             my $loadm=10000000;
 9699: 	    my %servers = &get_servers($udom,'library');
 9700: 	    foreach my $tryserver (keys(%servers)) {
 9701: 		my $answer=reply('load',$tryserver);
 9702: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9703: 		    $loadm=$answer;
 9704: 		    $unhome=$tryserver;
 9705: 		}
 9706: 	    }
 9707:         }
 9708:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9709: 	    return 'error: unable to find a home server for '.$uname.
 9710:                    ' in domain '.$udom;
 9711:         }
 9712:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9713:                          &escape($upass),$unhome);
 9714: 	unless ($reply eq 'ok') {
 9715:             return 'error: '.$reply;
 9716:         }   
 9717:         $uhome=&homeserver($uname,$udom,'true');
 9718:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9719: 	    return 'error: unable verify users home machine.';
 9720:         }
 9721:     }   # End of creation of new user
 9722: # ---------------------------------------------------------------------- Add ID
 9723:     if ($uid) {
 9724:        $uid=~tr/A-Z/a-z/;
 9725:        my %uidhash=&idrget($udom,$uname);
 9726:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9727:          && (!$forceid)) {
 9728: 	  unless ($uid eq $uidhash{$uname}) {
 9729: 	      return 'error: user id "'.$uid.'" does not match '.
 9730:                   'current user id "'.$uidhash{$uname}.'".';
 9731:           }
 9732:        } else {
 9733: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9734:        }
 9735:     }
 9736: # -------------------------------------------------------------- Add names, etc
 9737:     my @tmp=&get('environment',
 9738: 		   ['firstname','middlename','lastname','generation','id',
 9739:                     'permanentemail','inststatus'],
 9740: 		   $udom,$uname);
 9741:     my (%names,%oldnames);
 9742:     if ($tmp[0] =~ m/^error:.*/) { 
 9743:         %names=(); 
 9744:     } else {
 9745:         %names = @tmp;
 9746:         %oldnames = %names;
 9747:     }
 9748: #
 9749: # If name, email and/or uid are blank (e.g., because an uploaded file
 9750: # of users did not contain them), do not overwrite existing values
 9751: # unless field is in $candelete array ref.  
 9752: #
 9753: 
 9754:     my @fields = ('firstname','middlename','lastname','generation',
 9755:                   'permanentemail','id');
 9756:     my %newvalues;
 9757:     if (ref($candelete) eq 'ARRAY') {
 9758:         foreach my $field (@fields) {
 9759:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9760:                 if ($field eq 'firstname') {
 9761:                     $names{$field} = $first;
 9762:                 } elsif ($field eq 'middlename') {
 9763:                     $names{$field} = $middle;
 9764:                 } elsif ($field eq 'lastname') {
 9765:                     $names{$field} = $last;
 9766:                 } elsif ($field eq 'generation') { 
 9767:                     $names{$field} = $gene;
 9768:                 } elsif ($field eq 'permanentemail') {
 9769:                     $names{$field} = $email;
 9770:                 } elsif ($field eq 'id') {
 9771:                     $names{$field}  = $uid;
 9772:                 }
 9773:             }
 9774:         }
 9775:     }
 9776:     if ($first)  { $names{'firstname'}  = $first; }
 9777:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9778:     if ($last)   { $names{'lastname'}   = $last; }
 9779:     if (defined($gene))   { $names{'generation'} = $gene; }
 9780:     if ($email) {
 9781:        $email=~s/[^\w\@\.\-\,]//gs;
 9782:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9783:     }
 9784:     if ($uid) { $names{'id'}  = $uid; }
 9785:     if (defined($inststatus)) {
 9786:         $names{'inststatus'} = '';
 9787:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9788:         if (ref($usertypes) eq 'HASH') {
 9789:             my @okstatuses; 
 9790:             foreach my $item (split(/:/,$inststatus)) {
 9791:                 if (defined($usertypes->{$item})) {
 9792:                     push(@okstatuses,$item);  
 9793:                 }
 9794:             }
 9795:             if (@okstatuses) {
 9796:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9797:             }
 9798:         }
 9799:     }
 9800:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9801:                  $umode.', '.$first.', '.$middle.', '.
 9802:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9803:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9804:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9805:     } else {
 9806:         $logmsg .= ' during self creation';
 9807:     }
 9808:     my $changed;
 9809:     if ($newuser) {
 9810:         $changed = 1;
 9811:     } else {
 9812:         foreach my $field (@fields) {
 9813:             if ($names{$field} ne $oldnames{$field}) {
 9814:                 $changed = 1;
 9815:                 last;
 9816:             }
 9817:         }
 9818:     }
 9819:     unless ($changed) {
 9820:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9821:         &logthis($logmsg);
 9822:         return 'ok';
 9823:     }
 9824:     my $reply = &put('environment', \%names, $udom,$uname);
 9825:     if ($reply ne 'ok') { 
 9826:         return 'error: '.$reply;
 9827:     }
 9828:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9829:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9830:     }
 9831:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9832:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9833:     $logmsg = 'Success modifying user '.$logmsg;
 9834:     &logthis($logmsg);
 9835:     return 'ok';
 9836: }
 9837: 
 9838: # -------------------------------------------------------------- Modify student
 9839: 
 9840: sub modifystudent {
 9841:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9842:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9843:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9844:     if (!$cid) {
 9845: 	unless ($cid=$env{'request.course.id'}) {
 9846: 	    return 'not_in_class';
 9847: 	}
 9848:     }
 9849: # --------------------------------------------------------------- Make the user
 9850:     my $reply=&modifyuser
 9851: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9852:          $desiredhome,$email,$inststatus);
 9853:     unless ($reply eq 'ok') { return $reply; }
 9854:     # This will cause &modify_student_enrollment to get the uid from the
 9855:     # student's environment
 9856:     $uid = undef if (!$forceid);
 9857:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9858:                                         $gene,$usec,$end,$start,$type,$locktype,
 9859:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9860:     return $reply;
 9861: }
 9862: 
 9863: sub modify_student_enrollment {
 9864:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9865:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9866:     my ($cdom,$cnum,$chome);
 9867:     if (!$cid) {
 9868: 	unless ($cid=$env{'request.course.id'}) {
 9869: 	    return 'not_in_class';
 9870: 	}
 9871: 	$cdom=$env{'course.'.$cid.'.domain'};
 9872: 	$cnum=$env{'course.'.$cid.'.num'};
 9873:     } else {
 9874: 	($cdom,$cnum)=split(/_/,$cid);
 9875:     }
 9876:     $chome=$env{'course.'.$cid.'.home'};
 9877:     if (!$chome) {
 9878: 	$chome=&homeserver($cnum,$cdom);
 9879:     }
 9880:     if (!$chome) { return 'unknown_course'; }
 9881:     # Make sure the user exists
 9882:     my $uhome=&homeserver($uname,$udom);
 9883:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9884: 	return 'error: no such user';
 9885:     }
 9886:     # Get student data if we were not given enough information
 9887:     if (!defined($first)  || $first  eq '' || 
 9888:         !defined($last)   || $last   eq '' || 
 9889:         !defined($uid)    || $uid    eq '' || 
 9890:         !defined($middle) || $middle eq '' || 
 9891:         !defined($gene)   || $gene   eq '') {
 9892:         # They did not supply us with enough data to enroll the student, so
 9893:         # we need to pick up more information.
 9894:         my %tmp = &get('environment',
 9895:                        ['firstname','middlename','lastname', 'generation','id']
 9896:                        ,$udom,$uname);
 9897: 
 9898:         #foreach my $key (keys(%tmp)) {
 9899:         #    &logthis("key $key = ".$tmp{$key});
 9900:         #}
 9901:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9902:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9903:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9904:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9905:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9906:     }
 9907:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9908:     my $user = "$uname:$udom";
 9909:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9910:     my $reply=cput('classlist',
 9911: 		   {$user => 
 9912: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9913: 		   $cdom,$cnum);
 9914:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9915:         &devalidate_getsection_cache($udom,$uname,$cid);
 9916:     } else { 
 9917: 	return 'error: '.$reply;
 9918:     }
 9919:     # Add student role to user
 9920:     my $uurl='/'.$cid;
 9921:     $uurl=~s/\_/\//g;
 9922:     if ($usec) {
 9923: 	$uurl.='/'.$usec;
 9924:     }
 9925:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9926:                              $selfenroll,$context);
 9927:     if ($result ne 'ok') {
 9928:         if ($old_entry{$user} ne '') {
 9929:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9930:         } else {
 9931:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9932:         }
 9933:     }
 9934:     return $result; 
 9935: }
 9936: 
 9937: sub format_name {
 9938:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9939:     my $name;
 9940:     if ($first ne 'lastname') {
 9941: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9942:     } else {
 9943: 	if ($lastname=~/\S/) {
 9944: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9945: 	    $name=~s/\s+,/,/;
 9946: 	} else {
 9947: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9948: 	}
 9949:     }
 9950:     $name=~s/^\s+//;
 9951:     $name=~s/\s+$//;
 9952:     $name=~s/\s+/ /g;
 9953:     return $name;
 9954: }
 9955: 
 9956: # ------------------------------------------------- Write to course preferences
 9957: 
 9958: sub writecoursepref {
 9959:     my ($courseid,%prefs)=@_;
 9960:     $courseid=~s/^\///;
 9961:     $courseid=~s/\_/\//g;
 9962:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9963:     my $chome=homeserver($cnum,$cdomain);
 9964:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9965: 	return 'error: no such course';
 9966:     }
 9967:     my $cstring='';
 9968:     foreach my $pref (keys(%prefs)) {
 9969: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9970:     }
 9971:     $cstring=~s/\&$//;
 9972:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9973: }
 9974: 
 9975: # ---------------------------------------------------------- Make/modify course
 9976: 
 9977: sub createcourse {
 9978:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9979:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9980:     $url=&declutter($url);
 9981:     my $cid='';
 9982:     if ($context eq 'requestcourses') {
 9983:         my $can_create = 0;
 9984:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9985:         if ($udom eq $ownerdom) {
 9986:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9987:                                   $context)) {
 9988:                 $can_create = 1;
 9989:             }
 9990:         } else {
 9991:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9992:                                            $category);
 9993:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9994:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9995:                 if (@curr > 0) {
 9996:                     my @options = qw(approval validate autolimit);
 9997:                     my $optregex = join('|',@options);
 9998:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9999:                         $can_create = 1;
10000:                     }
10001:                 }
10002:             }
10003:         }
10004:         if ($can_create) {
10005:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10006:                 unless (&allowed('ccc',$udom)) {
10007:                     return 'refused'; 
10008:                 }
10009:             }
10010:         } else {
10011:             return 'refused';
10012:         }
10013:     } elsif (!&allowed('ccc',$udom)) {
10014:         return 'refused';
10015:     }
10016: # --------------------------------------------------------------- Get Unique ID
10017:     my $uname;
10018:     if ($cnum =~ /^$match_courseid$/) {
10019:         my $chome=&homeserver($cnum,$udom,'true');
10020:         if (($chome eq '') || ($chome eq 'no_host')) {
10021:             $uname = $cnum;
10022:         } else {
10023:             $uname = &generate_coursenum($udom,$crstype);
10024:         }
10025:     } else {
10026:         $uname = &generate_coursenum($udom,$crstype);
10027:     }
10028:     return $uname if ($uname =~ /^error/);
10029: # -------------------------------------------------- Check supplied server name
10030:     if (!defined($course_server)) {
10031:         if (defined(&domain($udom,'primary'))) {
10032:             $course_server = &domain($udom,'primary');
10033:         } else {
10034:             $course_server = $env{'user.home'}; 
10035:         }
10036:     }
10037:     my %host_servers =
10038:         &Apache::lonnet::get_servers($udom,'library');
10039:     unless ($host_servers{$course_server}) {
10040:         return 'error: invalid home server for course: '.$course_server;
10041:     }
10042: # ------------------------------------------------------------- Make the course
10043:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10044:                       $course_server);
10045:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10046:     my $uhome=&homeserver($uname,$udom,'true');
10047:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10048: 	return 'error: no such course';
10049:     }
10050: # ----------------------------------------------------------------- Course made
10051: # log existence
10052:     my $now = time;
10053:     my $newcourse = {
10054:                     $udom.'_'.$uname => {
10055:                                      description => $description,
10056:                                      inst_code   => $inst_code,
10057:                                      owner       => $course_owner,
10058:                                      type        => $crstype,
10059:                                      creator     => $env{'user.name'}.':'.
10060:                                                     $env{'user.domain'},
10061:                                      created     => $now,
10062:                                      context     => $context,
10063:                                                 },
10064:                     };
10065:     &courseidput($udom,$newcourse,$uhome,'notime');
10066: # set toplevel url
10067:     my $topurl=$url;
10068:     unless ($nonstandard) {
10069: # ------------------------------------------ For standard courses, make top url
10070:         my $mapurl=&clutter($url);
10071:         if ($mapurl eq '/res/') { $mapurl=''; }
10072:         $env{'form.initmap'}=(<<ENDINITMAP);
10073: <map>
10074: <resource id="1" type="start"></resource>
10075: <resource id="2" src="$mapurl"></resource>
10076: <resource id="3" type="finish"></resource>
10077: <link index="1" from="1" to="2"></link>
10078: <link index="2" from="2" to="3"></link>
10079: </map>
10080: ENDINITMAP
10081:         $topurl=&declutter(
10082:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10083:                           );
10084:     }
10085: # ----------------------------------------------------------- Write preferences
10086:     &writecoursepref($udom.'_'.$uname,
10087:                      ('description'              => $description,
10088:                       'url'                      => $topurl,
10089:                       'internal.creator'         => $env{'user.name'}.':'.
10090:                                                     $env{'user.domain'},
10091:                       'internal.created'         => $now,
10092:                       'internal.creationcontext' => $context)
10093:                     );
10094:     return '/'.$udom.'/'.$uname;
10095: }
10096: 
10097: # ------------------------------------------------------------------- Create ID
10098: sub generate_coursenum {
10099:     my ($udom,$crstype) = @_;
10100:     my $domdesc = &domain($udom);
10101:     return 'error: invalid domain' if ($domdesc eq '');
10102:     my $first;
10103:     if ($crstype eq 'Community') {
10104:         $first = '0';
10105:     } else {
10106:         $first = int(1+rand(9)); 
10107:     } 
10108:     my $uname=$first.
10109:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10110:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10111:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10112: # ----------------------------------------------- Make sure that does not exist
10113:     my $uhome=&homeserver($uname,$udom,'true');
10114:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10115:         if ($crstype eq 'Community') {
10116:             $first = '0';
10117:         } else {
10118:             $first = int(1+rand(9));
10119:         }
10120:         $uname=$first.
10121:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10122:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10123:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10124:         $uhome=&homeserver($uname,$udom,'true');
10125:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10126:             return 'error: unable to generate unique course-ID';
10127:         }
10128:     }
10129:     return $uname;
10130: }
10131: 
10132: sub is_course {
10133:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10134:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10135: 
10136:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10137:     my $uhome=&homeserver($cnum,$cdom);
10138:     my $iscourse;
10139:     if (grep { $_ eq $uhome } current_machine_ids()) {
10140:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10141:     } else {
10142:         my $hashid = $cdom.':'.$cnum;
10143:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10144:         unless (defined($cached)) {
10145:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10146:                                         $cnum,undef,undef,'.');
10147:             $iscourse = 0;
10148:             if (exists($courses{$cdom.'_'.$cnum})) {
10149:                 $iscourse = 1;
10150:             }
10151:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10152:         }
10153:     }
10154:     return unless ($iscourse);
10155:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10156: }
10157: 
10158: sub store_userdata {
10159:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10160:     my $result;
10161:     if ($datakey ne '') {
10162:         if (ref($storehash) eq 'HASH') {
10163:             if ($udom eq '' || $uname eq '') {
10164:                 $udom = $env{'user.domain'};
10165:                 $uname = $env{'user.name'};
10166:             }
10167:             my $uhome=&homeserver($uname,$udom);
10168:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10169:                 $result = 'error: no_host';
10170:             } else {
10171:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10172:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10173: 
10174:                 my $namevalue='';
10175:                 foreach my $key (keys(%{$storehash})) {
10176:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10177:                 }
10178:                 $namevalue=~s/\&$//;
10179:                 unless ($namespace eq 'courserequests') {
10180:                     $datakey = &escape($datakey);
10181:                 }
10182:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10183:                                   $namevalue,$uhome);
10184:             }
10185:         } else {
10186:             $result = 'error: data to store was not a hash reference'; 
10187:         }
10188:     } else {
10189:         $result= 'error: invalid requestkey'; 
10190:     }
10191:     return $result;
10192: }
10193: 
10194: # ---------------------------------------------------------- Assign Custom Role
10195: 
10196: sub assigncustomrole {
10197:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10198:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10199:                        $end,$start,$deleteflag,$selfenroll,$context);
10200: }
10201: 
10202: # ----------------------------------------------------------------- Revoke Role
10203: 
10204: sub revokerole {
10205:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10206:     my $now=time;
10207:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10208: }
10209: 
10210: # ---------------------------------------------------------- Revoke Custom Role
10211: 
10212: sub revokecustomrole {
10213:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10214:     my $now=time;
10215:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10216:            $deleteflag,$selfenroll,$context);
10217: }
10218: 
10219: # ------------------------------------------------------------ Disk usage
10220: sub diskusage {
10221:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10222:     $directorypath =~ s/\/$//;
10223:     my $listing=&reply('du2:'.&escape($directorypath).':'
10224:                        .&escape($getpropath).':'.&escape($uname).':'
10225:                        .&escape($udom),homeserver($uname,$udom));
10226:     if ($listing eq 'unknown_cmd') {
10227:         if ($getpropath) {
10228:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10229:         }
10230:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10231:     }
10232:     return $listing;
10233: }
10234: 
10235: sub is_locked {
10236:     my ($file_name, $domain, $user, $which) = @_;
10237:     my @check;
10238:     my $is_locked;
10239:     push (@check,$file_name);
10240:     my %locked = &get('file_permissions',\@check,
10241: 		      $env{'user.domain'},$env{'user.name'});
10242:     my ($tmp)=keys(%locked);
10243:     if ($tmp=~/^error:/) { undef(%locked); }
10244:     
10245:     if (ref($locked{$file_name}) eq 'ARRAY') {
10246:         $is_locked = 'false';
10247:         foreach my $entry (@{$locked{$file_name}}) {
10248:            if (ref($entry) eq 'ARRAY') {
10249:                $is_locked = 'true';
10250:                if (ref($which) eq 'ARRAY') {
10251:                    push(@{$which},$entry);
10252:                } else {
10253:                    last;
10254:                }
10255:            }
10256:        }
10257:     } else {
10258:         $is_locked = 'false';
10259:     }
10260:     return $is_locked;
10261: }
10262: 
10263: sub declutter_portfile {
10264:     my ($file) = @_;
10265:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10266:     return $file;
10267: }
10268: 
10269: # ------------------------------------------------------------- Mark as Read Only
10270: 
10271: sub mark_as_readonly {
10272:     my ($domain,$user,$files,$what) = @_;
10273:     my %current_permissions = &dump('file_permissions',$domain,$user);
10274:     my ($tmp)=keys(%current_permissions);
10275:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10276:     foreach my $file (@{$files}) {
10277: 	$file = &declutter_portfile($file);
10278:         push(@{$current_permissions{$file}},$what);
10279:     }
10280:     &put('file_permissions',\%current_permissions,$domain,$user);
10281:     return;
10282: }
10283: 
10284: # ------------------------------------------------------------Save Selected Files
10285: 
10286: sub save_selected_files {
10287:     my ($user, $path, @files) = @_;
10288:     my $filename = $user."savedfiles";
10289:     my @other_files = &files_not_in_path($user, $path);
10290:     open (OUT,'>',LONCAPA::tempdir().$filename);
10291:     foreach my $file (@files) {
10292:         print (OUT $env{'form.currentpath'}.$file."\n");
10293:     }
10294:     foreach my $file (@other_files) {
10295:         print (OUT $file."\n");
10296:     }
10297:     close (OUT);
10298:     return 'ok';
10299: }
10300: 
10301: sub clear_selected_files {
10302:     my ($user) = @_;
10303:     my $filename = $user."savedfiles";
10304:     open (OUT,'>',LONCAPA::tempdir().$filename);
10305:     print (OUT undef);
10306:     close (OUT);
10307:     return ("ok");    
10308: }
10309: 
10310: sub files_in_path {
10311:     my ($user, $path) = @_;
10312:     my $filename = $user."savedfiles";
10313:     my %return_files;
10314:     open (IN,'<',LONCAPA::tempdir().$filename);
10315:     while (my $line_in = <IN>) {
10316:         chomp ($line_in);
10317:         my @paths_and_file = split (m!/!, $line_in);
10318:         my $file_part = pop (@paths_and_file);
10319:         my $path_part = join ('/', @paths_and_file);
10320:         $path_part.='/';
10321:         my $path_and_file = $path_part.$file_part;
10322:         if ($path_part eq $path) {
10323:             $return_files{$file_part}= 'selected';
10324:         }
10325:     }
10326:     close (IN);
10327:     return (\%return_files);
10328: }
10329: 
10330: # called in portfolio select mode, to show files selected NOT in current directory
10331: sub files_not_in_path {
10332:     my ($user, $path) = @_;
10333:     my $filename = $user."savedfiles";
10334:     my @return_files;
10335:     my $path_part;
10336:     open(IN, '<',LONCAPA::tempdir().$filename);
10337:     while (my $line = <IN>) {
10338:         #ok, I know it's clunky, but I want it to work
10339:         my @paths_and_file = split(m|/|, $line);
10340:         my $file_part = pop(@paths_and_file);
10341:         chomp($file_part);
10342:         my $path_part = join('/', @paths_and_file);
10343:         $path_part .= '/';
10344:         my $path_and_file = $path_part.$file_part;
10345:         if ($path_part ne $path) {
10346:             push(@return_files, ($path_and_file));
10347:         }
10348:     }
10349:     close(OUT);
10350:     return (@return_files);
10351: }
10352: 
10353: #------------------------------Submitted/Handedback Portfolio Files Versioning
10354:  
10355: sub portfiles_versioning {
10356:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10357:     my $portfolio_root = '/userfiles/portfolio';
10358:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10359:     foreach my $file (@{$portfiles}) {
10360:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10361:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10362:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10363:         my $getpropath = 1;
10364:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10365:                                              $stu_name,$getpropath);
10366:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10367:         my $new_answer = 
10368:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10369:         if ($new_answer ne 'problem getting file') {
10370:             push(@{$versioned_portfiles}, $directory.$new_answer);
10371:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10372:                               [$symb,$env{'request.course.id'},'graded']);
10373:         }
10374:     }
10375: }
10376: 
10377: sub get_next_version {
10378:     my ($answer_name, $answer_ext, $dir_list) = @_;
10379:     my $version;
10380:     if (ref($dir_list) eq 'ARRAY') {
10381:         foreach my $row (@{$dir_list}) {
10382:             my ($file) = split(/\&/,$row,2);
10383:             my ($file_name,$file_version,$file_ext) =
10384:                 &file_name_version_ext($file);
10385:             if (($file_name eq $answer_name) &&
10386:                 ($file_ext eq $answer_ext)) {
10387:                      # gets here if filename and extension match,
10388:                      # regardless of version
10389:                 if ($file_version ne '') {
10390:                     # a versioned file is found  so save it for later
10391:                     if ($file_version > $version) {
10392:                         $version = $file_version;
10393:                     }
10394:                 }
10395:             }
10396:         }
10397:     }
10398:     $version ++;
10399:     return($version);
10400: }
10401: 
10402: sub version_selected_portfile {
10403:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10404:     my ($answer_name,$answer_ver,$answer_ext) =
10405:         &file_name_version_ext($file_name);
10406:     my $new_answer;
10407:     $env{'form.copy'} =
10408:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10409:     if($env{'form.copy'} eq '-1') {
10410:         $new_answer = 'problem getting file';
10411:     } else {
10412:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10413:         my $copy_result = 
10414:             &finishuserfileupload($stu_name,$domain,'copy',
10415:                                   '/portfolio'.$directory.$new_answer);
10416:     }
10417:     undef($env{'form.copy'});
10418:     return ($new_answer);
10419: }
10420: 
10421: sub file_name_version_ext {
10422:     my ($file)=@_;
10423:     my @file_parts = split(/\./, $file);
10424:     my ($name,$version,$ext);
10425:     if (@file_parts > 1) {
10426:         $ext=pop(@file_parts);
10427:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10428:             $version=pop(@file_parts);
10429:         }
10430:         $name=join('.',@file_parts);
10431:     } else {
10432:         $name=join('.',@file_parts);
10433:     }
10434:     return($name,$version,$ext);
10435: }
10436: 
10437: #----------------------------------------------Get portfolio file permissions
10438: 
10439: sub get_portfile_permissions {
10440:     my ($domain,$user) = @_;
10441:     my %current_permissions = &dump('file_permissions',$domain,$user);
10442:     my ($tmp)=keys(%current_permissions);
10443:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10444:     return \%current_permissions;
10445: }
10446: 
10447: #---------------------------------------------Get portfolio file access controls
10448: 
10449: sub get_access_controls {
10450:     my ($current_permissions,$group,$file) = @_;
10451:     my %access;
10452:     my $real_file = $file;
10453:     $file =~ s/\.meta$//;
10454:     if (defined($file)) {
10455:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10456:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10457:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10458:             }
10459:         }
10460:     } else {
10461:         foreach my $key (keys(%{$current_permissions})) {
10462:             if ($key =~ /\0accesscontrol$/) {
10463:                 if (defined($group)) {
10464:                     if ($key !~ m-^\Q$group\E/-) {
10465:                         next;
10466:                     }
10467:                 }
10468:                 my ($fullpath) = split(/\0/,$key);
10469:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10470:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10471:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10472:                     }
10473:                 }
10474:             }
10475:         }
10476:     }
10477:     return %access;
10478: }
10479: 
10480: sub modify_access_controls {
10481:     my ($file_name,$changes,$domain,$user)=@_;
10482:     my ($outcome,$deloutcome);
10483:     my %store_permissions;
10484:     my %new_values;
10485:     my %new_control;
10486:     my %translation;
10487:     my @deletions = ();
10488:     my $now = time;
10489:     if (exists($$changes{'activate'})) {
10490:         if (ref($$changes{'activate'}) eq 'HASH') {
10491:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10492:             my $numnew = scalar(@newitems);
10493:             for (my $i=0; $i<$numnew; $i++) {
10494:                 my $newkey = $newitems[$i];
10495:                 my $newid = &Apache::loncommon::get_cgi_id();
10496:                 if ($newkey =~ /^\d+:/) { 
10497:                     $newkey =~ s/^(\d+)/$newid/;
10498:                     $translation{$1} = $newid;
10499:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10500:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10501:                     $translation{$1} = $newid;
10502:                 }
10503:                 $new_values{$file_name."\0".$newkey} = 
10504:                                           $$changes{'activate'}{$newitems[$i]};
10505:                 $new_control{$newkey} = $now;
10506:             }
10507:         }
10508:     }
10509:     my %todelete;
10510:     my %changed_items;
10511:     foreach my $action ('delete','update') {
10512:         if (exists($$changes{$action})) {
10513:             if (ref($$changes{$action}) eq 'HASH') {
10514:                 foreach my $key (keys(%{$$changes{$action}})) {
10515:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10516:                     if ($action eq 'delete') { 
10517:                         $todelete{$itemnum} = 1;
10518:                     } else {
10519:                         $changed_items{$itemnum} = $key;
10520:                     }
10521:                 }
10522:             }
10523:         }
10524:     }
10525:     # get lock on access controls for file.
10526:     my $lockhash = {
10527:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10528:                                                        ':'.$env{'user.domain'},
10529:                    }; 
10530:     my $tries = 0;
10531:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10532:    
10533:     while (($gotlock ne 'ok') && $tries < 10) {
10534:         $tries ++;
10535:         sleep(0.1);
10536:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10537:     }
10538:     if ($gotlock eq 'ok') {
10539:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10540:         my ($tmp)=keys(%curr_permissions);
10541:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10542:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10543:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10544:             if (ref($curr_controls) eq 'HASH') {
10545:                 foreach my $control_item (keys(%{$curr_controls})) {
10546:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10547:                     if (defined($todelete{$itemnum})) {
10548:                         push(@deletions,$file_name."\0".$control_item);
10549:                     } else {
10550:                         if (defined($changed_items{$itemnum})) {
10551:                             $new_control{$changed_items{$itemnum}} = $now;
10552:                             push(@deletions,$file_name."\0".$control_item);
10553:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10554:                         } else {
10555:                             $new_control{$control_item} = $$curr_controls{$control_item};
10556:                         }
10557:                     }
10558:                 }
10559:             }
10560:         }
10561:         my ($group);
10562:         if (&is_course($domain,$user)) {
10563:             ($group,my $file) = split(/\//,$file_name,2);
10564:         }
10565:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10566:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10567:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10568:         #  remove lock
10569:         my @del_lock = ($file_name."\0".'locked_access_records');
10570:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10571:         my $sqlresult =
10572:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10573:                                     $group);
10574:     } else {
10575:         $outcome = "error: could not obtain lockfile\n";  
10576:     }
10577:     return ($outcome,$deloutcome,\%new_values,\%translation);
10578: }
10579: 
10580: sub make_public_indefinitely {
10581:     my (@requrl) = @_;
10582:     return &automated_portfile_access('public',\@requrl);
10583: }
10584: 
10585: sub automated_portfile_access {
10586:     my ($accesstype,$addsref,$delsref,$info) = @_;
10587:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10588:         return 'invalid';
10589:     }
10590:     my %urls;
10591:     if (ref($addsref) eq 'ARRAY') {
10592:         foreach my $requrl (@{$addsref}) {
10593:             if (&is_portfolio_url($requrl)) {
10594:                 unless (exists($urls{$requrl})) {
10595:                     $urls{$requrl} = 'add';
10596:                 }
10597:             }
10598:         }
10599:     }
10600:     if (ref($delsref) eq 'ARRAY') {
10601:         foreach my $requrl (@{$delsref}) { 
10602:             if (&is_portfolio_url($requrl)) {
10603:                 unless (exists($urls{$requrl})) {
10604:                     $urls{$requrl} = 'delete'; 
10605:                 }
10606:             }
10607:         }
10608:     }
10609:     unless (keys(%urls)) {
10610:         return 'invalid';
10611:     }
10612:     my $ip;
10613:     if ($accesstype eq 'ip') {
10614:         if (ref($info) eq 'HASH') {
10615:             if ($info->{'ip'} ne '') {
10616:                 $ip = $info->{'ip'};
10617:             }
10618:         }
10619:         if ($ip eq '') {
10620:             return 'invalid';
10621:         }
10622:     }
10623:     my $errors;
10624:     my $now = time;
10625:     my %current_perms;
10626:     foreach my $requrl (sort(keys(%urls))) {
10627:         my $action;
10628:         if ($urls{$requrl} eq 'add') {
10629:             $action = 'activate';
10630:         } else {
10631:             $action = 'none';
10632:         }
10633:         my $aclnum = 0;
10634:         my (undef,$udom,$unum,$file_name,$group) =
10635:             &parse_portfolio_url($requrl);
10636:         unless (exists($current_perms{$unum.':'.$udom})) {
10637:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10638:         }
10639:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10640:                                                    $group,$file_name);
10641:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10642:             my ($num,$scope,$end,$start) = 
10643:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10644:             if ($scope eq $accesstype) {
10645:                 if (($start <= $now) && ($end == 0)) {
10646:                     if ($accesstype eq 'ip') {
10647:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10648:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10649:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10650:                                     if ($urls{$requrl} eq 'add') {
10651:                                         $action = 'none';
10652:                                         last;
10653:                                     } else {
10654:                                         $action = 'delete';
10655:                                         $aclnum = $num;
10656:                                         last;
10657:                                     }
10658:                                 }
10659:                             }
10660:                         }
10661:                     } elsif ($accesstype eq 'public') {
10662:                         if ($urls{$requrl} eq 'add') {
10663:                             $action = 'none';
10664:                             last;
10665:                         } else {
10666:                             $action = 'delete';
10667:                             $aclnum = $num;
10668:                             last;
10669:                         }
10670:                     }
10671:                 } elsif ($accesstype eq 'public') {
10672:                     $action = 'update';
10673:                     $aclnum = $num;
10674:                     last;
10675:                 }
10676:             }
10677:         }
10678:         if ($action eq 'none') {
10679:             next;
10680:         } else {
10681:             my %changes;
10682:             my $newend = 0;
10683:             my $newstart = $now;
10684:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10685:             $changes{$action}{$newkey} = {
10686:                 type => $accesstype,
10687:                 time => {
10688:                     start => $newstart,
10689:                     end   => $newend,
10690:                 },
10691:             };
10692:             if ($accesstype eq 'ip') {
10693:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10694:             }
10695:             my ($outcome,$deloutcome,$new_values,$translation) =
10696:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10697:             unless ($outcome eq 'ok') {
10698:                 $errors .= $outcome.' ';
10699:             }
10700:         }
10701:     }
10702:     if ($errors) {
10703:         $errors =~ s/\s$//;
10704:         return $errors;
10705:     } else {
10706:         return 'ok';
10707:     }
10708: }
10709: 
10710: #------------------------------------------------------Get Marked as Read Only
10711: 
10712: sub get_marked_as_readonly {
10713:     my ($domain,$user,$what,$group) = @_;
10714:     my $current_permissions = &get_portfile_permissions($domain,$user);
10715:     my @readonly_files;
10716:     my $cmp1=$what;
10717:     if (ref($what)) { $cmp1=join('',@{$what}) };
10718:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10719:         if (defined($group)) {
10720:             if ($file_name !~ m-^\Q$group\E/-) {
10721:                 next;
10722:             }
10723:         }
10724:         if (ref($value) eq "ARRAY"){
10725:             foreach my $stored_what (@{$value}) {
10726:                 my $cmp2=$stored_what;
10727:                 if (ref($stored_what) eq 'ARRAY') {
10728:                     $cmp2=join('',@{$stored_what});
10729:                 }
10730:                 if ($cmp1 eq $cmp2) {
10731:                     push(@readonly_files, $file_name);
10732:                     last;
10733:                 } elsif (!defined($what)) {
10734:                     push(@readonly_files, $file_name);
10735:                     last;
10736:                 }
10737:             }
10738:         }
10739:     }
10740:     return @readonly_files;
10741: }
10742: #-----------------------------------------------------------Get Marked as Read Only Hash
10743: 
10744: sub get_marked_as_readonly_hash {
10745:     my ($current_permissions,$group,$what) = @_;
10746:     my %readonly_files;
10747:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10748:         if (defined($group)) {
10749:             if ($file_name !~ m-^\Q$group\E/-) {
10750:                 next;
10751:             }
10752:         }
10753:         if (ref($value) eq "ARRAY"){
10754:             foreach my $stored_what (@{$value}) {
10755:                 if (ref($stored_what) eq 'ARRAY') {
10756:                     foreach my $lock_descriptor(@{$stored_what}) {
10757:                         if ($lock_descriptor eq 'graded') {
10758:                             $readonly_files{$file_name} = 'graded';
10759:                         } elsif ($lock_descriptor eq 'handback') {
10760:                             $readonly_files{$file_name} = 'handback';
10761:                         } else {
10762:                             if (!exists($readonly_files{$file_name})) {
10763:                                 $readonly_files{$file_name} = 'locked';
10764:                             }
10765:                         }
10766:                     }
10767:                 } 
10768:             }
10769:         } 
10770:     }
10771:     return %readonly_files;
10772: }
10773: # ------------------------------------------------------------ Unmark as Read Only
10774: 
10775: sub unmark_as_readonly {
10776:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10777:     # for portfolio submissions, $what contains [$symb,$crsid] 
10778:     my ($domain,$user,$what,$file_name,$group) = @_;
10779:     $file_name = &declutter_portfile($file_name);
10780:     my $symb_crs = $what;
10781:     if (ref($what)) { $symb_crs=join('',@$what); }
10782:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10783:     my ($tmp)=keys(%current_permissions);
10784:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10785:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10786:     foreach my $file (@readonly_files) {
10787: 	my $clean_file = &declutter_portfile($file);
10788: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10789: 	my $current_locks = $current_permissions{$file};
10790:         my @new_locks;
10791:         my @del_keys;
10792:         if (ref($current_locks) eq "ARRAY"){
10793:             foreach my $locker (@{$current_locks}) {
10794:                 my $compare=$locker;
10795:                 if (ref($locker) eq 'ARRAY') {
10796:                     $compare=join('',@{$locker});
10797:                     if ($compare ne $symb_crs) {
10798:                         push(@new_locks, $locker);
10799:                     }
10800:                 }
10801:             }
10802:             if (scalar(@new_locks) > 0) {
10803:                 $current_permissions{$file} = \@new_locks;
10804:             } else {
10805:                 push(@del_keys, $file);
10806:                 &del('file_permissions',\@del_keys, $domain, $user);
10807:                 delete($current_permissions{$file});
10808:             }
10809:         }
10810:     }
10811:     &put('file_permissions',\%current_permissions,$domain,$user);
10812:     return;
10813: }
10814: 
10815: # ------------------------------------------------------------ Directory lister
10816: 
10817: sub dirlist {
10818:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10819:     $uri=~s/^\///;
10820:     $uri=~s/\/$//;
10821:     my ($udom, $uname);
10822:     if ($getuserdir) {
10823:         $udom = $userdomain;
10824:         $uname = $username;
10825:     } else {
10826:         (undef,$udom,$uname)=split(/\//,$uri);
10827:         if(defined($userdomain)) {
10828:             $udom = $userdomain;
10829:         }
10830:         if(defined($username)) {
10831:             $uname = $username;
10832:         }
10833:     }
10834:     my ($dirRoot,$listing,@listing_results);
10835: 
10836:     $dirRoot = $perlvar{'lonDocRoot'};
10837:     if (defined($getpropath)) {
10838:         $dirRoot = &propath($udom,$uname);
10839:         $dirRoot =~ s/\/$//;
10840:     } elsif (defined($getuserdir)) {
10841:         my $subdir=$uname.'__';
10842:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10843:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10844:                    ."/$udom/$subdir/$uname";
10845:     } elsif (defined($alternateRoot)) {
10846:         $dirRoot = $alternateRoot;
10847:     }
10848: 
10849:     if($udom) {
10850:         if($uname) {
10851:             my $uhome = &homeserver($uname,$udom);
10852:             if ($uhome eq 'no_host') {
10853:                 return ([],'no_host');
10854:             }
10855:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10856:                               .$getuserdir.':'.&escape($dirRoot)
10857:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10858:             if ($listing eq 'unknown_cmd') {
10859:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10860:             } else {
10861:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10862:             }
10863:             if ($listing eq 'unknown_cmd') {
10864:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10865:                 @listing_results = split(/:/,$listing);
10866:             } else {
10867:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10868:             }
10869:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10870:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10871:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10872:                 return ([],$listing);
10873:             } else {
10874:                 return (\@listing_results);
10875:             }
10876:         } elsif(!$alternateRoot) {
10877:             my (%allusers,%listerror);
10878: 	    my %servers = &get_servers($udom,'library');
10879:  	    foreach my $tryserver (keys(%servers)) {
10880:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10881:                                   &escape($udom),$tryserver);
10882:                 if ($listing eq 'unknown_cmd') {
10883: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10884: 				      $udom, $tryserver);
10885:                 } else {
10886:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10887:                 }
10888: 		if ($listing eq 'unknown_cmd') {
10889: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10890: 				      $udom, $tryserver);
10891: 		    @listing_results = split(/:/,$listing);
10892: 		} else {
10893: 		    @listing_results =
10894: 			map { &unescape($_); } split(/:/,$listing);
10895: 		}
10896:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10897:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10898:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10899:                     $listerror{$tryserver} = $listing;
10900:                 } else {
10901: 		    foreach my $line (@listing_results) {
10902: 			my ($entry) = split(/&/,$line,2);
10903: 			$allusers{$entry} = 1;
10904: 		    }
10905: 		}
10906:             }
10907:             my @alluserslist=();
10908:             foreach my $user (sort(keys(%allusers))) {
10909:                 push(@alluserslist,$user.'&user');
10910:             }
10911: 
10912:             if (!%listerror) {
10913:                 # no errors
10914:                 return (\@alluserslist);
10915:             } elsif (scalar(keys(%servers)) == 1) {
10916:                 # one library server, one error 
10917:                 my ($key) = keys(%listerror);
10918:                 return (\@alluserslist, $listerror{$key});
10919:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10920:                 # con_lost indicates that we might miss data from at least one
10921:                 # library server
10922:                 return (\@alluserslist, 'con_lost');
10923:             } else {
10924:                 # multiple library servers and no con_lost -> data should be
10925:                 # complete. 
10926:                 return (\@alluserslist);
10927:             }
10928: 
10929:         } else {
10930:             return ([],'missing username');
10931:         }
10932:     } elsif(!defined($getpropath)) {
10933:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10934:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10935:         return (\@all_domains);
10936:     } else {
10937:         return ([],'missing domain');
10938:     }
10939: }
10940: 
10941: # --------------------------------------------- GetFileTimestamp
10942: # This function utilizes dirlist and returns the date stamp for
10943: # when it was last modified.  It will also return an error of -1
10944: # if an error occurs
10945: 
10946: sub GetFileTimestamp {
10947:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10948:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10949:     $studentName   = &LONCAPA::clean_username($studentName);
10950:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10951:                                     undef,$getuserdir);
10952:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10953:         return -1;
10954:     }
10955:     if (ref($fileref) eq 'ARRAY') {
10956:         my @stats = split('&',$fileref->[0]);
10957:         # @stats contains first the filename, then the stat output
10958:         return $stats[10]; # so this is 10 instead of 9.
10959:     } else {
10960:         return -1;
10961:     }
10962: }
10963: 
10964: sub stat_file {
10965:     my ($uri) = @_;
10966:     $uri = &clutter_with_no_wrapper($uri);
10967: 
10968:     my ($udom,$uname,$file);
10969:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10970: 	($udom,$uname,$file) =
10971: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10972: 	$file = 'userfiles/'.$file;
10973:     }
10974:     if ($uri =~ m-^/res/-) {
10975: 	($udom,$uname) = 
10976: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10977: 	$file = $uri;
10978:     }
10979: 
10980:     if (!$udom || !$uname || !$file) {
10981: 	# unable to handle the uri
10982: 	return ();
10983:     }
10984:     my $getpropath;
10985:     if ($file =~ /^userfiles\//) {
10986:         $getpropath = 1;
10987:     }
10988:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10989:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10990:         return ();
10991:     } else {
10992:         if (ref($listref) eq 'ARRAY') {
10993:             my @stats = split('&',$listref->[0]);
10994: 	    shift(@stats); #filename is first
10995: 	    return @stats;
10996:         }
10997:     }
10998:     return ();
10999: }
11000: 
11001: # --------------------------------------------------------- recursedirs
11002: # Recursive function to traverse either a specific user's Authoring Space
11003: # or corresponding Published Resource Space, and populate the hash ref:
11004: # $dirhashref with URLs of all directories, and if $filehashref hash
11005: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11006: # or .rights files in resource space, and .meta, .save, .log, and .bak
11007: # files in Authoring Space.
11008: #
11009: # Inputs:
11010: #
11011: # $is_home - true if current server is home server for user's space
11012: # $context - either: priv, or res respectively for Authoring or Resource Space.
11013: # $docroot - Document root (i.e., /home/httpd/html
11014: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11015: # $relpath - Current path (relative to top level).
11016: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11017: # $filehashref - reference to hash to populate with URLs of files (Optional)
11018: #
11019: # Returns: nothing
11020: #
11021: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11022: #
11023: # Currently used by interface/londocs.pm to create linked select boxes for
11024: # directory and filename to import a Course "Author" resource into a course, and
11025: # also to create linked select boxes for Authoring Space and Directory to choose
11026: # save location for creation of a new "standard" problem from the Course Editor.
11027: #
11028: 
11029: sub recursedirs {
11030:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11031:     return unless (ref($dirhashref) eq 'HASH');
11032:     my $currpath = $docroot.$toppath;
11033:     if ($relpath) {
11034:         $currpath .= "/$relpath";
11035:     }
11036:     my $savefile;
11037:     if (ref($filehashref)) {
11038:         $savefile = 1;
11039:     }
11040:     if ($is_home) {
11041:         if (opendir(my $dirh,$currpath)) {
11042:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11043:                 next if ($item eq '');
11044:                 if (-d "$currpath/$item") {
11045:                     my $newpath;
11046:                     if ($relpath) {
11047:                         $newpath = "$relpath/$item";
11048:                     } else {
11049:                         $newpath = $item;
11050:                     }
11051:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11052:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11053:                 } elsif ($savefile) {
11054:                     if ($context eq 'priv') {
11055:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11056:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11057:                         }
11058:                     } else {
11059:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11060:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11061:                         }
11062:                     }
11063:                 }
11064:             }
11065:             closedir($dirh);
11066:         }
11067:     } else {
11068:         my ($dirlistref,$listerror) =
11069:             &dirlist($toppath.$relpath);
11070:         my @dir_lines;
11071:         my $dirptr=16384;
11072:         if (ref($dirlistref) eq 'ARRAY') {
11073:             foreach my $dir_line (sort
11074:                               {
11075:                                   my ($afile)=split('&',$a,2);
11076:                                   my ($bfile)=split('&',$b,2);
11077:                                   return (lc($afile) cmp lc($bfile));
11078:                               } (@{$dirlistref})) {
11079:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11080:                     split(/\&/,$dir_line,16);
11081:                 $item =~ s/\s+$//;
11082:                 next if (($item =~ /^\.\.?$/) || ($obs));
11083:                 if ($dirptr&$testdir) {
11084:                     my $newpath;
11085:                     if ($relpath) {
11086:                         $newpath = "$relpath/$item";
11087:                     } else {
11088:                         $relpath = '/';
11089:                         $newpath = $item;
11090:                     }
11091:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11092:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11093:                 } elsif ($savefile) {
11094:                     if ($context eq 'priv') {
11095:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11096:                             $filehashref->{$relpath}{$item} = 1;
11097:                         }
11098:                     } else {
11099:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11100:                             $filehashref->{$relpath}{$item} = 1;
11101:                         }
11102:                     }
11103:                 }
11104:             }
11105:         }
11106:     }
11107:     return;
11108: }
11109: 
11110: # -------------------------------------------------------- Value of a Condition
11111: 
11112: # gets the value of a specific preevaluated condition
11113: #    stored in the string  $env{user.state.<cid>}
11114: # or looks up a condition reference in the bighash and if if hasn't
11115: # already been evaluated recurses into docondval to get the value of
11116: # the condition, then memoizing it to 
11117: #   $env{user.state.<cid>.<condition>}
11118: sub directcondval {
11119:     my $number=shift;
11120:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11121: 	&Apache::lonuserstate::evalstate();
11122:     }
11123:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11124: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11125:     } elsif ($number =~ /^_/) {
11126: 	my $sub_condition;
11127: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11128: 		&GDBM_READER(),0640)) {
11129: 	    $sub_condition=$bighash{'conditions'.$number};
11130: 	    untie(%bighash);
11131: 	}
11132: 	my $value = &docondval($sub_condition);
11133: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11134: 	return $value;
11135:     }
11136:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11137:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11138:     } else {
11139:        return 2;
11140:     }
11141: }
11142: 
11143: # get the collection of conditions for this resource
11144: sub condval {
11145:     my $condidx=shift;
11146:     my $allpathcond='';
11147:     foreach my $cond (split(/\|/,$condidx)) {
11148: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11149: 	    $allpathcond.=
11150: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11151: 	}
11152:     }
11153:     $allpathcond=~s/\|$//;
11154:     return &docondval($allpathcond);
11155: }
11156: 
11157: #evaluates an expression of conditions
11158: sub docondval {
11159:     my ($allpathcond) = @_;
11160:     my $result=0;
11161:     if ($env{'request.course.id'}
11162: 	&& defined($allpathcond)) {
11163: 	my $operand='|';
11164: 	my @stack;
11165: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11166: 	    if ($chunk eq '(') {
11167: 		push @stack,($operand,$result);
11168: 	    } elsif ($chunk eq ')') {
11169: 		my $before=pop @stack;
11170: 		if (pop @stack eq '&') {
11171: 		    $result=$result>$before?$before:$result;
11172: 		} else {
11173: 		    $result=$result>$before?$result:$before;
11174: 		}
11175: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11176: 		$operand=$chunk;
11177: 	    } else {
11178: 		my $new=directcondval($chunk);
11179: 		if ($operand eq '&') {
11180: 		    $result=$result>$new?$new:$result;
11181: 		} else {
11182: 		    $result=$result>$new?$result:$new;
11183: 		}
11184: 	    }
11185: 	}
11186:     }
11187:     return $result;
11188: }
11189: 
11190: # ---------------------------------------------------- Devalidate courseresdata
11191: 
11192: sub devalidatecourseresdata {
11193:     my ($coursenum,$coursedomain)=@_;
11194:     my $hashid=$coursenum.':'.$coursedomain;
11195:     &devalidate_cache_new('courseres',$hashid);
11196: }
11197: 
11198: 
11199: # --------------------------------------------------- Course Resourcedata Query
11200: #
11201: #  Parameters:
11202: #      $coursenum    - Number of the course.
11203: #      $coursedomain - Domain at which the course was created.
11204: #  Returns:
11205: #     A hash of the course parameters along (I think) with timestamps
11206: #     and version info.
11207: 
11208: sub get_courseresdata {
11209:     my ($coursenum,$coursedomain)=@_;
11210:     my $coursehom=&homeserver($coursenum,$coursedomain);
11211:     my $hashid=$coursenum.':'.$coursedomain;
11212:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11213:     my %dumpreply;
11214:     unless (defined($cached)) {
11215: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11216: 	$result=\%dumpreply;
11217: 	my ($tmp) = keys(%dumpreply);
11218: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11219: 	    &do_cache_new('courseres',$hashid,$result,600);
11220: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11221: 	    return $tmp;
11222: 	} elsif ($tmp =~ /^(error)/) {
11223: 	    $result=undef;
11224: 	    &do_cache_new('courseres',$hashid,$result,600);
11225: 	}
11226:     }
11227:     return $result;
11228: }
11229: 
11230: sub devalidateuserresdata {
11231:     my ($uname,$udom)=@_;
11232:     my $hashid="$udom:$uname";
11233:     &devalidate_cache_new('userres',$hashid);
11234: }
11235: 
11236: sub get_userresdata {
11237:     my ($uname,$udom)=@_;
11238:     #most student don\'t have any data set, check if there is some data
11239:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11240: 
11241:     my $hashid="$udom:$uname";
11242:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11243:     if (!defined($cached)) {
11244: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11245: 	$result=\%resourcedata;
11246: 	&do_cache_new('userres',$hashid,$result,600);
11247:     }
11248:     my ($tmp)=keys(%$result);
11249:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11250: 	return $result;
11251:     }
11252:     #error 2 occurs when the .db doesn't exist
11253:     if ($tmp!~/error: 2 /) {
11254:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11255: 	    &logthis("<font color=\"blue\">WARNING:".
11256: 		     " Trying to get resource data for ".
11257: 		     $uname." at ".$udom.": ".
11258: 		     $tmp."</font>");
11259:         }
11260:     } elsif ($tmp=~/error: 2 /) {
11261: 	#&EXT_cache_set($udom,$uname);
11262: 	&do_cache_new('userres',$hashid,undef,600);
11263: 	undef($tmp); # not really an error so don't send it back
11264:     }
11265:     return $tmp;
11266: }
11267: #----------------------------------------------- resdata - return resource data
11268: #  Purpose:
11269: #    Return resource data for either users or for a course.
11270: #  Parameters:
11271: #     $name      - Course/user name.
11272: #     $domain    - Name of the domain the user/course is registered on.
11273: #     $type      - Type of thing $name is (must be 'course' or 'user')
11274: #     $mapp      - decluttered URL of enclosing map  
11275: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11276: #     $recurseup - Ref to array of map URLs, starting with map containing
11277: #                  $mapp up through hierarchy of nested maps to top level map.  
11278: #     $courseid  - CourseID (first part of param identifier).
11279: #     $modifier  - Middle part of param identifier.
11280: #     $what      - Last part of param identifier.
11281: #     @which     - Array of names of resources desired.
11282: #  Returns:
11283: #     The value of the first reasource in @which that is found in the
11284: #     resource hash.
11285: #  Exceptional Conditions:
11286: #     If the $type passed in is not valid (not the string 'course' or 
11287: #     'user', an undefined  reference is returned.
11288: #     If none of the resources are found, an undef is returned
11289: sub resdata {
11290:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11291:         $modifier,$what,@which)=@_;
11292:     my $result;
11293:     if ($type eq 'course') {
11294: 	$result=&get_courseresdata($name,$domain);
11295:     } elsif ($type eq 'user') {
11296: 	$result=&get_userresdata($name,$domain);
11297:     }
11298:     if (!ref($result)) { return $result; }    
11299:     foreach my $item (@which) {
11300:         if ($item->[1] eq 'course') {
11301:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11302:                 unless ($$recursed) {
11303:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11304:                     $$recursed = 1;
11305:                 }
11306:                 foreach my $item (@${recurseup}) {
11307:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11308:                     last if (defined($result->{$norecursechk}));
11309:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11310:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11311:                 }
11312:             }
11313:         }
11314:         if (defined($result->{$item->[0]})) {
11315: 	    return [$result->{$item->[0]},$item->[1]];
11316: 	}
11317:     }
11318:     return undef;
11319: }
11320: 
11321: sub get_domain_lti {
11322:     my ($cdom,$context) = @_;
11323:     my ($name,%lti);
11324:     if ($context eq 'consumer') {
11325:         $name = 'ltitools';
11326:     } elsif ($context eq 'provider') {
11327:         $name = 'lti';
11328:     } else {
11329:         return %lti;
11330:     }
11331:     my ($result,$cached)=&is_cached_new($name,$cdom);
11332:     if (defined($cached)) {
11333:         if (ref($result) eq 'HASH') {
11334:             %lti = %{$result};
11335:         }
11336:     } else {
11337:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11338:         if (ref($domconfig{$name}) eq 'HASH') {
11339:             %lti = %{$domconfig{$name}};
11340:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11341:             if (ref($encdomconfig{$name}) eq 'HASH') {
11342:                 foreach my $id (keys(%lti)) {
11343:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11344:                         foreach my $item ('key','secret') {
11345:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11346:                         }
11347:                     }
11348:                 }
11349:             }
11350:         }
11351:         my $cachetime = 24*60*60;
11352:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11353:     }
11354:     return %lti;
11355: }
11356: 
11357: sub get_numsuppfiles {
11358:     my ($cnum,$cdom,$ignorecache)=@_;
11359:     my $hashid=$cnum.':'.$cdom;
11360:     my ($suppcount,$cached);
11361:     unless ($ignorecache) {
11362:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11363:     }
11364:     unless (defined($cached)) {
11365:         my $chome=&homeserver($cnum,$cdom);
11366:         unless ($chome eq 'no_host') {
11367:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11368:             my $suppmap = 'supplemental.sequence';
11369:             ($suppcount,$supptools,$errors) =
11370:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11371:                                                          $supptools,$errors);
11372:         }
11373:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11374:     }
11375:     return $suppcount;
11376: }
11377: 
11378: #
11379: # EXT resource caching routines
11380: #
11381: 
11382: {
11383: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11384: #
11385: # The course for which we cache
11386: my $cachedmapkey='';
11387: # The cached recursive maps for this course
11388: my %cachedmaps=();
11389: # When this was last done
11390: my $cachedmaptime='';
11391: 
11392: sub clear_EXT_cache_status {
11393:     &delenv('cache.EXT.');
11394: }
11395: 
11396: sub EXT_cache_status {
11397:     my ($target_domain,$target_user) = @_;
11398:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11399:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11400:         # We know already the user has no data
11401:         return 1;
11402:     } else {
11403:         return 0;
11404:     }
11405: }
11406: 
11407: sub EXT_cache_set {
11408:     my ($target_domain,$target_user) = @_;
11409:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11410:     #&appenv({$cachename => time});
11411: }
11412: 
11413: # --------------------------------------------------------- Value of a Variable
11414: sub EXT {
11415: 
11416:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11417:     unless ($varname) { return ''; }
11418:     #get real user name/domain, courseid and symb
11419:     my $courseid;
11420:     my $publicuser;
11421:     if ($symbparm) {
11422: 	$symbparm=&get_symb_from_alias($symbparm);
11423:     }
11424:     if (!($uname && $udom)) {
11425:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11426:       if (!$symbparm) {	$symbparm=$cursymb; }
11427:     } else {
11428: 	$courseid=$env{'request.course.id'};
11429:     }
11430:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11431:     my $rest;
11432:     if (defined($therest[0])) {
11433:        $rest=join('.',@therest);
11434:     } else {
11435:        $rest='';
11436:     }
11437: 
11438:     my $qualifierrest=$qualifier;
11439:     if ($rest) { $qualifierrest.='.'.$rest; }
11440:     my $spacequalifierrest=$space;
11441:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11442:     if ($realm eq 'user') {
11443: # --------------------------------------------------------------- user.resource
11444: 	if ($space eq 'resource') {
11445: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11446: 		  || defined($Apache::lonhomework::parsing_a_task))
11447: 		 &&
11448: 		 ($symbparm eq &symbread()) ) {	
11449: 		# if we are in the middle of processing the resource the
11450: 		# get the value we are planning on committing
11451:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11452:                     return $Apache::lonhomework::results{$qualifierrest};
11453:                 } else {
11454:                     return $Apache::lonhomework::history{$qualifierrest};
11455:                 }
11456: 	    } else {
11457: 		my %restored;
11458: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11459: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11460: 		} else {
11461: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11462: 		}
11463: 		return $restored{$qualifierrest};
11464: 	    }
11465: # ----------------------------------------------------------------- user.access
11466:         } elsif ($space eq 'access') {
11467: 	    # FIXME - not supporting calls for a specific user
11468:             return &allowed($qualifier,$rest);
11469: # ------------------------------------------ user.preferences, user.environment
11470:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11471: 	    if (($uname eq $env{'user.name'}) &&
11472: 		($udom eq $env{'user.domain'})) {
11473: 		return $env{join('.',('environment',$qualifierrest))};
11474: 	    } else {
11475: 		my %returnhash;
11476: 		if (!$publicuser) {
11477: 		    %returnhash=&userenvironment($udom,$uname,
11478: 						 $qualifierrest);
11479: 		}
11480: 		return $returnhash{$qualifierrest};
11481: 	    }
11482: # ----------------------------------------------------------------- user.course
11483:         } elsif ($space eq 'course') {
11484: 	    # FIXME - not supporting calls for a specific user
11485:             return $env{join('.',('request.course',$qualifier))};
11486: # ------------------------------------------------------------------- user.role
11487:         } elsif ($space eq 'role') {
11488: 	    # FIXME - not supporting calls for a specific user
11489:             my ($role,$where)=split(/\./,$env{'request.role'});
11490:             if ($qualifier eq 'value') {
11491: 		return $role;
11492:             } elsif ($qualifier eq 'extent') {
11493:                 return $where;
11494:             }
11495: # ----------------------------------------------------------------- user.domain
11496:         } elsif ($space eq 'domain') {
11497:             return $udom;
11498: # ------------------------------------------------------------------- user.name
11499:         } elsif ($space eq 'name') {
11500:             return $uname;
11501: # ---------------------------------------------------- Any other user namespace
11502:         } else {
11503: 	    my %reply;
11504: 	    if (!$publicuser) {
11505: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11506: 	    }
11507: 	    return $reply{$qualifierrest};
11508:         }
11509:     } elsif ($realm eq 'query') {
11510: # ---------------------------------------------- pull stuff out of query string
11511:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11512: 						[$spacequalifierrest]);
11513: 	return $env{'form.'.$spacequalifierrest}; 
11514:    } elsif ($realm eq 'request') {
11515: # ------------------------------------------------------------- request.browser
11516:         if ($space eq 'browser') {
11517:             return $env{'browser.'.$qualifier};
11518: # ------------------------------------------------------------ request.filename
11519:         } else {
11520:             return $env{'request.'.$spacequalifierrest};
11521:         }
11522:     } elsif ($realm eq 'course') {
11523: # ---------------------------------------------------------- course.description
11524:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11525:     } elsif ($realm eq 'resource') {
11526: 
11527: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11528: 	    if (!$symbparm) { $symbparm=&symbread(); }
11529: 	}
11530: 
11531:         if ($qualifier eq '') {
11532: 	    if ($space eq 'title') {
11533: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11534: 	        return &gettitle($symbparm);
11535: 	    }
11536: 	
11537: 	    if ($space eq 'map') {
11538: 	        my ($map) = &decode_symb($symbparm);
11539: 	        return &symbread($map);
11540: 	    }
11541:             if ($space eq 'maptitle') {
11542:                 my ($map) = &decode_symb($symbparm);
11543:                 return &gettitle($map);
11544:             }
11545: 	    if ($space eq 'filename') {
11546: 	        if ($symbparm) {
11547: 		    return &clutter((&decode_symb($symbparm))[2]);
11548: 	        }
11549: 	        return &hreflocation('',$env{'request.filename'});
11550: 	    }
11551: 
11552:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11553:                 if ($space eq 'visibleparts') {
11554:                     my $navmap = Apache::lonnavmaps::navmap->new();
11555:                     my $item;
11556:                     if (ref($navmap)) {
11557:                         my $res = $navmap->getBySymb($symbparm);
11558:                         my $parts = $res->parts();
11559:                         if (ref($parts) eq 'ARRAY') {
11560:                             $item = join(',',@{$parts});
11561:                         }
11562:                         undef($navmap);
11563:                     }
11564:                     return $item;
11565:                 }
11566:             }
11567:         }
11568: 
11569: 	my ($section, $group, @groups, @recurseup, $recursed);
11570: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11571:         if (($courseid eq '') && ($cid)) {
11572:             $courseid = $cid;
11573:         }
11574: 	if (($symbparm && $courseid) && 
11575: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11576: 
11577: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11578: 
11579: # ----------------------------------------------------- Cascading lookup scheme
11580: 	    my $symbp=$symbparm;
11581: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11582: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11583:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11584: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11585: 	    if (($env{'user.name'} eq $uname) &&
11586: 		($env{'user.domain'} eq $udom)) {
11587: 		$section=$env{'request.course.sec'};
11588:                 @groups = split(/:/,$env{'request.course.groups'});  
11589:                 @groups=&sort_course_groups($courseid,@groups); 
11590: 	    } else {
11591: 		if (! defined($usection)) {
11592: 		    $section=&getsection($udom,$uname,$courseid);
11593: 		} else {
11594: 		    $section = $usection;
11595: 		}
11596:                 @groups = &get_users_groups($udom,$uname,$courseid);
11597: 	    }
11598: 
11599: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11600: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11601:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11602: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11603: 
11604: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11605: 	    my $courselevelr=$courseid.'.'.$symbparm;
11606:             $courseleveli=$courseid.'.'.$recurseparm;
11607: 	    $courselevelm=$courseid.'.'.$mapparm;
11608: 
11609: # ----------------------------------------------------------- first, check user
11610: 
11611: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11612:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11613: 				       ([$courselevelr,'resource'],
11614: 					[$courselevelm,'map'     ],
11615:                                         [$courseleveli,'map'     ],
11616: 					[$courselevel, 'course'  ]));
11617: 	    if (defined($userreply)) { return &get_reply($userreply); }
11618: 
11619: # ------------------------------------------------ second, check some of course
11620:             my $coursereply;
11621:             if (@groups > 0) {
11622:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11623:                                        $recurseparm,$mapparm,$spacequalifierrest,
11624:                                        $mapp,\$recursed,\@recurseup);
11625:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11626:             }
11627: 
11628: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11629: 				  $env{'course.'.$courseid.'.domain'},
11630: 				  'course',$mapp,\$recursed,\@recurseup,
11631:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11632: 				  ([$seclevelr,   'resource'],
11633: 				   [$seclevelm,   'map'     ],
11634:                                    [$secleveli,   'map'     ],
11635: 				   [$seclevel,    'course'  ],
11636: 				   [$courselevelr,'resource']));
11637: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11638: 
11639: # ------------------------------------------------------ third, check map parms
11640: 	    my %parmhash=();
11641: 	    my $thisparm='';
11642: 	    if (tie(%parmhash,'GDBM_File',
11643: 		    $env{'request.course.fn'}.'_parms.db',
11644: 		    &GDBM_READER(),0640)) {
11645: 		$thisparm=$parmhash{$symbparm};
11646: 		untie(%parmhash);
11647: 	    }
11648: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11649: 	}
11650: # ------------------------------------------ fourth, look in resource metadata
11651:  
11652:         my $what = $spacequalifierrest;
11653: 	$what=~s/\./\_/;
11654: 	my $filename;
11655: 	if (!$symbparm) { $symbparm=&symbread(); }
11656: 	if ($symbparm) {
11657: 	    $filename=(&decode_symb($symbparm))[2];
11658: 	} else {
11659: 	    $filename=$env{'request.filename'};
11660: 	}
11661:         my $toolsymb;
11662:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11663:             $toolsymb = $symbparm;
11664:         }
11665: 	my $metadata=&metadata($filename,$what,$toolsymb);
11666: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11667: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11668: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11669: 
11670: # ----------------------------------------------- fifth, look in rest of course
11671: 	if ($symbparm && defined($courseid) && 
11672: 	    $courseid eq $env{'request.course.id'}) {
11673: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11674: 				     $env{'course.'.$courseid.'.domain'},
11675: 				     'course',$mapp,\$recursed,\@recurseup,
11676:                                      $courseid,'.',$spacequalifierrest,
11677: 				     ([$courselevelm,'map'   ],
11678:                                       [$courseleveli,'map'   ],
11679: 				      [$courselevel, 'course']));
11680: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11681: 	}
11682: # ------------------------------------------------------------------ Cascade up
11683: 	unless ($space eq '0') {
11684: 	    my @parts=split(/_/,$space);
11685: 	    my $id=pop(@parts);
11686: 	    my $part=join('_',@parts);
11687: 	    if ($part eq '') { $part='0'; }
11688: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11689: 				 $symbparm,$udom,$uname,$section,1);
11690: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11691: 	}
11692: 	if ($recurse) { return undef; }
11693: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11694: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11695: # ---------------------------------------------------- Any other user namespace
11696:     } elsif ($realm eq 'environment') {
11697: # ----------------------------------------------------------------- environment
11698: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11699: 	    return $env{'environment.'.$spacequalifierrest};
11700: 	} else {
11701: 	    if ($uname eq 'anonymous' && $udom eq '') {
11702: 		return '';
11703: 	    }
11704: 	    my %returnhash=&userenvironment($udom,$uname,
11705: 					    $spacequalifierrest);
11706: 	    return $returnhash{$spacequalifierrest};
11707: 	}
11708:     } elsif ($realm eq 'system') {
11709: # ----------------------------------------------------------------- system.time
11710: 	if ($space eq 'time') {
11711: 	    return time;
11712:         }
11713:     } elsif ($realm eq 'server') {
11714: # ----------------------------------------------------------------- system.time
11715: 	if ($space eq 'name') {
11716: 	    return $ENV{'SERVER_NAME'};
11717:         }
11718:     }
11719:     return '';
11720: }
11721: 
11722: sub get_reply {
11723:     my ($reply_value) = @_;
11724:     if (ref($reply_value) eq 'ARRAY') {
11725:         if (wantarray) {
11726: 	    return @$reply_value;
11727:         }
11728:         return $reply_value->[0];
11729:     } else {
11730:         return $reply_value;
11731:     }
11732: }
11733: 
11734: sub check_group_parms {
11735:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11736:         $recursed,$recurseupref) = @_;
11737:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11738:                   [$what,'course']);
11739:     my $coursereply;
11740:     foreach my $group (@{$groups}) {
11741:         my @groupitems = ();
11742:         foreach my $level (@levels) {
11743:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11744:              push(@groupitems,[$item,$level->[1]]);
11745:         }
11746:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11747:                                    $env{'course.'.$courseid.'.domain'},
11748:                                    'course',$mapp,$recursed,$recurseupref,
11749:                                    $courseid,'.['.$group.'].',$what,
11750:                                    @groupitems);
11751:         last if (defined($coursereply));
11752:     }
11753:     return $coursereply;
11754: }
11755: 
11756: sub get_map_hierarchy {
11757:     my ($mapname,$courseid) = @_;
11758:     my @recurseup = ();
11759:     if ($mapname) {
11760:         if (($cachedmapkey eq $courseid) &&
11761:             (abs($cachedmaptime-time)<5)) {
11762:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11763:                 return @{$cachedmaps{$mapname}};
11764:             }
11765:         }
11766:         my $navmap = Apache::lonnavmaps::navmap->new();
11767:         if (ref($navmap)) {
11768:             @recurseup = $navmap->recurseup_maps($mapname);
11769:             undef($navmap);
11770:             $cachedmaps{$mapname} = \@recurseup;
11771:             $cachedmaptime=time;
11772:             $cachedmapkey=$courseid;
11773:         }
11774:     }
11775:     return @recurseup;
11776: }
11777: 
11778: }
11779: 
11780: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11781:     my ($courseid,@groups) = @_;
11782:     @groups = sort(@groups);
11783:     return @groups;
11784: }
11785: 
11786: sub packages_tab_default {
11787:     my ($uri,$varname,$toolsymb)=@_;
11788:     my (undef,$part,$name)=split(/\./,$varname);
11789: 
11790:     my (@extension,@specifics,$do_default);
11791:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11792: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11793: 	if ($pack_type eq 'default') {
11794: 	    $do_default=1;
11795: 	} elsif ($pack_type eq 'extension') {
11796: 	    push(@extension,[$package,$pack_type,$pack_part]);
11797: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11798: 	    # only look at packages defaults for packages that this id is
11799: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11800: 	}
11801:     }
11802:     # first look for a package that matches the requested part id
11803:     foreach my $package (@specifics) {
11804: 	my (undef,$pack_type,$pack_part)=@{$package};
11805: 	next if ($pack_part ne $part);
11806: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11807: 	    return $packagetab{"$pack_type&$name&default"};
11808: 	}
11809:     }
11810:     # look for any possible matching non extension_ package
11811:     foreach my $package (@specifics) {
11812: 	my (undef,$pack_type,$pack_part)=@{$package};
11813: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11814: 	    return $packagetab{"$pack_type&$name&default"};
11815: 	}
11816: 	if ($pack_type eq 'part') { $pack_part='0'; }
11817: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11818: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11819: 	}
11820:     }
11821:     # look for any posible extension_ match
11822:     foreach my $package (@extension) {
11823: 	my ($package,$pack_type)=@{$package};
11824: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11825: 	    return $packagetab{"$pack_type&$name&default"};
11826: 	}
11827: 	if (defined($packagetab{$package."&$name&default"})) {
11828: 	    return $packagetab{$package."&$name&default"};
11829: 	}
11830:     }
11831:     # look for a global default setting
11832:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11833: 	return $packagetab{"default&$name&default"};
11834:     }
11835:     return undef;
11836: }
11837: 
11838: sub add_prefix_and_part {
11839:     my ($prefix,$part)=@_;
11840:     my $keyroot;
11841:     if (defined($prefix) && $prefix !~ /^__/) {
11842: 	# prefix that has a part already
11843: 	$keyroot=$prefix;
11844:     } elsif (defined($prefix)) {
11845: 	# prefix that is missing a part
11846: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11847:     } else {
11848: 	# no prefix at all
11849: 	if (defined($part)) { $keyroot='_'.$part; }
11850:     }
11851:     return $keyroot;
11852: }
11853: 
11854: # ---------------------------------------------------------------- Get metadata
11855: 
11856: my %metaentry;
11857: my %importedpartids;
11858: my %importedrespids;
11859: sub metadata {
11860:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11861:     $uri=&declutter($uri);
11862:     # if it is a non metadata possible uri return quickly
11863:     if (($uri eq '') || 
11864: 	(($uri =~ m|^/*adm/|) && 
11865: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11866:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11867: 	return undef;
11868:     }
11869:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11870: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11871: 	return undef;
11872:     }
11873:     my $filename=$uri;
11874:     $uri=~s/\.meta$//;
11875: #
11876: # Is the metadata already cached?
11877: # Look at timestamp of caching
11878: # Everything is cached by the main uri, libraries are never directly cached
11879: #
11880:     if (!defined($liburi)) {
11881: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11882: 	if (defined($cached)) { return $result->{':'.$what}; }
11883:     }
11884: 
11885: #
11886: # If the uri is for an external tool the file from
11887: # which metadata should be retrieved depends on whether
11888: # the tool had been configured to be gradable (set in the Course
11889: # Editor or Resource Editor).
11890: #
11891: # If a valid symb has been included as the third arg in the call
11892: # to &metadata() that can be used to retrieve the value of
11893: # parameter_0_gradable set for the resource, and included in the
11894: # uploaded map containing the tool. The value is retrieved via
11895: # &EXT(), if a valid symb is available.  Otherwise the value of
11896: # gradable in the exttool_$marker.db file for the tool instance
11897: # is retrieved via &get().
11898: #
11899: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11900: # hiddenresource and encrypturl (during course initialization)
11901: # the map-level parameter for resource.0.gradable included in the 
11902: # uploaded map containing the tool will not yet have been stored
11903: # in the user_course_parms.db file for the user's session, so in 
11904: # this case fall back to retrieving gradable status from the
11905: # exttool_$marker.db file.
11906: #
11907: # In order to avoid an infinite loop, &metadata() will return
11908: # before a call to &EXT(), if the uri is for an external tool
11909: # and the $what for which metadata is being requested is
11910: # parameter_0_gradable or 0_gradable.
11911: #
11912: 
11913:     if ($uri =~ /ext\.tool$/) {
11914:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11915:             return;
11916:         } else {
11917:             my ($checked,$use_passback);
11918:             if ($toolsymb ne '') {
11919:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11920:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11921:                     $checked = 1;
11922:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11923:                         $use_passback = 1;
11924:                     }
11925:                 }
11926:             }
11927:             unless ($checked) {
11928:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11929:                 $marker=~s/\D//g;
11930:                 if ($marker) {
11931:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11932:                     $use_passback = $toolsettings{'gradable'};
11933:                 }
11934:             }
11935:             if ($use_passback) {
11936:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11937:             } else {
11938:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11939:             }
11940:         }
11941:     }
11942: 
11943:     {
11944: # Imported parts would go here
11945:         my @origfiletagids=();
11946:         my $importedparts=0;
11947: 
11948: # Imported responseids would go here
11949:         my $importedresponses=0;
11950: #
11951: # Is this a recursive call for a library?
11952: #
11953: #	if (! exists($metacache{$uri})) {
11954: #	    $metacache{$uri}={};
11955: #	}
11956: 	my $cachetime = 60*60;
11957:         if ($liburi) {
11958: 	    $liburi=&declutter($liburi);
11959:             $filename=$liburi;
11960:         } else {
11961: 	    &devalidate_cache_new('meta',$uri);
11962: 	    undef(%metaentry);
11963: 	}
11964:         my %metathesekeys=();
11965:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11966: 	my $metastring;
11967: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11968: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11969: 	    $metastring = 
11970: 		&Apache::lonnet::ssi_body($which,
11971: 					  ('grade_target' => 'meta'));
11972: 	    $cachetime = 1; # only want this cached in the child not long term
11973: 	} elsif (($uri !~ m -^(editupload)/-) && 
11974:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11975: 	    my $file=&filelocation('',&clutter($filename));
11976: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11977: 	    $metastring=&getfile($file);
11978: 	}
11979:         my $parser=HTML::LCParser->new(\$metastring);
11980:         my $token;
11981:         undef %metathesekeys;
11982:         while ($token=$parser->get_token) {
11983: 	    if ($token->[0] eq 'S') {
11984: 		if (defined($token->[2]->{'package'})) {
11985: #
11986: # This is a package - get package info
11987: #
11988: 		    my $package=$token->[2]->{'package'};
11989: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11990: 		    if (defined($token->[2]->{'id'})) { 
11991: 			$keyroot.='_'.$token->[2]->{'id'}; 
11992: 		    }
11993: 		    if ($metaentry{':packages'}) {
11994: 			$metaentry{':packages'}.=','.$package.$keyroot;
11995: 		    } else {
11996: 			$metaentry{':packages'}=$package.$keyroot;
11997: 		    }
11998: 		    foreach my $pack_entry (keys(%packagetab)) {
11999: 			my $part=$keyroot;
12000: 			$part=~s/^\_//;
12001: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12002: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12003: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12004: 			    # ignore package.tab specified default values
12005:                             # here &package_tab_default() will fetch those
12006: 			    if ($subp eq 'default') { next; }
12007: 			    my $value=$packagetab{$pack_entry};
12008: 			    my $unikey;
12009: 			    if ($pack =~ /_0$/) {
12010: 				$unikey='parameter_0_'.$name;
12011: 				$part=0;
12012: 			    } else {
12013: 				$unikey='parameter'.$keyroot.'_'.$name;
12014: 			    }
12015: 			    if ($subp eq 'display') {
12016: 				$value.=' [Part: '.$part.']';
12017: 			    }
12018: 			    $metaentry{':'.$unikey.'.part'}=$part;
12019: 			    $metathesekeys{$unikey}=1;
12020: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12021: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12022: 			    }
12023: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12024: 				$metaentry{':'.$unikey}=
12025: 				    $metaentry{':'.$unikey.'.default'};
12026: 			    }
12027: 			}
12028: 		    }
12029: 		} else {
12030: #
12031: # This is not a package - some other kind of start tag
12032: #
12033: 		    my $entry=$token->[1];
12034: 		    my $unikey='';
12035: 
12036: 		    if ($entry eq 'import') {
12037: #
12038: # Importing a library here
12039: #
12040:                         my $location=$parser->get_text('/import');
12041:                         my $dir=$filename;
12042:                         $dir=~s|[^/]*$||;
12043:                         $location=&filelocation($dir,$location);
12044: 
12045:                         my $importid=$token->[2]->{'id'};
12046:                         my $importmode=$token->[2]->{'importmode'};
12047: #
12048: # Check metadata for imported file to
12049: # see if it contained response items
12050: #
12051:                         my ($origfile,@libfilekeys);
12052:                         my %currmetaentry = %metaentry;
12053:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12054:                                                            $depthcount+1));
12055:                         if (grep(/^responseorder$/,@libfilekeys)) {
12056:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12057:                                                              undef,$depthcount+1);
12058:                             if ($libresponseorder ne '') {
12059:                                 if ($#origfiletagids<0) {
12060:                                     undef(%importedrespids);
12061:                                     undef(%importedpartids);
12062:                                 }
12063:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12064:                                 if (@respids) {
12065:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12066:                                 }
12067:                                 if ($importedrespids{$importid} ne '') {
12068:                                     $importedresponses = 1;
12069: # We need to get the original file and the imported file to get the response order correct
12070: # Load and inspect original file
12071:                                     if ($#origfiletagids<0) {
12072:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12073:                                         $origfile=&getfile($origfilelocation);
12074:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12075:                                     }
12076:                                 }
12077:                             }
12078:                         }
12079: # Do not overwrite contents of %metaentry hash for resource itself with 
12080: # hash populated for imported library file
12081:                         %metaentry = %currmetaentry;
12082:                         undef(%currmetaentry);
12083:                         if ($importmode eq 'part') {
12084: # Import as part(s)
12085:                            $importedparts=1;
12086: # We need to get the original file and the imported file to get the part order correct
12087: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12088: # Load and inspect original file if we didn't do that already
12089:                            if ($#origfiletagids<0) {
12090:                                undef(%importedrespids);
12091:                                undef(%importedpartids);
12092:                                if ($origfile eq '') {
12093:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12094:                                    $origfile=&getfile($origfilelocation);
12095:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12096:                                }
12097:                            }
12098:                            my @impfilepartids;
12099: # If <partorder> tag is included in metadata for the imported file
12100: # get the parts in the imported file from that.
12101:                            if (grep(/^partorder$/,@libfilekeys)) {
12102:                                %currmetaentry = %metaentry;
12103:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12104:                                                             $depthcount+1);
12105:                                %metaentry = %currmetaentry;
12106:                                undef(%currmetaentry);
12107:                                if ($libpartorder ne '') {
12108:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12109:                                }
12110:                            } else {
12111: # If no <partorder> tag available, load and inspect imported file
12112:                                my $impfile=&getfile($location);
12113:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12114:                            }
12115:                            if ($#impfilepartids>=0) {
12116: # This problem had parts
12117:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12118:                            } else {
12119: # Importing by turning a single problem into a problem part
12120: # It gets the import-tags ID as part-ID
12121:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12122:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12123:                            }
12124:                         } else {
12125: # Import as problem or as normal import
12126:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12127:                             unless ($importmode eq 'problem') {
12128: # Normal import
12129:                                 if (defined($token->[2]->{'id'})) {
12130:                                     $unikey.='_'.$token->[2]->{'id'};
12131:                                 }
12132:                             }
12133: # Check metadata for imported file to
12134: # see if it contained parts
12135:                             if (grep(/^partorder$/,@libfilekeys)) {
12136:                                 %currmetaentry = %metaentry;
12137:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12138:                                                              $depthcount+1);
12139:                                 %metaentry = %currmetaentry;
12140:                                 undef(%currmetaentry);
12141:                                 if ($libpartorder ne '') {
12142:                                     $importedparts = 1;
12143:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12144:                                 }
12145:                             }
12146:                         }
12147: 			if ($depthcount<20) {
12148: 			    my $metadata = 
12149: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12150: 					  $depthcount+1);
12151: 			    foreach my $meta (split(',',$metadata)) {
12152: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12153: 				$metathesekeys{$meta}=1;
12154: 			    }
12155:                         }
12156: 		    } else {
12157: #
12158: # Not importing, some other kind of non-package, non-library start tag
12159: # 
12160:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12161:                         if (defined($token->[2]->{'id'})) {
12162:                             $unikey.='_'.$token->[2]->{'id'};
12163:                         }
12164: 			if (defined($token->[2]->{'name'})) { 
12165: 			    $unikey.='_'.$token->[2]->{'name'}; 
12166: 			}
12167: 			$metathesekeys{$unikey}=1;
12168: 			foreach my $param (@{$token->[3]}) {
12169: 			    $metaentry{':'.$unikey.'.'.$param} =
12170: 				$token->[2]->{$param};
12171: 			}
12172: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12173: 			my $default=$metaentry{':'.$unikey.'.default'};
12174: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12175: 		 # only ws inside the tag, and not in default, so use default
12176: 		 # as value
12177: 			    $metaentry{':'.$unikey}=$default;
12178: 			} elsif ( $internaltext =~ /\S/ ) {
12179: 		  # something interesting inside the tag
12180: 			    $metaentry{':'.$unikey}=$internaltext;
12181: 			} else {
12182: 		  # no interesting values, don't set a default
12183: 			}
12184: # end of not-a-package not-a-library import
12185: 		    }
12186: # end of not-a-package start tag
12187: 		}
12188: # the next is the end of "start tag"
12189: 	    }
12190: 	}
12191: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12192: 	$extension = lc($extension);
12193: 	if ($extension eq 'htm') { $extension='html'; }
12194: 
12195: 	foreach my $key (keys(%packagetab)) {
12196: 	    #no specific packages #how's our extension
12197: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12198: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12199: 					 \%metathesekeys);
12200: 	}
12201: 
12202: 	if (!exists($metaentry{':packages'})
12203: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12204: 	    foreach my $key (keys(%packagetab)) {
12205: 		#no specific packages well let's get default then
12206: 		if ($key!~/^default&/) { next; }
12207: 		&metadata_create_package_def($uri,$key,'default',
12208: 					     \%metathesekeys);
12209: 	    }
12210: 	}
12211: # are there custom rights to evaluate
12212: 	if ($metaentry{':copyright'} eq 'custom') {
12213: 
12214:     #
12215:     # Importing a rights file here
12216:     #
12217: 	    unless ($depthcount) {
12218: 		my $location=$metaentry{':customdistributionfile'};
12219: 		my $dir=$filename;
12220: 		$dir=~s|[^/]*$||;
12221: 		$location=&filelocation($dir,$location);
12222: 		my $rights_metadata =
12223: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12224: 			      $depthcount+1);
12225: 		foreach my $rights (split(',',$rights_metadata)) {
12226: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12227: 		    $metathesekeys{$rights}=1;
12228: 		}
12229: 	    }
12230: 	}
12231: 	# uniqifiy package listing
12232: 	my %seen;
12233: 	my @uniq_packages =
12234: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12235: 	$metaentry{':packages'} = join(',',@uniq_packages);
12236: 
12237:         if (($importedresponses) || ($importedparts)) {
12238:             if ($importedparts) {
12239: # We had imported parts and need to rebuild partorder
12240:                 $metaentry{':partorder'}='';
12241:                 $metathesekeys{'partorder'}=1;
12242:             }
12243:             if ($importedresponses) {
12244: # We had imported responses and need to rebuil responseorder
12245:                 $metaentry{':responseorder'}='';
12246:                 $metathesekeys{'responseorder'}=1;
12247:             }
12248:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12249:                 my $origid = $origfiletagids[$index+1];
12250:                 if ($origfiletagids[$index] eq 'part') {
12251: # Original part, part of the problem
12252:                     if ($importedparts) {
12253:                         $metaentry{':partorder'}.=','.$origid;
12254:                     }
12255:                 } elsif ($origfiletagids[$index] eq 'import') {
12256:                     if ($importedparts) {
12257: # We have imported parts at this position
12258:                         if ($importedpartids{$origid} ne '') {
12259:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12260:                         }
12261:                     }
12262:                     if ($importedresponses) {
12263: # We have imported responses at this position
12264:                         if ($importedrespids{$origid} ne '') {
12265:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12266:                         }
12267:                     }
12268:                 } else {
12269: # Original response item, part of the problem
12270:                     if ($importedresponses) {
12271:                         $metaentry{':responseorder'}.=','.$origid;
12272:                     }
12273:                 }
12274:             }
12275:             if ($importedparts) {
12276:                 $metaentry{':partorder'}=~s/^\,//;
12277:             }
12278:             if ($importedresponses) {
12279:                 $metaentry{':responseorder'}=~s/^\,//;
12280:             }
12281:         }
12282: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12283: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12284: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12285:         unless ($liburi) {
12286: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12287:         }
12288: # this is the end of "was not already recently cached
12289:     }
12290:     return $metaentry{':'.$what};
12291: }
12292: 
12293: sub metadata_create_package_def {
12294:     my ($uri,$key,$package,$metathesekeys)=@_;
12295:     my ($pack,$name,$subp)=split(/\&/,$key);
12296:     if ($subp eq 'default') { next; }
12297:     
12298:     if (defined($metaentry{':packages'})) {
12299: 	$metaentry{':packages'}.=','.$package;
12300:     } else {
12301: 	$metaentry{':packages'}=$package;
12302:     }
12303:     my $value=$packagetab{$key};
12304:     my $unikey;
12305:     $unikey='parameter_0_'.$name;
12306:     $metaentry{':'.$unikey.'.part'}=0;
12307:     $$metathesekeys{$unikey}=1;
12308:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12309: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12310:     }
12311:     if (defined($metaentry{':'.$unikey.'.default'})) {
12312: 	$metaentry{':'.$unikey}=
12313: 	    $metaentry{':'.$unikey.'.default'};
12314:     }
12315: }
12316: 
12317: sub metadata_generate_part0 {
12318:     my ($metadata,$metacache,$uri) = @_;
12319:     my %allnames;
12320:     foreach my $metakey (keys(%$metadata)) {
12321: 	if ($metakey=~/^parameter\_(.*)/) {
12322: 	  my $part=$$metacache{':'.$metakey.'.part'};
12323: 	  my $name=$$metacache{':'.$metakey.'.name'};
12324: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12325: 	    $allnames{$name}=$part;
12326: 	  }
12327: 	}
12328:     }
12329:     foreach my $name (keys(%allnames)) {
12330:       $$metadata{"parameter_0_$name"}=1;
12331:       my $key=":parameter_0_$name";
12332:       $$metacache{"$key.part"}='0';
12333:       $$metacache{"$key.name"}=$name;
12334:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12335: 					   $allnames{$name}.'_'.$name.
12336: 					   '.type'};
12337:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12338: 			     '.display'};
12339:       my $expr='[Part: '.$allnames{$name}.']';
12340:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12341:       $$metacache{"$key.display"}=$olddis;
12342:     }
12343: }
12344: 
12345: # ------------------------------------------------------ Devalidate title cache
12346: 
12347: sub devalidate_title_cache {
12348:     my ($url)=@_;
12349:     if (!$env{'request.course.id'}) { return; }
12350:     my $symb=&symbread($url);
12351:     if (!$symb) { return; }
12352:     my $key=$env{'request.course.id'}."\0".$symb;
12353:     &devalidate_cache_new('title',$key);
12354: }
12355: 
12356: # ------------------------------------------------- Get the title of a course
12357: 
12358: sub current_course_title {
12359:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12360: }
12361: # ------------------------------------------------- Get the title of a resource
12362: 
12363: sub gettitle {
12364:     my $urlsymb=shift;
12365:     my $symb=&symbread($urlsymb);
12366:     if ($symb) {
12367: 	my $key=$env{'request.course.id'}."\0".$symb;
12368: 	my ($result,$cached)=&is_cached_new('title',$key);
12369: 	if (defined($cached)) { 
12370: 	    return $result;
12371: 	}
12372: 	my ($map,$resid,$url)=&decode_symb($symb);
12373: 	my $title='';
12374: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12375: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12376: 	} else {
12377: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12378: 		    &GDBM_READER(),0640)) {
12379: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12380: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12381: 		untie(%bighash);
12382: 	    }
12383: 	}
12384: 	$title=~s/\&colon\;/\:/gs;
12385: 	if ($title) {
12386: # Remember both $symb and $title for dynamic metadata
12387:             $accesshash{$symb.'___crstitle'}=$title;
12388:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12389: # Cache this title and then return it
12390: 	    return &do_cache_new('title',$key,$title,600);
12391: 	}
12392: 	$urlsymb=$url;
12393:     }
12394:     my $title=&metadata($urlsymb,'title');
12395:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12396:     return $title;
12397: }
12398: 
12399: sub get_slot {
12400:     my ($which,$cnum,$cdom)=@_;
12401:     if (!$cnum || !$cdom) {
12402: 	(undef,my $courseid)=&whichuser();
12403: 	$cdom=$env{'course.'.$courseid.'.domain'};
12404: 	$cnum=$env{'course.'.$courseid.'.num'};
12405:     }
12406:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12407:     my %slotinfo;
12408:     if (exists($remembered{$key})) {
12409: 	$slotinfo{$which} = $remembered{$key};
12410:     } else {
12411: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12412: 	&Apache::lonhomework::showhash(%slotinfo);
12413: 	my ($tmp)=keys(%slotinfo);
12414: 	if ($tmp=~/^error:/) { return (); }
12415: 	$remembered{$key} = $slotinfo{$which};
12416:     }
12417:     if (ref($slotinfo{$which}) eq 'HASH') {
12418: 	return %{$slotinfo{$which}};
12419:     }
12420:     return $slotinfo{$which};
12421: }
12422: 
12423: sub get_reservable_slots {
12424:     my ($cnum,$cdom,$uname,$udom) = @_;
12425:     my $now = time;
12426:     my $reservable_info;
12427:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12428:     if (exists($remembered{$key})) {
12429:         $reservable_info = $remembered{$key};
12430:     } else {
12431:         my %resv;
12432:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12433:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12434:         $reservable_info = \%resv;
12435:         $remembered{$key} = $reservable_info;
12436:     }
12437:     return $reservable_info;
12438: }
12439: 
12440: sub get_course_slots {
12441:     my ($cnum,$cdom) = @_;
12442:     my $hashid=$cnum.':'.$cdom;
12443:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12444:     if (defined($cached)) {
12445:         if (ref($result) eq 'HASH') {
12446:             return %{$result};
12447:         }
12448:     } else {
12449:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12450:         my ($tmp) = keys(%slots);
12451:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12452:             &do_cache_new('allslots',$hashid,\%slots,600);
12453:             return %slots;
12454:         }
12455:     }
12456:     return;
12457: }
12458: 
12459: sub devalidate_slots_cache {
12460:     my ($cnum,$cdom)=@_;
12461:     my $hashid=$cnum.':'.$cdom;
12462:     &devalidate_cache_new('allslots',$hashid);
12463: }
12464: 
12465: sub get_coursechange {
12466:     my ($cdom,$cnum) = @_;
12467:     if ($cdom eq '' || $cnum eq '') {
12468:         return unless ($env{'request.course.id'});
12469:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12470:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12471:     }
12472:     my $hashid=$cdom.'_'.$cnum;
12473:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12474:     if ((defined($cached)) && ($change ne '')) {
12475:         return $change;
12476:     } else {
12477:         my %crshash;
12478:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12479:         if ($crshash{'internal.contentchange'} eq '') {
12480:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12481:             if ($change eq '') {
12482:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12483:                 $change = $crshash{'internal.created'};
12484:             }
12485:         } else {
12486:             $change = $crshash{'internal.contentchange'};
12487:         }
12488:         my $cachetime = 600;
12489:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12490:     }
12491:     return $change;
12492: }
12493: 
12494: sub devalidate_coursechange_cache {
12495:     my ($cnum,$cdom)=@_;
12496:     my $hashid=$cnum.':'.$cdom;
12497:     &devalidate_cache_new('crschange',$hashid);
12498: }
12499: 
12500: # ------------------------------------------------- Update symbolic store links
12501: 
12502: sub symblist {
12503:     my ($mapname,%newhash)=@_;
12504:     $mapname=&deversion(&declutter($mapname));
12505:     my %hash;
12506:     if (($env{'request.course.fn'}) && (%newhash)) {
12507:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12508:                       &GDBM_WRCREAT(),0640)) {
12509: 	    foreach my $url (keys(%newhash)) {
12510: 		next if ($url eq 'last_known'
12511: 			 && $env{'form.no_update_last_known'});
12512: 		$hash{declutter($url)}=&encode_symb($mapname,
12513: 						    $newhash{$url}->[1],
12514: 						    $newhash{$url}->[0]);
12515:             }
12516:             if (untie(%hash)) {
12517: 		return 'ok';
12518:             }
12519:         }
12520:     }
12521:     return 'error';
12522: }
12523: 
12524: # --------------------------------------------------------------- Verify a symb
12525: 
12526: sub symbverify {
12527:     my ($symb,$thisurl,$encstate)=@_;
12528:     my $thisfn=$thisurl;
12529:     $thisfn=&declutter($thisfn);
12530: # direct jump to resource in page or to a sequence - will construct own symbs
12531:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12532: # check URL part
12533:     my ($map,$resid,$url)=&decode_symb($symb);
12534: 
12535:     unless ($url eq $thisfn) { return 0; }
12536: 
12537:     $symb=&symbclean($symb);
12538:     $thisurl=&deversion($thisurl);
12539:     $thisfn=&deversion($thisfn);
12540: 
12541:     my %bighash;
12542:     my $okay=0;
12543: 
12544:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12545:                             &GDBM_READER(),0640)) {
12546:         my $noclutter;
12547:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12548:             $thisurl =~ s/\?.+$//;
12549:             if ($map =~ m{^uploaded/.+\.page$}) {
12550:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12551:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12552:                 $noclutter = 1;
12553:             }
12554:         }
12555:         my $ids;
12556:         if ($noclutter) {
12557:             $ids=$bighash{'ids_'.$thisurl};
12558:         } else {
12559:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12560:         }
12561:         unless ($ids) {
12562:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12563:             $ids=$bighash{$idkey};
12564:         }
12565:         if ($ids) {
12566: # ------------------------------------------------------------------- Has ID(s)
12567:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12568:                 $symb =~ s/\?.+$//;
12569:             }
12570: 	    foreach my $id (split(/\,/,$ids)) {
12571: 	       my ($mapid,$resid)=split(/\./,$id);
12572:                if (
12573:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12574:    eq $symb) {
12575:                    if (ref($encstate)) {
12576:                        $$encstate = $bighash{'encrypted_'.$id};
12577:                    }
12578: 		   if (($env{'request.role.adv'}) ||
12579: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12580:                        ($thisurl eq '/adm/navmaps')) {
12581: 		       $okay=1;
12582:                        last;
12583: 		   }
12584: 	       }
12585: 	   }
12586:         }
12587: 	untie(%bighash);
12588:     }
12589:     return $okay;
12590: }
12591: 
12592: # --------------------------------------------------------------- Clean-up symb
12593: 
12594: sub symbclean {
12595:     my $symb=shift;
12596:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12597: # remove version from map
12598:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12599: 
12600: # remove version from URL
12601:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12602: 
12603: # remove wrapper
12604: 
12605:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12606:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12607:     return $symb;
12608: }
12609: 
12610: # ---------------------------------------------- Split symb to find map and url
12611: 
12612: sub encode_symb {
12613:     my ($map,$resid,$url)=@_;
12614:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12615: }
12616: 
12617: sub decode_symb {
12618:     my $symb=shift;
12619:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12620:     my ($map,$resid,$url)=split(/___/,$symb);
12621:     return (&fixversion($map),$resid,&fixversion($url));
12622: }
12623: 
12624: sub fixversion {
12625:     my $fn=shift;
12626:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12627:     my %bighash;
12628:     my $uri=&clutter($fn);
12629:     my $key=$env{'request.course.id'}.'_'.$uri;
12630: # is this cached?
12631:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12632:     if (defined($cached)) { return $result; }
12633: # unfortunately not cached, or expired
12634:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12635: 	    &GDBM_READER(),0640)) {
12636:  	if ($bighash{'version_'.$uri}) {
12637:  	    my $version=$bighash{'version_'.$uri};
12638:  	    unless (($version eq 'mostrecent') || 
12639: 		    ($version==&getversion($uri))) {
12640:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12641:  	    }
12642:  	}
12643:  	untie %bighash;
12644:     }
12645:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12646: }
12647: 
12648: sub deversion {
12649:     my $url=shift;
12650:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12651:     return $url;
12652: }
12653: 
12654: # ------------------------------------------------------ Return symb list entry
12655: 
12656: sub symbread {
12657:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12658:     my $cache_str='request.symbread.cached.'.$thisfn;
12659:     if (defined($env{$cache_str})) {
12660:         if ($ignorecachednull) {
12661:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12662:         } else {
12663:             return $env{$cache_str};
12664:         }
12665:     }
12666: # no filename provided? try from environment
12667:     unless ($thisfn) {
12668:         if ($env{'request.symb'}) {
12669: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12670: 	}
12671: 	$thisfn=$env{'request.filename'};
12672:     }
12673:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12674: # is that filename actually a symb? Verify, clean, and return
12675:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12676: 	if (&symbverify($thisfn,$1)) {
12677: 	    return $env{$cache_str}=&symbclean($thisfn);
12678: 	}
12679:     }
12680:     $thisfn=declutter($thisfn);
12681:     my %hash;
12682:     my %bighash;
12683:     my $syval='';
12684:     if (($env{'request.course.fn'}) && ($thisfn)) {
12685:         my $targetfn = $thisfn;
12686:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12687:             $targetfn = 'adm/wrapper/'.$thisfn;
12688:         }
12689: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12690: 	    $targetfn=$1;
12691: 	}
12692:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12693:                       &GDBM_READER(),0640)) {
12694: 	    $syval=$hash{$targetfn};
12695:             untie(%hash);
12696:         }
12697: # ---------------------------------------------------------- There was an entry
12698:         if ($syval) {
12699: 	    #unless ($syval=~/\_\d+$/) {
12700: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12701: 		    #&appenv({'request.ambiguous' => $thisfn});
12702: 		    #return $env{$cache_str}='';
12703: 		#}    
12704: 		#$syval.=$1;
12705: 	    #}
12706:         } else {
12707: # ------------------------------------------------------- Was not in symb table
12708:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12709:                             &GDBM_READER(),0640)) {
12710: # ---------------------------------------------- Get ID(s) for current resource
12711:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12712:               unless ($ids) { 
12713:                  $ids=$bighash{'ids_/'.$thisfn};
12714:               }
12715:               unless ($ids) {
12716: # alias?
12717: 		  $ids=$bighash{'mapalias_'.$thisfn};
12718:               }
12719:               if ($ids) {
12720: # ------------------------------------------------------------------- Has ID(s)
12721:                  my @possibilities=split(/\,/,$ids);
12722:                  if ($#possibilities==0) {
12723: # ----------------------------------------------- There is only one possibility
12724: 		     my ($mapid,$resid)=split(/\./,$ids);
12725: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12726: 						    $resid,$thisfn);
12727:                      if (ref($possibles) eq 'HASH') {
12728:                          $possibles->{$syval} = 1;    
12729:                      }
12730:                      if ($checkforblock) {
12731:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12732:                          if (@blockers) {
12733:                              $syval = '';
12734:                              return;
12735:                          }
12736:                      }
12737:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12738: # ------------------------------------------ There is more than one possibility
12739:                      my $realpossible=0;
12740:                      foreach my $id (@possibilities) {
12741: 			 my $file=$bighash{'src_'.$id};
12742:                          my $canaccess;
12743:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12744:                              $canaccess = 1;
12745:                          } else { 
12746:                              $canaccess = &allowed('bre',$file);
12747:                          }
12748:                          if ($canaccess) {
12749:          		     my ($mapid,$resid)=split(/\./,$id);
12750:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12751:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12752: 						             $resid,$thisfn);
12753:                                  if (ref($possibles) eq 'HASH') {
12754:                                      $possibles->{$syval} = 1;
12755:                                  }
12756:                                  if ($checkforblock) {
12757:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12758:                                      unless (@blockers > 0) {
12759:                                          $syval = $poss_syval;
12760:                                          $realpossible++;
12761:                                      }
12762:                                  } else {
12763:                                      $syval = $poss_syval;
12764:                                      $realpossible++;
12765:                                  }
12766:                              }
12767: 			 }
12768:                      }
12769: 		     if ($realpossible!=1) { $syval=''; }
12770:                  } else {
12771:                      $syval='';
12772:                  }
12773: 	      }
12774:               untie(%bighash);
12775:            }
12776:         }
12777:         if ($syval) {
12778: 	    return $env{$cache_str}=$syval;
12779:         }
12780:     }
12781:     &appenv({'request.ambiguous' => $thisfn});
12782:     return $env{$cache_str}='';
12783: }
12784: 
12785: # ---------------------------------------------------------- Return random seed
12786: 
12787: sub numval {
12788:     my $txt=shift;
12789:     $txt=~tr/A-J/0-9/;
12790:     $txt=~tr/a-j/0-9/;
12791:     $txt=~tr/K-T/0-9/;
12792:     $txt=~tr/k-t/0-9/;
12793:     $txt=~tr/U-Z/0-5/;
12794:     $txt=~tr/u-z/0-5/;
12795:     $txt=~s/\D//g;
12796:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12797:     return int($txt);
12798: }
12799: 
12800: sub numval2 {
12801:     my $txt=shift;
12802:     $txt=~tr/A-J/0-9/;
12803:     $txt=~tr/a-j/0-9/;
12804:     $txt=~tr/K-T/0-9/;
12805:     $txt=~tr/k-t/0-9/;
12806:     $txt=~tr/U-Z/0-5/;
12807:     $txt=~tr/u-z/0-5/;
12808:     $txt=~s/\D//g;
12809:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12810:     my $total;
12811:     foreach my $val (@txts) { $total+=$val; }
12812:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12813:     return int($total);
12814: }
12815: 
12816: sub numval3 {
12817:     use integer;
12818:     my $txt=shift;
12819:     $txt=~tr/A-J/0-9/;
12820:     $txt=~tr/a-j/0-9/;
12821:     $txt=~tr/K-T/0-9/;
12822:     $txt=~tr/k-t/0-9/;
12823:     $txt=~tr/U-Z/0-5/;
12824:     $txt=~tr/u-z/0-5/;
12825:     $txt=~s/\D//g;
12826:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12827:     my $total;
12828:     foreach my $val (@txts) { $total+=$val; }
12829:     if ($_64bit) { $total=(($total<<32)>>32); }
12830:     return $total;
12831: }
12832: 
12833: sub digest {
12834:     my ($data)=@_;
12835:     my $digest=&Digest::MD5::md5($data);
12836:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12837:     my ($e,$f);
12838:     {
12839:         use integer;
12840:         $e=($a+$b);
12841:         $f=($c+$d);
12842:         if ($_64bit) {
12843:             $e=(($e<<32)>>32);
12844:             $f=(($f<<32)>>32);
12845:         }
12846:     }
12847:     if (wantarray) {
12848: 	return ($e,$f);
12849:     } else {
12850: 	my $g;
12851: 	{
12852: 	    use integer;
12853: 	    $g=($e+$f);
12854: 	    if ($_64bit) {
12855: 		$g=(($g<<32)>>32);
12856: 	    }
12857: 	}
12858: 	return $g;
12859:     }
12860: }
12861: 
12862: sub latest_rnd_algorithm_id {
12863:     return '64bit5';
12864: }
12865: 
12866: sub get_rand_alg {
12867:     my ($courseid)=@_;
12868:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12869:     if ($courseid) {
12870: 	return $env{"course.$courseid.rndseed"};
12871:     }
12872:     return &latest_rnd_algorithm_id();
12873: }
12874: 
12875: sub validCODE {
12876:     my ($CODE)=@_;
12877:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12878:     return 0;
12879: }
12880: 
12881: sub getCODE {
12882:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12883:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12884: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12885: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12886: 	return $Apache::lonhomework::history{'resource.CODE'};
12887:     }
12888:     return undef;
12889: }
12890: #
12891: #  Determines the random seed for a specific context:
12892: #
12893: # parameters:
12894: #   symb      - in course context the symb for the seed.
12895: #   course_id - The course id of the form domain_coursenum.
12896: #   domain    - Domain for the user.
12897: #   course    - Course for the user.
12898: #   cenv      - environment of the course.
12899: #
12900: # NOTE:
12901: #   All parameters are picked out of the environment if missing
12902: #   or not defined.
12903: #   If a symb cannot be determined the current time is used instead.
12904: #
12905: #  For a given well defined symb, courside, domain, username,
12906: #  and course environment, the seed is reproducible.
12907: #
12908: sub rndseed {
12909:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12910:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12911:     if (!defined($symb)) {
12912: 	unless ($symb=$wsymb) { return time; }
12913:     }
12914:     if (!defined $courseid) { 
12915: 	$courseid=$wcourseid; 
12916:     }
12917:     if (!defined $domain) { $domain=$wdomain; }
12918:     if (!defined $username) { $username=$wusername }
12919: 
12920:     my $which;
12921:     if (defined($cenv->{'rndseed'})) {
12922: 	$which = $cenv->{'rndseed'};
12923:     } else {
12924: 	$which =&get_rand_alg($courseid);
12925:     }
12926:     if (defined(&getCODE())) {
12927: 
12928: 	if ($which eq '64bit5') {
12929: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12930: 	} elsif ($which eq '64bit4') {
12931: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12932: 	} else {
12933: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12934: 	}
12935:     } elsif ($which eq '64bit5') {
12936: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12937:     } elsif ($which eq '64bit4') {
12938: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12939:     } elsif ($which eq '64bit3') {
12940: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12941:     } elsif ($which eq '64bit2') {
12942: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12943:     } elsif ($which eq '64bit') {
12944: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12945:     }
12946:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12947: }
12948: 
12949: sub rndseed_32bit {
12950:     my ($symb,$courseid,$domain,$username)=@_;
12951:     {
12952: 	use integer;
12953: 	my $symbchck=unpack("%32C*",$symb) << 27;
12954: 	my $symbseed=numval($symb) << 22;
12955: 	my $namechck=unpack("%32C*",$username) << 17;
12956: 	my $nameseed=numval($username) << 12;
12957: 	my $domainseed=unpack("%32C*",$domain) << 7;
12958: 	my $courseseed=unpack("%32C*",$courseid);
12959: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12960: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12961: 	#&logthis("rndseed :$num:$symb");
12962: 	if ($_64bit) { $num=(($num<<32)>>32); }
12963: 	return $num;
12964:     }
12965: }
12966: 
12967: sub rndseed_64bit {
12968:     my ($symb,$courseid,$domain,$username)=@_;
12969:     {
12970: 	use integer;
12971: 	my $symbchck=unpack("%32S*",$symb) << 21;
12972: 	my $symbseed=numval($symb) << 10;
12973: 	my $namechck=unpack("%32S*",$username);
12974: 	
12975: 	my $nameseed=numval($username) << 21;
12976: 	my $domainseed=unpack("%32S*",$domain) << 10;
12977: 	my $courseseed=unpack("%32S*",$courseid);
12978: 	
12979: 	my $num1=$symbchck+$symbseed+$namechck;
12980: 	my $num2=$nameseed+$domainseed+$courseseed;
12981: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12982: 	#&logthis("rndseed :$num:$symb");
12983: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12984: 	return "$num1,$num2";
12985:     }
12986: }
12987: 
12988: sub rndseed_64bit2 {
12989:     my ($symb,$courseid,$domain,$username)=@_;
12990:     {
12991: 	use integer;
12992: 	# strings need to be an even # of cahracters long, it it is odd the
12993:         # last characters gets thrown away
12994: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12995: 	my $symbseed=numval($symb) << 10;
12996: 	my $namechck=unpack("%32S*",$username.' ');
12997: 	
12998: 	my $nameseed=numval($username) << 21;
12999: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13000: 	my $courseseed=unpack("%32S*",$courseid.' ');
13001: 	
13002: 	my $num1=$symbchck+$symbseed+$namechck;
13003: 	my $num2=$nameseed+$domainseed+$courseseed;
13004: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13005: 	#&logthis("rndseed :$num:$symb");
13006: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13007: 	return "$num1,$num2";
13008:     }
13009: }
13010: 
13011: sub rndseed_64bit3 {
13012:     my ($symb,$courseid,$domain,$username)=@_;
13013:     {
13014: 	use integer;
13015: 	# strings need to be an even # of cahracters long, it it is odd the
13016:         # last characters gets thrown away
13017: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13018: 	my $symbseed=numval2($symb) << 10;
13019: 	my $namechck=unpack("%32S*",$username.' ');
13020: 	
13021: 	my $nameseed=numval2($username) << 21;
13022: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13023: 	my $courseseed=unpack("%32S*",$courseid.' ');
13024: 	
13025: 	my $num1=$symbchck+$symbseed+$namechck;
13026: 	my $num2=$nameseed+$domainseed+$courseseed;
13027: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13028: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13029: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13030: 	
13031: 	return "$num1:$num2";
13032:     }
13033: }
13034: 
13035: sub rndseed_64bit4 {
13036:     my ($symb,$courseid,$domain,$username)=@_;
13037:     {
13038: 	use integer;
13039: 	# strings need to be an even # of cahracters long, it it is odd the
13040:         # last characters gets thrown away
13041: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13042: 	my $symbseed=numval3($symb) << 10;
13043: 	my $namechck=unpack("%32S*",$username.' ');
13044: 	
13045: 	my $nameseed=numval3($username) << 21;
13046: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13047: 	my $courseseed=unpack("%32S*",$courseid.' ');
13048: 	
13049: 	my $num1=$symbchck+$symbseed+$namechck;
13050: 	my $num2=$nameseed+$domainseed+$courseseed;
13051: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13052: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13053: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13054: 	
13055: 	return "$num1:$num2";
13056:     }
13057: }
13058: 
13059: sub rndseed_64bit5 {
13060:     my ($symb,$courseid,$domain,$username)=@_;
13061:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13062:     return "$num1:$num2";
13063: }
13064: 
13065: sub rndseed_CODE_64bit {
13066:     my ($symb,$courseid,$domain,$username)=@_;
13067:     {
13068: 	use integer;
13069: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13070: 	my $symbseed=numval2($symb);
13071: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13072: 	my $CODEseed=numval(&getCODE());
13073: 	my $courseseed=unpack("%32S*",$courseid.' ');
13074: 	my $num1=$symbseed+$CODEchck;
13075: 	my $num2=$CODEseed+$courseseed+$symbchck;
13076: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13077: 	#&logthis("rndseed :$num1:$num2:$symb");
13078: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13079: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13080: 	return "$num1:$num2";
13081:     }
13082: }
13083: 
13084: sub rndseed_CODE_64bit4 {
13085:     my ($symb,$courseid,$domain,$username)=@_;
13086:     {
13087: 	use integer;
13088: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13089: 	my $symbseed=numval3($symb);
13090: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13091: 	my $CODEseed=numval3(&getCODE());
13092: 	my $courseseed=unpack("%32S*",$courseid.' ');
13093: 	my $num1=$symbseed+$CODEchck;
13094: 	my $num2=$CODEseed+$courseseed+$symbchck;
13095: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13096: 	#&logthis("rndseed :$num1:$num2:$symb");
13097: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13098: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13099: 	return "$num1:$num2";
13100:     }
13101: }
13102: 
13103: sub rndseed_CODE_64bit5 {
13104:     my ($symb,$courseid,$domain,$username)=@_;
13105:     my $code = &getCODE();
13106:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13107:     return "$num1:$num2";
13108: }
13109: 
13110: sub setup_random_from_rndseed {
13111:     my ($rndseed)=@_;
13112:     if ($rndseed =~/([,:])/) {
13113:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13114:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13115:             &Math::Random::random_set_seed_from_phrase($rndseed);
13116:         } else {
13117:             &Math::Random::random_set_seed($num1,$num2);
13118:         }
13119:     } else {
13120: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13121:     }
13122: }
13123: 
13124: sub latest_receipt_algorithm_id {
13125:     return 'receipt3';
13126: }
13127: 
13128: sub recunique {
13129:     my $fucourseid=shift;
13130:     my $unique;
13131:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13132: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13133: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13134:     } else {
13135: 	$unique=$perlvar{'lonReceipt'};
13136:     }
13137:     return unpack("%32C*",$unique);
13138: }
13139: 
13140: sub recprefix {
13141:     my $fucourseid=shift;
13142:     my $prefix;
13143:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13144: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13145: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13146:     } else {
13147: 	$prefix=$perlvar{'lonHostID'};
13148:     }
13149:     return unpack("%32C*",$prefix);
13150: }
13151: 
13152: sub ireceipt {
13153:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13154: 
13155:     my $return =&recprefix($fucourseid).'-';
13156: 
13157:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13158: 	$env{'request.state'} eq 'construct') {
13159: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13160: 	return $return;
13161:     }
13162: 
13163:     my $cuname=unpack("%32C*",$funame);
13164:     my $cudom=unpack("%32C*",$fudom);
13165:     my $cucourseid=unpack("%32C*",$fucourseid);
13166:     my $cusymb=unpack("%32C*",$fusymb);
13167:     my $cunique=&recunique($fucourseid);
13168:     my $cpart=unpack("%32S*",$part);
13169:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13170: 
13171: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13172: 			       
13173: 	$return.= ($cunique%$cuname+
13174: 		   $cunique%$cudom+
13175: 		   $cusymb%$cuname+
13176: 		   $cusymb%$cudom+
13177: 		   $cucourseid%$cuname+
13178: 		   $cucourseid%$cudom+
13179: 		   $cpart%$cuname+
13180: 		   $cpart%$cudom);
13181:     } else {
13182: 	$return.= ($cunique%$cuname+
13183: 		   $cunique%$cudom+
13184: 		   $cusymb%$cuname+
13185: 		   $cusymb%$cudom+
13186: 		   $cucourseid%$cuname+
13187: 		   $cucourseid%$cudom);
13188:     }
13189:     return $return;
13190: }
13191: 
13192: sub receipt {
13193:     my ($part)=@_;
13194:     my ($symb,$courseid,$domain,$name) = &whichuser();
13195:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13196: }
13197: 
13198: sub whichuser {
13199:     my ($passedsymb)=@_;
13200:     my ($symb,$courseid,$domain,$name,$publicuser);
13201:     if (defined($env{'form.grade_symb'})) {
13202: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13203: 	my $allowed=&allowed('vgr',$tmp_courseid);
13204: 	if (!$allowed &&
13205: 	    exists($env{'request.course.sec'}) &&
13206: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13207: 	    $allowed=&allowed('vgr',$tmp_courseid.
13208: 			      '/'.$env{'request.course.sec'});
13209: 	}
13210: 	if ($allowed) {
13211: 	    ($symb)=&get_env_multiple('form.grade_symb');
13212: 	    $courseid=$tmp_courseid;
13213: 	    ($domain)=&get_env_multiple('form.grade_domain');
13214: 	    ($name)=&get_env_multiple('form.grade_username');
13215: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13216: 	}
13217:     }
13218:     if (!$passedsymb) {
13219: 	$symb=&symbread();
13220:     } else {
13221: 	$symb=$passedsymb;
13222:     }
13223:     $courseid=$env{'request.course.id'};
13224:     $domain=$env{'user.domain'};
13225:     $name=$env{'user.name'};
13226:     if ($name eq 'public' && $domain eq 'public') {
13227: 	if (!defined($env{'form.username'})) {
13228: 	    $env{'form.username'}.=time.rand(10000000);
13229: 	}
13230: 	$name.=$env{'form.username'};
13231:     }
13232:     return ($symb,$courseid,$domain,$name,$publicuser);
13233: 
13234: }
13235: 
13236: # ------------------------------------------------------------ Serves up a file
13237: # returns either the contents of the file or 
13238: # -1 if the file doesn't exist
13239: #
13240: # if the target is a file that was uploaded via DOCS, 
13241: # a check will be made to see if a current copy exists on the local server,
13242: # if it does this will be served, otherwise a copy will be retrieved from
13243: # the home server for the course and stored in /home/httpd/html/userfiles on
13244: # the local server.   
13245: 
13246: sub getfile {
13247:     my ($file) = @_;
13248:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13249:     &repcopy($file);
13250:     return &readfile($file);
13251: }
13252: 
13253: sub repcopy_userfile {
13254:     my ($file)=@_;
13255:     my $londocroot = $perlvar{'lonDocRoot'};
13256:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13257:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13258:     my ($cdom,$cnum,$filename) = 
13259: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13260:     my $uri="/uploaded/$cdom/$cnum/$filename";
13261:     if (-e "$file") {
13262: # we already have a local copy, check it out
13263: 	my @fileinfo = stat($file);
13264: 	my $rtncode;
13265: 	my $info;
13266: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13267: 	if ($lwpresp ne 'ok') {
13268: # there is no such file anymore, even though we had a local copy
13269: 	    if ($rtncode eq '404') {
13270: 		unlink($file);
13271: 	    }
13272: 	    return -1;
13273: 	}
13274: 	if ($info < $fileinfo[9]) {
13275: # nice, the file we have is up-to-date, just say okay
13276: 	    return 'ok';
13277: 	} else {
13278: # the file is outdated, get rid of it
13279: 	    unlink($file);
13280: 	}
13281:     }
13282: # one way or the other, at this point, we don't have the file
13283: # construct the correct path for the file
13284:     my @parts = ($cdom,$cnum); 
13285:     if ($filename =~ m|^(.+)/[^/]+$|) {
13286: 	push @parts, split(/\//,$1);
13287:     }
13288:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13289:     foreach my $part (@parts) {
13290: 	$path .= '/'.$part;
13291: 	if (!-e $path) {
13292: 	    mkdir($path,0770);
13293: 	}
13294:     }
13295: # now the path exists for sure
13296: # get a user agent
13297:     my $transferfile=$file.'.in.transfer';
13298: # FIXME: this should flock
13299:     if (-e $transferfile) { return 'ok'; }
13300:     my $request;
13301:     $uri=~s/^\///;
13302:     my $homeserver = &homeserver($cnum,$cdom);
13303:     my $protocol = $protocol{$homeserver};
13304:     $protocol = 'http' if ($protocol ne 'https');
13305:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13306:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13307: # did it work?
13308:     if ($response->is_error()) {
13309: 	unlink($transferfile);
13310: 	&logthis("Userfile repcopy failed for $uri");
13311: 	return -1;
13312:     }
13313: # worked, rename the transfer file
13314:     rename($transferfile,$file);
13315:     return 'ok';
13316: }
13317: 
13318: sub tokenwrapper {
13319:     my $uri=shift;
13320:     $uri=~s|^https?\://([^/]+)||;
13321:     $uri=~s|^/||;
13322:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13323:     my $token=$1;
13324:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13325:     if ($udom && $uname && $file) {
13326: 	$file=~s|(\?\.*)*$||;
13327:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13328:         my $homeserver = &homeserver($uname,$udom);
13329:         my $protocol = $protocol{$homeserver};
13330:         $protocol = 'http' if ($protocol ne 'https');
13331:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13332:                (($uri=~/\?/)?'&':'?').'token='.$token.
13333:                                '&tokenissued='.$perlvar{'lonHostID'};
13334:     } else {
13335:         return '/adm/notfound.html';
13336:     }
13337: }
13338: 
13339: # call with reqtype HEAD: get last modification time
13340: # call with reqtype GET: get the file contents
13341: # Do not call this with reqtype GET for large files! It loads everything into memory
13342: #
13343: sub getuploaded {
13344:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13345:     $uri=~s/^\///;
13346:     my $homeserver = &homeserver($cnum,$cdom);
13347:     my $protocol = $protocol{$homeserver};
13348:     $protocol = 'http' if ($protocol ne 'https');
13349:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13350:     my $request=new HTTP::Request($reqtype,$uri);
13351:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13352:     $$rtncode = $response->code;
13353:     if (! $response->is_success()) {
13354: 	return 'failed';
13355:     }      
13356:     if ($reqtype eq 'HEAD') {
13357: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13358:     } elsif ($reqtype eq 'GET') {
13359: 	$$info = $response->content;
13360:     }
13361:     return 'ok';
13362: }
13363: 
13364: sub readfile {
13365:     my $file = shift;
13366:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13367:     my $fh;
13368:     open($fh,"<",$file);
13369:     my $a='';
13370:     while (my $line = <$fh>) { $a .= $line; }
13371:     return $a;
13372: }
13373: 
13374: sub filelocation {
13375:     my ($dir,$file) = @_;
13376:     my $location;
13377:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13378: 
13379:     if ($file =~ m-^/adm/-) {
13380: 	$file=~s-^/adm/wrapper/-/-;
13381: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13382:     }
13383: 
13384:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13385:         $location = $file;
13386:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13387:         my ($udom,$uname,$filename)=
13388:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13389:         my $home=&homeserver($uname,$udom);
13390:         my $is_me=0;
13391:         my @ids=&current_machine_ids();
13392:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13393:         if ($is_me) {
13394:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13395:         } else {
13396:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13397:   	      $udom.'/'.$uname.'/'.$filename;
13398:         }
13399:     } elsif ($file =~ m-^/adm/-) {
13400: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13401:     } else {
13402:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13403:         $file=~s:^/(res|priv)/:/:;
13404:         my $space=$1;
13405:         if ( !( $file =~ m:^/:) ) {
13406:             $location = $dir. '/'.$file;
13407:         } else {
13408:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13409:         }
13410:     }
13411:     $location=~s://+:/:g; # remove duplicate /
13412:     while ($location=~m{/\.\./}) {
13413: 	if ($location =~ m{/[^/]+/\.\./}) {
13414: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13415: 	} else {
13416: 	    $location=~ s{/\.\./}{/}g;
13417: 	}
13418:     } #remove dir/..
13419:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13420:     return $location;
13421: }
13422: 
13423: sub hreflocation {
13424:     my ($dir,$file)=@_;
13425:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13426: 	$file=filelocation($dir,$file);
13427:     } elsif ($file=~m-^/adm/-) {
13428: 	$file=~s-^/adm/wrapper/-/-;
13429: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13430:     }
13431:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13432: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13433:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13434: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13435: 	        {/uploaded/$1/$2/}x;
13436:     }
13437:     if ($file=~ m{^/userfiles/}) {
13438: 	$file =~ s{^/userfiles/}{/uploaded/};
13439:     }
13440:     return $file;
13441: }
13442: 
13443: 
13444: 
13445: 
13446: 
13447: sub current_machine_domains {
13448:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13449: }
13450: 
13451: sub machine_domains {
13452:     my ($hostname) = @_;
13453:     my @domains;
13454:     my %hostname = &all_hostnames();
13455:     while( my($id, $name) = each(%hostname)) {
13456: #	&logthis("-$id-$name-$hostname-");
13457: 	if ($hostname eq $name) {
13458: 	    push(@domains,&host_domain($id));
13459: 	}
13460:     }
13461:     return @domains;
13462: }
13463: 
13464: sub current_machine_ids {
13465:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13466: }
13467: 
13468: sub machine_ids {
13469:     my ($hostname) = @_;
13470:     $hostname ||= &hostname($perlvar{'lonHostID'});
13471:     my @ids;
13472:     my %name_to_host = &all_names();
13473:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13474: 	return @{ $name_to_host{$hostname} };
13475:     }
13476:     return;
13477: }
13478: 
13479: sub additional_machine_domains {
13480:     my @domains;
13481:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13482:     while( my $line = <$fh>) {
13483:         $line =~ s/\s//g;
13484:         push(@domains,$line);
13485:     }
13486:     return @domains;
13487: }
13488: 
13489: sub default_login_domain {
13490:     my $domain = $perlvar{'lonDefDomain'};
13491:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13492:     foreach my $posdom (&current_machine_domains(),
13493:                         &additional_machine_domains()) {
13494:         if (lc($posdom) eq lc($testdomain)) {
13495:             $domain=$posdom;
13496:             last;
13497:         }
13498:     }
13499:     return $domain;
13500: }
13501: 
13502: # ------------------------------------------------------------- Declutters URLs
13503: 
13504: sub declutter {
13505:     my $thisfn=shift;
13506:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13507:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13508:         $thisfn=~s{^/home/httpd/html}{};
13509:     }
13510:     $thisfn=~s/^\///;
13511:     $thisfn=~s|^adm/wrapper/||;
13512:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13513:     $thisfn=~s/^res\///;
13514:     $thisfn=~s/^priv\///;
13515:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13516:         $thisfn=~s/\?.+$//;
13517:     }
13518:     return $thisfn;
13519: }
13520: 
13521: # ------------------------------------------------------------- Clutter up URLs
13522: 
13523: sub clutter {
13524:     my $thisfn='/'.&declutter(shift);
13525:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13526: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13527:        $thisfn='/res'.$thisfn; 
13528:     }
13529:     if ($thisfn !~m|^/adm|) {
13530: 	if ($thisfn =~ m|^/ext/|) {
13531: 	    $thisfn='/adm/wrapper'.$thisfn;
13532: 	} else {
13533: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13534: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13535: 	    if ($embstyle eq 'ssi'
13536: 		|| ($embstyle eq 'hdn')
13537: 		|| ($embstyle eq 'rat')
13538: 		|| ($embstyle eq 'prv')
13539: 		|| ($embstyle eq 'ign')) {
13540: 		#do nothing with these
13541: 	    } elsif (($embstyle eq 'img') 
13542: 		|| ($embstyle eq 'emb')
13543: 		|| ($embstyle eq 'wrp')) {
13544: 		$thisfn='/adm/wrapper'.$thisfn;
13545: 	    } elsif ($embstyle eq 'unk'
13546: 		     && $thisfn!~/\.(sequence|page)$/) {
13547: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13548: 	    } else {
13549: #		&logthis("Got a blank emb style");
13550: 	    }
13551: 	}
13552:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13553:         $thisfn='/adm/wrapper'.$thisfn;
13554:     }
13555:     return $thisfn;
13556: }
13557: 
13558: sub clutter_with_no_wrapper {
13559:     my $uri = &clutter(shift);
13560:     if ($uri =~ m-^/adm/-) {
13561: 	$uri =~ s-^/adm/wrapper/-/-;
13562: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13563:     }
13564:     return $uri;
13565: }
13566: 
13567: sub freeze_escape {
13568:     my ($value)=@_;
13569:     if (ref($value)) {
13570: 	$value=&nfreeze($value);
13571: 	return '__FROZEN__'.&escape($value);
13572:     }
13573:     return &escape($value);
13574: }
13575: 
13576: 
13577: sub thaw_unescape {
13578:     my ($value)=@_;
13579:     if ($value =~ /^__FROZEN__/) {
13580: 	substr($value,0,10,undef);
13581: 	$value=&unescape($value);
13582: 	return &thaw($value);
13583:     }
13584:     return &unescape($value);
13585: }
13586: 
13587: sub correct_line_ends {
13588:     my ($result)=@_;
13589:     $$result =~s/\r\n/\n/mg;
13590:     $$result =~s/\r/\n/mg;
13591: }
13592: # ================================================================ Main Program
13593: 
13594: sub goodbye {
13595:    &logthis("Starting Shut down");
13596: #not converted to using infrastruture and probably shouldn't be
13597:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13598: #converted
13599: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13600:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13601: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13602: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13603: #1.1 only
13604: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13605: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13606: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13607: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13608:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13609:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13610:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13611:    &flushcourselogs();
13612:    &logthis("Shutting down");
13613: }
13614: 
13615: sub get_dns {
13616:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13617:     if (!$ignore_cache) {
13618: 	my ($content,$cached)=
13619: 	    &Apache::lonnet::is_cached_new('dns',$url);
13620: 	if ($cached) {
13621: 	    &$func($content,$hashref);
13622: 	    return;
13623: 	}
13624:     }
13625: 
13626:     my %alldns;
13627:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13628:         foreach my $dns (<$config>) {
13629: 	    next if ($dns !~ /^\^(\S*)/x);
13630:             my $line = $1;
13631:             my ($host,$protocol) = split(/:/,$line);
13632:             if ($protocol ne 'https') {
13633:                 $protocol = 'http';
13634:             }
13635: 	    $alldns{$host} = $protocol;
13636:         }
13637:         close($config);
13638:     }
13639:     while (%alldns) {
13640: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13641: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13642:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13643:         delete($alldns{$dns});
13644: 	next if ($response->is_error());
13645:         if ($url eq '/adm/dns/loncapaCRL') {
13646:             return &$func($response);
13647:         } else {
13648: 	    my @content = split("\n",$response->content);
13649: 	    unless ($nocache) {
13650: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13651: 	    }
13652: 	    &$func(\@content,$hashref);
13653:             return;
13654:         }
13655:     }
13656:     my $which = (split('/',$url,4))[3];
13657:     if ($which eq 'loncapaCRL') {
13658:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13659:         if (-e $diskfile) {
13660:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13661:         } else {
13662:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13663:         }
13664:     } else {
13665:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13666:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13667:             my @content = <$config>;
13668:             close($config);
13669:             &$func(\@content,$hashref);
13670:         }
13671:     }
13672:     return;
13673: }
13674: 
13675: # ------------------------------------------------------Get DNS checksums file
13676: sub parse_dns_checksums_tab {
13677:     my ($lines,$hashref) = @_;
13678:     my $lonhost = $perlvar{'lonHostID'};
13679:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13680:     my $loncaparev = &get_server_loncaparev($machine_dom);
13681:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13682:     my $webconfdir = '/etc/httpd/conf';
13683:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13684:         $webconfdir = '/etc/apache2';
13685:     } elsif ($distro =~ /^sles(\d+)$/) {
13686:         if ($1 >= 10) {
13687:             $webconfdir = '/etc/apache2';
13688:         }
13689:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13690:         if ($1 >= 10.0) {
13691:             $webconfdir = '/etc/apache2';
13692:         }
13693:     }
13694:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13695:     my (%chksum,%revnum);
13696:     if (ref($lines) eq 'ARRAY') {
13697:         chomp(@{$lines});
13698:         my $version = shift(@{$lines});
13699:         if ($version eq $release) {  
13700:             foreach my $line (@{$lines}) {
13701:                 my ($file,$version,$shasum) = split(/,/,$line);
13702:                 if ($file =~ m{^/etc/httpd/conf}) {
13703:                     if ($webconfdir eq '/etc/apache2') {
13704:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13705:                     }
13706:                 }
13707:                 $chksum{$file} = $shasum;
13708:                 $revnum{$file} = $version;
13709:             }
13710:             if (ref($hashref) eq 'HASH') {
13711:                 %{$hashref} = (
13712:                                 sums     => \%chksum,
13713:                                 versions => \%revnum,
13714:                               );
13715:             }
13716:         }
13717:     }
13718:     return;
13719: }
13720: 
13721: sub fetch_dns_checksums {
13722:     my %checksums;
13723:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13724:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13725:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13726:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13727:              \%checksums);
13728:     return \%checksums;
13729: }
13730: 
13731: sub fetch_crl_pemfile {
13732:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
13733: }
13734: 
13735: sub save_crl_pem {
13736:     my ($response) = @_;
13737:     my ($msg,$hadchanges);
13738:     if (ref($response)) {
13739:         my $now = time;
13740:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
13741:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
13742:         if (open(my $fh,'>',"$tmpcrl")) {
13743:             print $fh $response->content;
13744:             close($fh);
13745:             if (-e $lonca) {
13746:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
13747:                     my $check = <PIPE>;
13748:                     close(PIPE);
13749:                     chomp($check);
13750:                     if ($check eq 'verify OK') {
13751:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13752:                         my $backup;
13753:                         if (-e $dest) {
13754:                             if (&File::Copy::move($dest,"$dest.bak")) {
13755:                                 $backup = 'ok';
13756:                             }
13757:                         }
13758:                         if (&File::Copy::move($tmpcrl,$dest)) {
13759:                             $msg = 'ok';
13760:                             if ($backup) {
13761:                                 my (%oldnums,%newnums);
13762:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
13763:                                     while (<PIPE>) {
13764:                                         $oldnums{(split(/:/))[1]} = 1;
13765:                                     }
13766:                                     close(PIPE);
13767:                                 }
13768:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
13769:                                     while(<PIPE>) {
13770:                                         $newnums{(split(/:/))[1]} = 1;
13771:                                     }
13772:                                     close(PIPE);
13773:                                 }
13774:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
13775:                                     unless (exists($oldnums{$key})) {
13776:                                         $hadchanges = 1;
13777:                                         last;
13778:                                     }
13779:                                 }
13780:                                 unless ($hadchanges) {
13781:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
13782:                                         unless (exists($newnums{$key})) {
13783:                                             $hadchanges = 1;
13784:                                             last;
13785:                                         }
13786:                                     }
13787:                                 }
13788:                             }
13789:                         }
13790:                     } else {
13791:                         unlink($tmpcrl);
13792:                     }
13793:                 } else {
13794:                     unlink($tmpcrl);
13795:                 }
13796:             } else {
13797:                 unlink($tmpcrl);
13798:             }
13799:         }
13800:     }
13801:     return ($msg,$hadchanges);
13802: }
13803: 
13804: # ------------------------------------------------------------ Read domain file
13805: {
13806:     my $loaded;
13807:     my %domain;
13808: 
13809:     sub parse_domain_tab {
13810: 	my ($lines) = @_;
13811: 	foreach my $line (@$lines) {
13812: 	    next if ($line =~ /^(\#|\s*$ )/x);
13813: 
13814: 	    chomp($line);
13815: 	    my ($name,@elements) = split(/:/,$line,9);
13816: 	    my %this_domain;
13817: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13818: 			       'lang_def', 'city', 'longi', 'lati',
13819: 			       'primary') {
13820: 		$this_domain{$field} = shift(@elements);
13821: 	    }
13822: 	    $domain{$name} = \%this_domain;
13823: 	}
13824:     }
13825: 
13826:     sub reset_domain_info {
13827: 	undef($loaded);
13828: 	undef(%domain);
13829:     }
13830: 
13831:     sub load_domain_tab {
13832: 	my ($ignore_cache,$nocache) = @_;
13833: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13834: 	my $fh;
13835: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13836: 	    my @lines = <$fh>;
13837: 	    &parse_domain_tab(\@lines);
13838: 	}
13839: 	close($fh);
13840: 	$loaded = 1;
13841:     }
13842: 
13843:     sub domain {
13844: 	&load_domain_tab() if (!$loaded);
13845: 
13846: 	my ($name,$what) = @_;
13847: 	return if ( !exists($domain{$name}) );
13848: 
13849: 	if (!$what) {
13850: 	    return $domain{$name}{'description'};
13851: 	}
13852: 	return $domain{$name}{$what};
13853:     }
13854: 
13855:     sub domain_info {
13856:         &load_domain_tab() if (!$loaded);
13857:         return %domain;
13858:     }
13859: 
13860: }
13861: 
13862: 
13863: # ------------------------------------------------------------- Read hosts file
13864: {
13865:     my %hostname;
13866:     my %hostdom;
13867:     my %libserv;
13868:     my $loaded;
13869:     my %name_to_host;
13870:     my %internetdom;
13871:     my %LC_dns_serv;
13872: 
13873:     sub parse_hosts_tab {
13874: 	my ($file) = @_;
13875: 	foreach my $configline (@$file) {
13876: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13877:             chomp($configline);
13878: 	    if ($configline =~ /^\^/) {
13879:                 if ($configline =~ /^\^([\w.\-]+)/) {
13880:                     $LC_dns_serv{$1} = 1;
13881:                 }
13882:                 next;
13883:             }
13884: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13885: 	    $name=~s/\s//g;
13886: 	    if ($id && $domain && $role && $name) {
13887:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13888:                     my $curr = $hostname{$id};
13889:                     my $skip;
13890:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13891:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13892:                             $skip = 1;
13893:                         } else {
13894:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13895:                         }
13896:                     }
13897:                     unless ($skip) {
13898:                         push(@{$name_to_host{$name}},$id);
13899:                     }
13900:                 } else {
13901:                     push(@{$name_to_host{$name}},$id);
13902:                 }
13903: 		$hostname{$id}=$name;
13904: 		$hostdom{$id}=$domain;
13905: 		if ($role eq 'library') { $libserv{$id}=$name; }
13906:                 if (defined($protocol)) {
13907:                     if ($protocol eq 'https') {
13908:                         $protocol{$id} = $protocol;
13909:                     } else {
13910:                         $protocol{$id} = 'http'; 
13911:                     }
13912:                 } else {
13913:                     $protocol{$id} = 'http';
13914:                 }
13915:                 if (defined($intdom)) {
13916:                     $internetdom{$id} = $intdom;
13917:                 }
13918: 	    }
13919: 	}
13920:     }
13921:     
13922:     sub reset_hosts_info {
13923: 	&purge_remembered();
13924: 	&reset_domain_info();
13925: 	&reset_hosts_ip_info();
13926:         undef(%internetdom);
13927: 	undef(%name_to_host);
13928: 	undef(%hostname);
13929: 	undef(%hostdom);
13930: 	undef(%libserv);
13931: 	undef($loaded);
13932:     }
13933: 
13934:     sub load_hosts_tab {
13935: 	my ($ignore_cache,$nocache) = @_;
13936: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13937: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13938: 	my @config = <$config>;
13939: 	&parse_hosts_tab(\@config);
13940: 	close($config);
13941: 	$loaded=1;
13942:     }
13943: 
13944:     sub hostname {
13945: 	&load_hosts_tab() if (!$loaded);
13946: 
13947: 	my ($lonid) = @_;
13948: 	return $hostname{$lonid};
13949:     }
13950: 
13951:     sub all_hostnames {
13952: 	&load_hosts_tab() if (!$loaded);
13953: 
13954: 	return %hostname;
13955:     }
13956: 
13957:     sub all_names {
13958:         my ($ignore_cache,$nocache) = @_;
13959: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13960: 
13961: 	return %name_to_host;
13962:     }
13963: 
13964:     sub all_host_domain {
13965:         &load_hosts_tab() if (!$loaded);
13966:         return %hostdom;
13967:     }
13968: 
13969:     sub all_host_intdom {
13970:         &load_hosts_tab() if (!$loaded);
13971:         return %internetdom;
13972:     }
13973: 
13974:     sub is_library {
13975: 	&load_hosts_tab() if (!$loaded);
13976: 
13977: 	return exists($libserv{$_[0]});
13978:     }
13979: 
13980:     sub all_library {
13981: 	&load_hosts_tab() if (!$loaded);
13982: 
13983: 	return %libserv;
13984:     }
13985: 
13986:     sub unique_library {
13987: 	#2x reverse removes all hostnames that appear more than once
13988:         my %unique = reverse &all_library();
13989:         return reverse %unique;
13990:     }
13991: 
13992:     sub get_servers {
13993: 	&load_hosts_tab() if (!$loaded);
13994: 
13995: 	my ($domain,$type) = @_;
13996: 	my %possible_hosts = ($type eq 'library') ? %libserv
13997: 	                                          : %hostname;
13998: 	my %result;
13999: 	if (ref($domain) eq 'ARRAY') {
14000: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14001: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14002: 		    $result{$host} = $hostname;
14003: 		}
14004: 	    }
14005: 	} else {
14006: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14007: 		if ($hostdom{$host} eq $domain) {
14008: 		    $result{$host} = $hostname;
14009: 		}
14010: 	    }
14011: 	}
14012: 	return %result;
14013:     }
14014: 
14015:     sub get_unique_servers {
14016:         my %unique = reverse &get_servers(@_);
14017: 	return reverse %unique;
14018:     }
14019: 
14020:     sub host_domain {
14021: 	&load_hosts_tab() if (!$loaded);
14022: 
14023: 	my ($lonid) = @_;
14024: 	return $hostdom{$lonid};
14025:     }
14026: 
14027:     sub all_domains {
14028: 	&load_hosts_tab() if (!$loaded);
14029: 
14030: 	my %seen;
14031: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14032: 	return @uniq;
14033:     }
14034: 
14035:     sub internet_dom {
14036:         &load_hosts_tab() if (!$loaded);
14037: 
14038:         my ($lonid) = @_;
14039:         return $internetdom{$lonid};
14040:     }
14041: 
14042:     sub is_LC_dns {
14043:         &load_hosts_tab() if (!$loaded);
14044: 
14045:         my ($hostname) = @_;
14046:         return exists($LC_dns_serv{$hostname});
14047:     }
14048: 
14049: }
14050: 
14051: { 
14052:     my %iphost;
14053:     my %name_to_ip;
14054:     my %lonid_to_ip;
14055: 
14056:     sub get_hosts_from_ip {
14057: 	my ($ip) = @_;
14058: 	my %iphosts = &get_iphost();
14059: 	if (ref($iphosts{$ip})) {
14060: 	    return @{$iphosts{$ip}};
14061: 	}
14062: 	return;
14063:     }
14064:     
14065:     sub reset_hosts_ip_info {
14066: 	undef(%iphost);
14067: 	undef(%name_to_ip);
14068: 	undef(%lonid_to_ip);
14069:     }
14070: 
14071:     sub get_host_ip {
14072: 	my ($lonid) = @_;
14073: 	if (exists($lonid_to_ip{$lonid})) {
14074: 	    return $lonid_to_ip{$lonid};
14075: 	}
14076: 	my $name=&hostname($lonid);
14077:    	my $ip = gethostbyname($name);
14078: 	return if (!$ip || length($ip) ne 4);
14079: 	$ip=inet_ntoa($ip);
14080: 	$name_to_ip{$name}   = $ip;
14081: 	$lonid_to_ip{$lonid} = $ip;
14082: 	return $ip;
14083:     }
14084:     
14085:     sub get_iphost {
14086: 	my ($ignore_cache,$nocache) = @_;
14087: 
14088: 	if (!$ignore_cache) {
14089: 	    if (%iphost) {
14090: 		return %iphost;
14091: 	    }
14092: 	    my ($ip_info,$cached)=
14093: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14094: 	    if ($cached) {
14095: 		%iphost      = %{$ip_info->[0]};
14096: 		%name_to_ip  = %{$ip_info->[1]};
14097: 		%lonid_to_ip = %{$ip_info->[2]};
14098: 		return %iphost;
14099: 	    }
14100: 	}
14101: 
14102: 	# get yesterday's info for fallback
14103: 	my %old_name_to_ip;
14104: 	my ($ip_info,$cached)=
14105: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14106: 	if ($cached) {
14107: 	    %old_name_to_ip = %{$ip_info->[1]};
14108: 	}
14109: 
14110: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14111: 	foreach my $name (keys(%name_to_host)) {
14112: 	    my $ip;
14113: 	    if (!exists($name_to_ip{$name})) {
14114: 		$ip = gethostbyname($name);
14115: 		if (!$ip || length($ip) ne 4) {
14116: 		    if (defined($old_name_to_ip{$name})) {
14117: 			$ip = $old_name_to_ip{$name};
14118: 			&logthis("Can't find $name defaulting to old $ip");
14119: 		    } else {
14120: 			&logthis("Name $name no IP found");
14121: 			next;
14122: 		    }
14123: 		} else {
14124: 		    $ip=inet_ntoa($ip);
14125: 		}
14126: 		$name_to_ip{$name} = $ip;
14127: 	    } else {
14128: 		$ip = $name_to_ip{$name};
14129: 	    }
14130: 	    foreach my $id (@{ $name_to_host{$name} }) {
14131: 		$lonid_to_ip{$id} = $ip;
14132: 	    }
14133: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14134: 	}
14135:         unless ($nocache) {
14136: 	    &do_cache_new('iphost','iphost',
14137: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14138: 		          48*60*60);
14139:         }
14140: 
14141: 	return %iphost;
14142:     }
14143: 
14144:     #
14145:     #  Given a DNS returns the loncapa host name for that DNS 
14146:     # 
14147:     sub host_from_dns {
14148:         my ($dns) = @_;
14149:         my @hosts;
14150:         my $ip;
14151: 
14152:         if (exists($name_to_ip{$dns})) {
14153:             $ip = $name_to_ip{$dns};
14154:         }
14155:         if (!$ip) {
14156:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14157:             if (length($ip) == 4) { 
14158: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14159:             }
14160:         }
14161:         if ($ip) {
14162: 	    @hosts = get_hosts_from_ip($ip);
14163: 	    return $hosts[0];
14164:         }
14165:         return undef;
14166:     }
14167: 
14168:     sub get_internet_names {
14169:         my ($lonid) = @_;
14170:         return if ($lonid eq '');
14171:         my ($idnref,$cached)=
14172:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14173:         if ($cached) {
14174:             return $idnref;
14175:         }
14176:         my $ip = &get_host_ip($lonid);
14177:         my @hosts = &get_hosts_from_ip($ip);
14178:         my %iphost = &get_iphost();
14179:         my (@idns,%seen);
14180:         foreach my $id (@hosts) {
14181:             my $dom = &host_domain($id);
14182:             my $prim_id = &domain($dom,'primary');
14183:             my $prim_ip = &get_host_ip($prim_id);
14184:             next if ($seen{$prim_ip});
14185:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14186:                 foreach my $id (@{$iphost{$prim_ip}}) {
14187:                     my $intdom = &internet_dom($id);
14188:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14189:                         push(@idns,$intdom);
14190:                     }
14191:                 }
14192:             }
14193:             $seen{$prim_ip} = 1;
14194:         }
14195:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14196:     }
14197: 
14198: }
14199: 
14200: sub all_loncaparevs {
14201:     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);
14202: }
14203: 
14204: # ---------------------------------------------------------- Read loncaparev table
14205: {
14206:     sub load_loncaparevs { 
14207:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14208:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14209:                 while (my $configline=<$config>) {
14210:                     chomp($configline);
14211:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14212:                     $loncaparevs{$hostid}=$loncaparev;
14213:                 }
14214:                 close($config);
14215:             }
14216:         }
14217:     }
14218: }
14219: 
14220: # ---------------------------------------------------------- Read serverhostID table
14221: {
14222:     sub load_serverhomeIDs {
14223:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14224:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14225:                 while (my $configline=<$config>) {
14226:                     chomp($configline);
14227:                     my ($name,$id)=split(/:/,$configline);
14228:                     $serverhomeIDs{$name}=$id;
14229:                 }
14230:                 close($config);
14231:             }
14232:         }
14233:     }
14234: }
14235: 
14236: 
14237: BEGIN {
14238: 
14239: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14240:     unless ($readit) {
14241: {
14242:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14243:     %perlvar = (%perlvar,%{$configvars});
14244: }
14245: 
14246: 
14247: # ------------------------------------------------------ Read spare server file
14248: {
14249:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14250: 
14251:     while (my $configline=<$config>) {
14252:        chomp($configline);
14253:        if ($configline) {
14254: 	   my ($host,$type) = split(':',$configline,2);
14255: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14256: 	   push(@{ $spareid{$type} }, $host);
14257:        }
14258:     }
14259:     close($config);
14260: }
14261: # ------------------------------------------------------------ Read permissions
14262: {
14263:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14264: 
14265:     while (my $configline=<$config>) {
14266: 	chomp($configline);
14267: 	if ($configline) {
14268: 	    my ($role,$perm)=split(/ /,$configline);
14269: 	    if ($perm ne '') { $pr{$role}=$perm; }
14270: 	}
14271:     }
14272:     close($config);
14273: }
14274: 
14275: # -------------------------------------------- Read plain texts for permissions
14276: {
14277:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14278: 
14279:     while (my $configline=<$config>) {
14280: 	chomp($configline);
14281: 	if ($configline) {
14282: 	    my ($short,@plain)=split(/:/,$configline);
14283:             %{$prp{$short}} = ();
14284: 	    if (@plain > 0) {
14285:                 $prp{$short}{'std'} = $plain[0];
14286:                 for (my $i=1; $i<@plain; $i++) {
14287:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14288:                 }
14289:             }
14290: 	}
14291:     }
14292:     close($config);
14293: }
14294: 
14295: # ---------------------------------------------------------- Read package table
14296: {
14297:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14298: 
14299:     while (my $configline=<$config>) {
14300: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14301: 	chomp($configline);
14302: 	my ($short,$plain)=split(/:/,$configline);
14303: 	my ($pack,$name)=split(/\&/,$short);
14304: 	if ($plain ne '') {
14305: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14306: 	    $packagetab{$short}=$plain; 
14307: 	}
14308:     }
14309:     close($config);
14310: }
14311: 
14312: # ---------------------------------------------------------- Read loncaparev table
14313: 
14314: &load_loncaparevs();
14315: 
14316: # ---------------------------------------------------------- Read serverhostID table
14317: 
14318: &load_serverhomeIDs();
14319: 
14320: # ---------------------------------------------------------- Read releaseslist XML
14321: {
14322:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14323:     if (-e $file) {
14324:         my $parser = HTML::LCParser->new($file);
14325:         while (my $token = $parser->get_token()) {
14326:             if ($token->[0] eq 'S') {
14327:                 my $item = $token->[1];
14328:                 my $name = $token->[2]{'name'};
14329:                 my $value = $token->[2]{'value'};
14330:                 my $valuematch = $token->[2]{'valuematch'};
14331:                 my $namematch = $token->[2]{'namematch'};
14332:                 if ($item eq 'parameter') {
14333:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14334:                         my $release = $parser->get_text();
14335:                         $release =~ s/(^\s*|\s*$ )//gx;
14336:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14337:                     }
14338:                 } elsif ($item ne '' && $name ne '') {
14339:                     my $release = $parser->get_text();
14340:                     $release =~ s/(^\s*|\s*$ )//gx;
14341:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14342:                 }
14343:             }
14344:         }
14345:     }
14346: }
14347: 
14348: # ---------------------------------------------------------- Read managers table
14349: {
14350:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14351:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14352:             while (my $configline=<$config>) {
14353:                 chomp($configline);
14354:                 next if ($configline =~ /^\#/);
14355:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14356:                     $managerstab{$configline} = 1;
14357:                 }
14358:             }
14359:             close($config);
14360:         }
14361:     }
14362: }
14363: 
14364: # ------------- set up temporary directory
14365: {
14366:     $tmpdir = LONCAPA::tempdir();
14367: 
14368: }
14369: 
14370: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14371: 				'compress_threshold'=> 20_000,
14372:  			        });
14373: 
14374: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14375: $dumpcount=0;
14376: $locknum=0;
14377: 
14378: &logtouch();
14379: &logthis('<font color="yellow">INFO: Read configuration</font>');
14380: $readit=1;
14381:     {
14382: 	use integer;
14383: 	my $test=(2**32)+1;
14384: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14385: 	&logthis(" Detected 64bit platform ($_64bit)");
14386:     }
14387: }
14388: }
14389: 
14390: 1;
14391: __END__
14392: 
14393: =pod
14394: 
14395: =head1 NAME
14396: 
14397: Apache::lonnet - Subroutines to ask questions about things in the network.
14398: 
14399: =head1 SYNOPSIS
14400: 
14401: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14402: 
14403:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14404: 
14405: Common parameters:
14406: 
14407: =over 4
14408: 
14409: =item *
14410: 
14411: $uname : an internal username (if $cname expecting a course Id specifically)
14412: 
14413: =item *
14414: 
14415: $udom : a domain (if $cdom expecting a course's domain specifically)
14416: 
14417: =item *
14418: 
14419: $symb : a resource instance identifier
14420: 
14421: =item *
14422: 
14423: $namespace : the name of a .db file that contains the data needed or
14424: being set.
14425: 
14426: =back
14427: 
14428: =head1 OVERVIEW
14429: 
14430: lonnet provides subroutines which interact with the
14431: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14432: about classes, users, and resources.
14433: 
14434: For many of these objects you can also use this to store data about
14435: them or modify them in various ways.
14436: 
14437: =head2 Symbs
14438: 
14439: To identify a specific instance of a resource, LON-CAPA uses symbols
14440: or "symbs"X<symb>. These identifiers are built from the URL of the
14441: map, the resource number of the resource in the map, and the URL of
14442: the resource itself. The latter is somewhat redundant, but might help
14443: if maps change.
14444: 
14445: An example is
14446: 
14447:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14448: 
14449: The respective map entry is
14450: 
14451:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14452:   title="Problem 2">
14453:  </resource>
14454: 
14455: Symbs are used by the random number generator, as well as to store and
14456: restore data specific to a certain instance of for example a problem.
14457: 
14458: =head2 Storing And Retrieving Data
14459: 
14460: X<store()>X<cstore()>X<restore()>Three of the most important functions
14461: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14462: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14463: is is the non-critical message twin of cstore. These functions are for
14464: handlers to store a perl hash to a user's permanent data space in an
14465: easy manner, and to retrieve it again on another call. It is expected
14466: that a handler would use this once at the beginning to retrieve data,
14467: and then again once at the end to send only the new data back.
14468: 
14469: The data is stored in the user's data directory on the user's
14470: homeserver under the ID of the course.
14471: 
14472: The hash that is returned by restore will have all of the previous
14473: value for all of the elements of the hash.
14474: 
14475: Example:
14476: 
14477:  #creating a hash
14478:  my %hash;
14479:  $hash{'foo'}='bar';
14480: 
14481:  #storing it
14482:  &Apache::lonnet::cstore(\%hash);
14483: 
14484:  #changing a value
14485:  $hash{'foo'}='notbar';
14486: 
14487:  #adding a new value
14488:  $hash{'bar'}='foo';
14489:  &Apache::lonnet::cstore(\%hash);
14490: 
14491:  #retrieving the hash
14492:  my %history=&Apache::lonnet::restore();
14493: 
14494:  #print the hash
14495:  foreach my $key (sort(keys(%history))) {
14496:    print("\%history{$key} = $history{$key}");
14497:  }
14498: 
14499: Will print out:
14500: 
14501:  %history{1:foo} = bar
14502:  %history{1:keys} = foo:timestamp
14503:  %history{1:timestamp} = 990455579
14504:  %history{2:bar} = foo
14505:  %history{2:foo} = notbar
14506:  %history{2:keys} = foo:bar:timestamp
14507:  %history{2:timestamp} = 990455580
14508:  %history{bar} = foo
14509:  %history{foo} = notbar
14510:  %history{timestamp} = 990455580
14511:  %history{version} = 2
14512: 
14513: Note that the special hash entries C<keys>, C<version> and
14514: C<timestamp> were added to the hash. C<version> will be equal to the
14515: total number of versions of the data that have been stored. The
14516: C<timestamp> attribute will be the UNIX time the hash was
14517: stored. C<keys> is available in every historical section to list which
14518: keys were added or changed at a specific historical revision of a
14519: hash.
14520: 
14521: B<Warning>: do not store the hash that restore returns directly. This
14522: will cause a mess since it will restore the historical keys as if the
14523: were new keys. I.E. 1:foo will become 1:1:foo etc.
14524: 
14525: Calling convention:
14526: 
14527:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14528:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14529: 
14530: For more detailed information, see lonnet specific documentation.
14531: 
14532: =head1 RETURN MESSAGES
14533: 
14534: =over 4
14535: 
14536: =item * B<con_lost>: unable to contact remote host
14537: 
14538: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14539: when the connection is brought back up
14540: 
14541: =item * B<con_failed>: unable to contact remote host and unable to save message
14542: for later delivery
14543: 
14544: =item * B<error:>: an error a occurred, a description of the error follows the :
14545: 
14546: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14547: that was requested
14548: 
14549: =back
14550: 
14551: =head1 PUBLIC SUBROUTINES
14552: 
14553: =head2 Session Environment Functions
14554: 
14555: =over 4
14556: 
14557: =item * 
14558: X<appenv()>
14559: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14560: the user envirnoment file, and will be restored for each access this
14561: user makes during this session, also modifies the %env for the current
14562: process. Optional rolesarrayref - if defined contains a reference to an array
14563: of roles which are exempt from the restriction on modifying user.role entries 
14564: in the user's environment.db and in %env.    
14565: 
14566: =item *
14567: X<delenv()>
14568: B<delenv($delthis,$regexp)>: removes all items from the session
14569: environment file that begin with $delthis. If the 
14570: optional second arg - $regexp - is true, $delthis is treated as a 
14571: regular expression, otherwise \Q$delthis\E is used. 
14572: The values are also deleted from the current processes %env.
14573: 
14574: =item * get_env_multiple($name) 
14575: 
14576: gets $name from the %env hash, it seemlessly handles the cases where multiple
14577: values may be defined and end up as an array ref.
14578: 
14579: returns an array of values
14580: 
14581: =back
14582: 
14583: =head2 User Information
14584: 
14585: =over 4
14586: 
14587: =item *
14588: X<queryauthenticate()>
14589: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14590: authentication scheme
14591: 
14592: =item *
14593: X<authenticate()>
14594: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14595: authenticate user from domain's lib servers (first use the current
14596: one). C<$upass> should be the users password.
14597: $checkdefauth is optional (value is 1 if a check should be made to
14598:    authenticate user using default authentication method, and allow
14599:    account creation if username does not have account in the domain).
14600: $clientcancheckhost is optional (value is 1 if checking whether the
14601:    server can host will occur on the client side in lonauth.pm).   
14602: 
14603: =item *
14604: X<homeserver()>
14605: B<homeserver($uname,$udom)>: find the server which has
14606: the user's directory and files (there must be only one), this caches
14607: the answer, and also caches if there is a borken connection.
14608: 
14609: =item *
14610: X<idget()>
14611: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14612: a list of student/employee IDs or clicker IDs
14613: (student/employee IDs are a unique resource in a domain, there must be 
14614: only 1 ID per username, and only 1 username per ID in a specific domain).
14615: clickerIDs are not necessarily unique, as students might share clickers.
14616: (returns hash: id=>name,id=>name)
14617: 
14618: =item *
14619: X<idrget()>
14620: B<idrget($udom,@unames)>: find the IDs behind a list of
14621: usernames (returns hash: name=>id,name=>id)
14622: 
14623: =item *
14624: X<idput()>
14625: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14626: names and associated student/employee IDs or clicker IDs.
14627: 
14628: =item *
14629: X<iddel()>
14630: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14631: student/employee ID or clicker ID username look-ups from domain.
14632: The homeserver ($uhome) and namespace ($namespace) are optional.
14633: If no $uhome is provided, it will be determined usig &homeserver()
14634: for each user.  If no $namespace is provided, the default is ids.
14635: 
14636: =item *
14637: X<updateclickers()>
14638: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14639: clicker ID-to-username look-ups in clickers.db on library server.
14640: Permitted actions are add or del (i.e., add or delete). The 
14641: clickers.db contains clickerID as keys (escaped), and each corresponding
14642: value is an escaped comma-separated list of usernames (for whom the
14643: library server is the homeserver), who registered that particular ID.
14644: If $critical is true, the update will be sent via &critical, otherwise
14645: &reply() will be used.
14646: 
14647: =item *
14648: X<rolesinit()>
14649: B<rolesinit($udom,$username)>: get user privileges.
14650: returns user role, first access and timer interval hashes
14651: 
14652: =item *
14653: X<privileged()>
14654: B<privileged($username,$domain)>: returns a true if user has a
14655: privileged and active role (i.e. su or dc), false otherwise.
14656: 
14657: =item *
14658: X<getsection()>
14659: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14660: course $cname, return section name/number or '' for "not in course"
14661: and '-1' for "no section"
14662: 
14663: =item *
14664: X<userenvironment()>
14665: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14666: passed in @what from the requested user's environment, returns a hash
14667: 
14668: =item * 
14669: X<userlog_query()>
14670: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14671: activity.log file. %filters defines filters applied when parsing the
14672: log file. These can be start or end timestamps, or the type of action
14673: - log to look for Login or Logout events, check for Checkin or
14674: Checkout, role for role selection. The response is in the form
14675: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14676: escaped strings of the action recorded in the activity.log file.
14677: 
14678: =back
14679: 
14680: =head2 User Roles
14681: 
14682: =over 4
14683: 
14684: =item *
14685: 
14686: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14687: returns codes for allowed actions.
14688: 
14689: The first argument is required, all others are optional.
14690: 
14691: $priv is the privilege being checked.
14692: $uri contains additional information about what is being checked for access (e.g.,
14693: URL, course ID etc.). 
14694: $symb is the unique resource instance identifier in a course; if needed,
14695: but not provided, it will be retrieved via a call to &symbread(). 
14696: $role is the role for which a priv is being checked (only used if priv is evb). 
14697: $clientip is the user's IP address (only used when checking for access to portfolio 
14698: files).
14699: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14700: prevents recursive calls to &allowed.
14701: 
14702:  F: full access
14703:  U,I,K: authentication modes (cxx only)
14704:  '': forbidden
14705:  1: user needs to choose course
14706:  2: browse allowed
14707:  A: passphrase authentication needed
14708:  B: access temporarily blocked because of a blocking event in a course.
14709: 
14710: =item *
14711: 
14712: constructaccess($url,$setpriv) : check for access to construction space URL
14713: 
14714: See if the owner domain and name in the URL match those in the
14715: expected environment.  If so, return three element list
14716: ($ownername,$ownerdomain,$ownerhome).
14717: 
14718: Otherwise return the null string.
14719: 
14720: If second argument 'setpriv' is true, it assigns the privileges,
14721: and returns the same three element list, unless the owner has
14722: blocked "ad hoc" Domain Coordinator access to the Author Space,
14723: in which case the null string is returned.
14724: 
14725: =item *
14726: 
14727: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14728: define a custom role rolename set privileges in format of lonTabs/roles.tab
14729: for system, domain, and course level. $uname and $udom are optional (current
14730: user's username and domain will be used when either of $uname or $udom are absent.
14731: 
14732: =item *
14733: 
14734: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14735: (rolesplain.tab); plain text explanation of a user role term.
14736: $type is Course (default) or Community.
14737: If $forcedefault evaluates to true, text returned will be default 
14738: text for $type. Otherwise, if this is a course, the text returned 
14739: will be a custom name for the role (if defined in the course's 
14740: environment).  If no custom name is defined the default is returned.
14741:    
14742: =item *
14743: 
14744: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14745: All arguments are optional. Returns a hash of a roles, either for
14746: co-author/assistant author roles for a user's Construction Space
14747: (default), or if $context is 'userroles', roles for the user himself,
14748: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14749: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14750: For each key, value is set to colon-separated start and end times for
14751: the role.  If no username and domain are specified, will default to
14752: current user/domain. Types, roles, and roledoms are references to arrays
14753: of role statuses (active, future or previous), roles 
14754: (e.g., cc,in, st etc.) and domains of the roles which can be used
14755: to restrict the list of roles reported. If no array ref is 
14756: provided for types, will default to return only active roles.
14757: 
14758: =item *
14759: 
14760: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14761: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14762: 
14763: Additional optional arguments are: $type (if role checking is to be restricted 
14764: to certain user status types -- previous (expired roles), active (currently
14765: available roles) or future (roles available in the future), and
14766: $hideprivileged -- if true will not report course roles for users who
14767: have active Domain Coordinator role in course's domain or in additional
14768: domains (specified in 'Domains to check for privileged users' in course
14769: environment -- set via:  Course Settings -> Classlists and staff listing).
14770: 
14771: =item *
14772: 
14773: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14774: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14775: $possdomains and $possroles are optional array refs -- to domains to check and
14776: roles to check.  If $possdomains is not specified, a dump will be done of the
14777: users' roles.db to check for a dc or su role in any domain. This can be
14778: time consuming if &privileged is called repeatedly (e.g., when displaying a
14779: classlist), so in such cases, supplying a $possdomains array is preferred, as
14780: this then allows &privileged_by_domain() to be used, which caches the identity
14781: of privileged users, eliminating the need for repeated calls to &dump().
14782: 
14783: =item *
14784: 
14785: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14786: where the outer hash keys are domains specified in the $possdomains array ref,
14787: next inner hash keys are privileged roles specified in the $roles array ref,
14788: and the innermost hash contains key = value pairs for username:domain = end:start
14789: for active or future "privileged" users with that role in that domain. To avoid
14790: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14791: innerhash are cached using priv_$role and $dom as the identifiers.
14792: 
14793: =back
14794: 
14795: =head2 User Modification
14796: 
14797: =over 4
14798: 
14799: =item *
14800: 
14801: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14802: user for the level given by URL.  Optional start and end dates (leave empty
14803: string or zero for "no date")
14804: 
14805: =item *
14806: 
14807: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14808: change a users, password, possible return values are: ok,
14809: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14810: refused
14811: 
14812: =item *
14813: 
14814: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14815: 
14816: =item *
14817: 
14818: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14819:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14820: 
14821: will update user information (firstname,middlename,lastname,generation,
14822: permanentemail), and if forceid is true, student/employee ID also.
14823: A user's institutional affiliation(s) can also be updated.
14824: User information fields will not be overwritten with empty entries 
14825: unless the field is included in the $candelete array reference.
14826: This array is included when a single user is modified via "Manage Users",
14827: or when Autoupdate.pl is run by cron in a domain.
14828: 
14829: =item *
14830: 
14831: modifystudent
14832: 
14833: modify a student's enrollment and identification information.
14834: The course id is resolved based on the current user's environment.  
14835: This means the invoking user must be a course coordinator or otherwise
14836: associated with a course.
14837: 
14838: This call is essentially a wrapper for lonnet::modifyuser and
14839: lonnet::modify_student_enrollment
14840: 
14841: Inputs: 
14842: 
14843: =over 4
14844: 
14845: =item B<$udom> Student's loncapa domain
14846: 
14847: =item B<$uname> Student's loncapa login name
14848: 
14849: =item B<$uid> Student/Employee ID
14850: 
14851: =item B<$umode> Student's authentication mode
14852: 
14853: =item B<$upass> Student's password
14854: 
14855: =item B<$first> Student's first name
14856: 
14857: =item B<$middle> Student's middle name
14858: 
14859: =item B<$last> Student's last name
14860: 
14861: =item B<$gene> Student's generation
14862: 
14863: =item B<$usec> Student's section in course
14864: 
14865: =item B<$end> Unix time of the roles expiration
14866: 
14867: =item B<$start> Unix time of the roles start date
14868: 
14869: =item B<$forceid> If defined, allow $uid to be changed
14870: 
14871: =item B<$desiredhome> server to use as home server for student
14872: 
14873: =item B<$email> Student's permanent e-mail address
14874: 
14875: =item B<$type> Type of enrollment (auto or manual)
14876: 
14877: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14878: 
14879: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14880: 
14881: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14882: 
14883: =item B<$context> role change context (shown in User Management Logs display in a course)
14884: 
14885: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14886: 
14887: =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.
14888: 
14889: =back
14890: 
14891: =item *
14892: 
14893: modify_student_enrollment
14894: 
14895: Change a student's enrollment status in a class.  The environment variable
14896: 'role.request.course' must be defined for this function to proceed.
14897: 
14898: Inputs:
14899: 
14900: =over 4
14901: 
14902: =item $udom, student's domain
14903: 
14904: =item $uname, student's name
14905: 
14906: =item $uid, student's user id
14907: 
14908: =item $first, student's first name
14909: 
14910: =item $middle
14911: 
14912: =item $last
14913: 
14914: =item $gene
14915: 
14916: =item $usec
14917: 
14918: =item $end
14919: 
14920: =item $start
14921: 
14922: =item $type
14923: 
14924: =item $locktype
14925: 
14926: =item $cid
14927: 
14928: =item $selfenroll
14929: 
14930: =item $context
14931: 
14932: =item $credits, number of credits student will earn from this class
14933: 
14934: =item $instsec, institutional course section code for student
14935: 
14936: =back
14937: 
14938: 
14939: =item *
14940: 
14941: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14942: custom role; give a custom role to a user for the level given by URL.  Specify
14943: name and domain of role author, and role name
14944: 
14945: =item *
14946: 
14947: revokerole($udom,$uname,$url,$role) : revoke a role for url
14948: 
14949: =item *
14950: 
14951: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14952: 
14953: =back
14954: 
14955: =head2 Course Infomation
14956: 
14957: =over 4
14958: 
14959: =item *
14960: 
14961: coursedescription($courseid,$options) : returns a hash of information about the
14962: specified course id, including all environment settings for the
14963: course, the description of the course will be in the hash under the
14964: key 'description'
14965: 
14966: $options is an optional parameter that if supplied is a hash reference that controls
14967: what how this function works.  It has the following key/values:
14968: 
14969: =over 4
14970: 
14971: =item freshen_cache
14972: 
14973: If defined, and the environment cache for the course is valid, it is 
14974: returned in the returned hash.
14975: 
14976: =item one_time
14977: 
14978: If defined, the last cache time is set to _now_
14979: 
14980: =item user
14981: 
14982: If defined, the supplied username is used instead of the current user.
14983: 
14984: 
14985: =back
14986: 
14987: =item *
14988: 
14989: resdata($name,$domain,$type,@which) : request for current parameter
14990: setting for a specific $type, where $type is either 'course' or 'user',
14991: @what should be a list of parameters to ask about. This routine caches
14992: answers for 10 minutes.
14993: 
14994: =item *
14995: 
14996: get_courseresdata($courseid, $domain) : dump the entire course resource
14997: data base, returning a hash that is keyed by the resource name and has
14998: values that are the resource value.  I believe that the timestamps and
14999: versions are also returned.
15000: 
15001: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15002: supplemental content area. This routine caches the number of files for 
15003: 10 minutes.
15004: 
15005: =back
15006: 
15007: =head2 Course Modification
15008: 
15009: =over 4
15010: 
15011: =item *
15012: 
15013: writecoursepref($courseid,%prefs) : write preferences (environment
15014: database) for a course
15015: 
15016: =item *
15017: 
15018: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15019: 
15020: =item *
15021: 
15022: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15023: 
15024: =item *
15025: 
15026: is_course($courseid), is_course($cdom, $cnum)
15027: 
15028: Accepts either a combined $courseid (in the form of domain_courseid) or the
15029: two component version $cdom, $cnum. It checks if the specified course exists.
15030: 
15031: Returns:
15032:     undef if the course doesn't exist, otherwise
15033:     in scalar context the combined courseid.
15034:     in list context the two components of the course identifier, domain and 
15035:     courseid.    
15036: 
15037: =back
15038: 
15039: =head2 Resource Subroutines
15040: 
15041: =over 4
15042: 
15043: =item *
15044: 
15045: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15046: 
15047: =item *
15048: 
15049: repcopy($filename) : subscribes to the requested file, and attempts to
15050: replicate from the owning library server, Might return
15051: 'unavailable', 'not_found', 'forbidden', 'ok', or
15052: 'bad_request', also attempts to grab the metadata for the
15053: resource. Expects the local filesystem pathname
15054: (/home/httpd/html/res/....)
15055: 
15056: =back
15057: 
15058: =head2 Resource Information
15059: 
15060: =over 4
15061: 
15062: =item *
15063: 
15064: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15065: and returns the value of a variety of different possible values,
15066: $varname should be a request string, and the other parameters can be
15067: used to specify who and what one is asking about. Ordinarily, $cid 
15068: does not need to be specified, as it is retrived from 
15069: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15070: within lonuserstate::loadmap() when initializing a course, before
15071: $env{'request.course.id'} has been set, so it needs to be provided
15072: in that one case.
15073: 
15074: Possible values for $varname are environment.lastname (or other item
15075: from the envirnment hash), user.name (or someother aspect about the
15076: user), resource.0.maxtries (or some other part and parameter of a
15077: resource)
15078: 
15079: =item *
15080: 
15081: directcondval($number) : get current value of a condition; reads from a state
15082: string
15083: 
15084: =item *
15085: 
15086: condval($condidx) : value of condition index based on state
15087: 
15088: =item *
15089: 
15090: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15091: resource's metadata, $what should be either a specific key, or either
15092: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15093: packages that this resource currently uses, the last 3 arguments are 
15094: only used internally for recursive metadata.
15095: 
15096: the toolsymb is only used where the uri is for an external tool (for which
15097: the uri as well as the symb are guaranteed to be unique).
15098: 
15099: this function automatically caches all requests except any made recursively
15100: to retrieve a list of metadata keys for an imported library file ($liburi is 
15101: defined).
15102: 
15103: =item *
15104: 
15105: metadata_query($query,$custom,$customshow) : make a metadata query against the
15106: network of library servers; returns file handle of where SQL and regex results
15107: will be stored for query
15108: 
15109: =item *
15110: 
15111: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15112: return symbolic list entry (all arguments optional). 
15113: 
15114: Args: filename is the filename (including path) for the file for which a symb 
15115: is required; donotrecurse, if true will prevent calls to allowed() being made 
15116: to check access status if more than one resource was found in the bighash 
15117: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15118: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15119: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15120: cause possible symbs to be checked to determine if they are subject to content
15121: blocking, if so they will not be included as possible symbs; possibles is a
15122: ref to a hash, which, as a side effect, will be populated with all possible 
15123: symbs (content blocking not tested).
15124:  
15125: returns the data handle
15126: 
15127: =item *
15128: 
15129: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15130: and is a possible symb for the URL in $thisfn, and if is an encrypted
15131: resource that the user accessed using /enc/ returns a 1 on success, 0
15132: on failure, user must be in a course, as it assumes the existence of
15133: the course initial hash, and uses $env('request.course.id'}.  The third
15134: arg is an optional reference to a scalar.  If this arg is passed in the 
15135: call to symbverify, it will be set to 1 if the symb has been set to be 
15136: encrypted; otherwise it will be null.  
15137: 
15138: =item *
15139: 
15140: symbclean($symb) : removes versions numbers from a symb, returns the
15141: cleaned symb
15142: 
15143: =item *
15144: 
15145: is_on_map($uri) : checks if the $uri is somewhere on the current
15146: course map, user must be in a course for it to work.
15147: 
15148: =item *
15149: 
15150: numval($salt) : return random seed value (addend for rndseed)
15151: 
15152: =item *
15153: 
15154: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15155: a random seed, all arguments are optional, if they aren't sent it uses the
15156: environment to derive them. Note: if symb isn't sent and it can't get one
15157: from &symbread it will use the current time as its return value
15158: 
15159: =item *
15160: 
15161: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15162: unfakeable, receipt
15163: 
15164: =item *
15165: 
15166: receipt() : API to ireceipt working off of env values; given out to users
15167: 
15168: =item *
15169: 
15170: countacc($url) : count the number of accesses to a given URL
15171: 
15172: =item *
15173: 
15174: 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
15175: 
15176: =item *
15177: 
15178: 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)
15179: 
15180: =item *
15181: 
15182: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15183: 
15184: =item *
15185: 
15186: devalidate($symb) : devalidate temporary spreadsheet calculations,
15187: forcing spreadsheet to reevaluate the resource scores next time.
15188: 
15189: =item * 
15190: 
15191: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15192: when viewing in course context.
15193: 
15194:  input: six args -- filename (decluttered), course number, course domain,
15195:                     url, symb (if registered) and group (if this is a 
15196:                     group item -- e.g., bulletin board, group page etc.).
15197: 
15198:  output: array of five scalars --
15199:          $cfile -- url for file editing if editable on current server
15200:          $home -- homeserver of resource (i.e., for author if published,
15201:                                           or course if uploaded.).
15202:          $switchserver --  1 if server switch will be needed.
15203:          $forceedit -- 1 if icon/link should be to go to edit mode 
15204:          $forceview -- 1 if icon/link should be to go to view mode
15205: 
15206: =item *
15207: 
15208: is_course_upload($file,$cnum,$cdom)
15209: 
15210: Used in course context to determine if current file was uploaded to 
15211: the course (i.e., would be found in /userfiles/docs on the course's 
15212: homeserver.
15213: 
15214:   input: 3 args -- filename (decluttered), course number and course domain.
15215:   output: boolean -- 1 if file was uploaded.
15216: 
15217: =back
15218: 
15219: =head2 Storing/Retreiving Data
15220: 
15221: =over 4
15222: 
15223: =item *
15224: 
15225: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15226: permanently for this url; hashref needs to be given and should be a \%hashname;
15227: the remaining args aren't required and if they aren't passed or are '' they will
15228: be derived from the env (with the exception of $laststore, which is an 
15229: optional arg used when a user's submission is stored in grading).
15230: $laststore is $version=$timestamp, where $version is the most recent version
15231: number retrieved for the corresponding $symb in the $namespace db file, and
15232: $timestamp is the timestamp for that transaction (UNIX time).
15233: $laststore is currently only passed when cstore() is called by 
15234: structuretags::finalize_storage().
15235: 
15236: =item *
15237: 
15238: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15239: but uses critical subroutine
15240: 
15241: =item *
15242: 
15243: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15244: all args are optional
15245: 
15246: =item *
15247: 
15248: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15249: dumps the complete (or key matching regexp) namespace into a hash
15250: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15251: normally &store()ed into
15252: 
15253: $range should be either an integer '100' (give me the first 100
15254:                                            matching records)
15255:               or be  two integers sperated by a - with no spaces
15256:                  '30-50' (give me the 30th through the 50th matching
15257:                           records)
15258: 
15259: 
15260: =item *
15261: 
15262: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15263: replaces a &store() version of data with a replacement set of data
15264: for a particular resource in a namespace passed in the $storehash hash 
15265: reference. If $tolog is true, the transaction is logged in the courselog
15266: with an action=PUTSTORE.
15267: 
15268: =item *
15269: 
15270: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15271: works very similar to store/cstore, but all data is stored in a
15272: temporary location and can be reset using tmpreset, $storehash should
15273: be a hash reference, returns nothing on success
15274: 
15275: =item *
15276: 
15277: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15278: similar to restore, but all data is stored in a temporary location and
15279: can be reset using tmpreset. Returns a hash of values on success,
15280: error string otherwise.
15281: 
15282: =item *
15283: 
15284: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15285: deltes all keys for $symb form the temporary storage hash.
15286: 
15287: =item *
15288: 
15289: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15290: reference filled in from namesp ($udom and $uname are optional)
15291: 
15292: =item *
15293: 
15294: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15295: namesp ($udom and $uname are optional)
15296: 
15297: =item *
15298: 
15299: dump($namespace,$udom,$uname,$regexp,$range) : 
15300: dumps the complete (or key matching regexp) namespace into a hash
15301: ($udom, $uname, $regexp, $range are optional)
15302: 
15303: $range should be either an integer '100' (give me the first 100
15304:                                            matching records)
15305:               or be  two integers sperated by a - with no spaces
15306:                  '30-50' (give me the 30th through the 50th matching
15307:                           records)
15308: =item *
15309: 
15310: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15311: $store can be a scalar, an array reference, or if the amount to be 
15312: incremented is > 1, a hash reference.
15313: 
15314: ($udom and $uname are optional)
15315: 
15316: =item *
15317: 
15318: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15319: ($udom and $uname are optional)
15320: 
15321: =item *
15322: 
15323: cput($namespace,$storehash,$udom,$uname) : critical put
15324: ($udom and $uname are optional)
15325: 
15326: =item *
15327: 
15328: newput($namespace,$storehash,$udom,$uname) :
15329: 
15330: Attempts to store the items in the $storehash, but only if they don't
15331: currently exist, if this succeeds you can be certain that you have 
15332: successfully created a new key value pair in the $namespace db.
15333: 
15334: 
15335: Args:
15336:  $namespace: name of database to store values to
15337:  $storehash: hashref to store to the db
15338:  $udom: (optional) domain of user containing the db
15339:  $uname: (optional) name of user caontaining the db
15340: 
15341: Returns:
15342:  'ok' -> succeeded in storing all keys of $storehash
15343:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15344:                         least <key> already existed in the db (other
15345:                         requested keys may also already exist)
15346:  'error: <msg>' -> unable to tie the DB or other error occurred
15347:  'con_lost' -> unable to contact request server
15348:  'refused' -> action was not allowed by remote machine
15349: 
15350: 
15351: =item *
15352: 
15353: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15354: reference filled in from namesp (encrypts the return communication)
15355: ($udom and $uname are optional)
15356: 
15357: =item *
15358: 
15359: log($udom,$name,$home,$message) : write to permanent log for user; use
15360: critical subroutine
15361: 
15362: =item *
15363: 
15364: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15365: array reference filled in from namespace found in domain level on either
15366: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15367: 
15368: =item *
15369: 
15370: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15371: domain level either on specified domain server ($uhome) or primary domain 
15372: server ($udom and $uhome are optional)
15373: 
15374: =item * 
15375: 
15376: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15377: for: authentication, language, quotas, timezone, date locale, and portal URL in
15378: the target domain.
15379: 
15380: May also include additional key => value pairs for the following groups:
15381: 
15382: =over
15383: 
15384: =item
15385: disk quotas (MB allocated by default to portfolios and authoring spaces).
15386: 
15387: =over
15388: 
15389: =item defaultquota, authorquota
15390: 
15391: =back
15392: 
15393: =item
15394: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15395: portfolio for users).
15396: 
15397: =over
15398: 
15399: =item
15400: aboutme, blog, webdav, portfolio
15401: 
15402: =back
15403: 
15404: =item
15405: requestcourses: ability to request courses, and how requests are processed.
15406: 
15407: =over
15408: 
15409: =item
15410: official, unofficial, community, textbook, placement
15411: 
15412: =back
15413: 
15414: =item
15415: inststatus: types of institutional affiliation, and order in which they are displayed.
15416: 
15417: =over
15418: 
15419: =item
15420: inststatustypes, inststatusorder, inststatusguest
15421: 
15422: =back
15423: 
15424: =item
15425: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15426: for course's uploaded content.
15427: 
15428: =over
15429: 
15430: =item
15431: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15432: communityquota, textbookquota, placementquota
15433: 
15434: =back
15435: 
15436: =item
15437: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15438: on your servers.
15439: 
15440: =over
15441: 
15442: =item 
15443: remotesessions, hostedsessions
15444: 
15445: =back
15446: 
15447: =back
15448: 
15449: In cases where a domain coordinator has never used the "Set Domain Configuration"
15450: utility to create a configuration.db file on a domain's primary library server 
15451: only the following domain defaults: auth_def, auth_arg_def, lang_def
15452: -- corresponding values are authentication type (internal, krb4, krb5,
15453: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15454: will be available. Values are retrieved from cache (if current), unless the
15455: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15456: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15457: 
15458: Typical usage:
15459: 
15460: %domdefaults = &get_domain_defaults($target_domain);
15461: 
15462: =back
15463: 
15464: =head2 Network Status Functions
15465: 
15466: =over 4
15467: 
15468: =item *
15469: 
15470: dirlist() : return directory list based on URI (first arg).
15471: 
15472: Inputs: 1 required, 5 optional.
15473: 
15474: =over
15475: 
15476: =item 
15477: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15478: 
15479: =item
15480: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15481: 
15482: =item
15483: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15484: 
15485: =item
15486: $getpropath - boolean: 1 if prepend path using &propath(). 
15487: 
15488: =item
15489: $getuserdir - boolean: 1 if prepend path for "userfiles".
15490: 
15491: =item 
15492: $alternateRoot - path to prepend in place of path from $uri.
15493: 
15494: =back
15495: 
15496: Returns: Array of up to two items.
15497: 
15498: =over
15499: 
15500: a reference to an array of files/subdirectories
15501: 
15502: =over
15503: 
15504: Each element in the array of files/subdirectories is a & separated list of
15505: item name and the result of running stat on the item.  If dirlist was requested
15506: for a file instead of a directory, the item name will be ''. For a directory 
15507: listing, if the item is a metadata file, the element will end &N&M 
15508: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15509: default copyright set (1).  
15510: 
15511: =back
15512: 
15513: a scalar containing error condition (if encountered).
15514: 
15515: =over
15516: 
15517: =item 
15518: no_host (no homeserver identified for $username:$domain).
15519: 
15520: =item 
15521: no_such_host (server contacted for listing not identified as valid host).
15522: 
15523: =item 
15524: con_lost (connection to remote server failed).
15525: 
15526: =item 
15527: refused (invalid $username:$domain received on lond side).
15528: 
15529: =item 
15530: no_such_dir (directory at specified path on lond side does not exist). 
15531: 
15532: =item 
15533: empty (directory at specified path on lond side is empty).
15534: 
15535: =over
15536: 
15537: This is currently not encountered because the &ls3, &ls2, 
15538: &ls (_handler) routines on the lond side do not filter out
15539: . and .. from a directory listing. 
15540: 
15541: =back
15542: 
15543: =back
15544: 
15545: =back
15546: 
15547: =item *
15548: 
15549: spareserver() : find server with least workload from spare.tab
15550: 
15551: 
15552: =item *
15553: 
15554: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15555: if there is no corresponding loncapa host.
15556: 
15557: =back
15558: 
15559: 
15560: =head2 Apache Request
15561: 
15562: =over 4
15563: 
15564: =item *
15565: 
15566: ssi($url,%hash) : server side include, does a complete request cycle on url to
15567: localhost, posts hash
15568: 
15569: =back
15570: 
15571: =head2 Data to String to Data
15572: 
15573: =over 4
15574: 
15575: =item *
15576: 
15577: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15578: and '&' separators, supports elements that are arrayrefs and hashrefs
15579: 
15580: =item *
15581: 
15582: hashref2str($hashref) : convert a hashref into a string complete with
15583: escaping and '=' and '&' separators, supports elements that are
15584: arrayrefs and hashrefs
15585: 
15586: =item *
15587: 
15588: arrayref2str($arrayref) : convert an arrayref into a string complete
15589: with escaping and '&' separators, supports elements that are arrayrefs
15590: and hashrefs
15591: 
15592: =item *
15593: 
15594: str2hash($string) : convert string to hash using unescaping and
15595: splitting on '=' and '&', supports elements that are arrayrefs and
15596: hashrefs
15597: 
15598: =item *
15599: 
15600: str2array($string) : convert string to hash using unescaping and
15601: splitting on '&', supports elements that are arrayrefs and hashrefs
15602: 
15603: =back
15604: 
15605: =head2 Logging Routines
15606: 
15607: 
15608: These routines allow one to make log messages in the lonnet.log and
15609: lonnet.perm logfiles.
15610: 
15611: =over 4
15612: 
15613: =item *
15614: 
15615: logtouch() : make sure the logfile, lonnet.log, exists
15616: 
15617: =item *
15618: 
15619: logthis() : append message to the normal lonnet.log file, it gets
15620: preiodically rolled over and deleted.
15621: 
15622: =item *
15623: 
15624: logperm() : append a permanent message to lonnet.perm.log, this log
15625: file never gets deleted by any automated portion of the system, only
15626: messages of critical importance should go in here.
15627: 
15628: 
15629: =back
15630: 
15631: =head2 General File Helper Routines
15632: 
15633: =over 4
15634: 
15635: =item *
15636: 
15637: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15638: (a) files in /uploaded
15639:   (i) If a local copy of the file exists - 
15640:       compares modification date of local copy with last-modified date for 
15641:       definitive version stored on home server for course. If local copy is 
15642:       stale, requests a new version from the home server and stores it. 
15643:       If the original has been removed from the home server, then local copy 
15644:       is unlinked.
15645:   (ii) If local copy does not exist -
15646:       requests the file from the home server and stores it. 
15647:   
15648:   If $caller is 'uploadrep':  
15649:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15650:     for request for files originally uploaded via DOCS. 
15651:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15652:   
15653:   Otherwise:
15654:      This indicates a call from the content generation phase of the request.
15655:      -  returns the entire contents of the file or -1.
15656:      
15657: (b) files in /res
15658:    - returns the entire contents of a file or -1; 
15659:    it properly subscribes to and replicates the file if neccessary.
15660: 
15661: 
15662: =item *
15663: 
15664: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15665:                   reference
15666: 
15667: returns either a stat() list of data about the file or an empty list
15668: if the file doesn't exist or couldn't find out about it (connection
15669: problems or user unknown)
15670: 
15671: =item *
15672: 
15673: filelocation($dir,$file) : returns file system location of a file
15674: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15675: directory that relative $file lookups are to looked in ($dir of /a/dir
15676: and a file of ../bob will become /a/bob)
15677: 
15678: =item *
15679: 
15680: hreflocation($dir,$file) : returns file system location or a URL; same as
15681: filelocation except for hrefs
15682: 
15683: =item *
15684: 
15685: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15686: also removes beginning /home/httpd/html unless /priv/ follows it.
15687: 
15688: =back
15689: 
15690: =head2 Usererfile file routines (/uploaded*)
15691: 
15692: =over 4
15693: 
15694: =item *
15695: 
15696: userfileupload(): main rotine for putting a file in a user or course's
15697:                   filespace, arguments are,
15698: 
15699:  formname - required - this is the name of the element in $env where the
15700:            filename, and the contents of the file to create/modifed exist
15701:            the filename is in $env{'form.'.$formname.'.filename'} and the
15702:            contents of the file is located in $env{'form.'.$formname}
15703:  context - if coursedoc, store the file in the course of the active role
15704:              of the current user; 
15705:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15706:            if 'canceloverwrite': delete file in tmp/overwrites directory
15707:  subdir - required - subdirectory to put the file in under ../userfiles/
15708:          if undefined, it will be placed in "unknown"
15709: 
15710:  (This routine calls clean_filename() to remove any dangerous
15711:  characters from the filename, and then calls finuserfileupload() to
15712:  complete the transaction)
15713: 
15714:  returns either the url of the uploaded file (/uploaded/....) if successful
15715:  and /adm/notfound.html if unsuccessful
15716: 
15717: =item *
15718: 
15719: clean_filename(): routine for cleaing a filename up for storage in
15720:                  userfile space, argument is:
15721: 
15722:  filename - proposed filename
15723: 
15724: returns: the new clean filename
15725: 
15726: =item *
15727: 
15728: finishuserfileupload(): routine that creates and sends the file to
15729: userspace, probably shouldn't be called directly
15730: 
15731:   docuname: username or courseid of destination for the file
15732:   docudom: domain of user/course of destination for the file
15733:   formname: same as for userfileupload()
15734:   fname: filename (including subdirectories) for the file
15735:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15736:   allfiles: reference to hash used to store objects found by parser
15737:   codebase: reference to hash used for codebases of java objects found by parser
15738:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15739:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15740:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15741:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15742:   context: if 'overwrite', will move the uploaded file from its temporary location to
15743:             userfiles to facilitate overwriting a previously uploaded file with same name.
15744:   mimetype: reference to scalar to accommodate mime type determined
15745:             from File::MMagic if $parser = parse.
15746: 
15747:  returns either the url of the uploaded file (/uploaded/....) if successful
15748:  and /adm/notfound.html if unsuccessful (or an error message if context 
15749:  was 'overwrite').
15750:  
15751: 
15752: =item *
15753: 
15754: renameuserfile(): renames an existing userfile to a new name
15755: 
15756:   Args:
15757:    docuname: username or courseid of destination for the file
15758:    docudom: domain of user/course of destination for the file
15759:    old: current file name (including any subdirs under userfiles)
15760:    new: desired file name (including any subdirs under userfiles)
15761: 
15762: =item *
15763: 
15764: mkdiruserfile(): creates a directory is a userfiles dir
15765: 
15766:   Args:
15767:    docuname: username or courseid of destination for the file
15768:    docudom: domain of user/course of destination for the file
15769:    dir: dir to create (including any subdirs under userfiles)
15770: 
15771: =item *
15772: 
15773: removeuserfile(): removes a file that exists in userfiles
15774: 
15775:   Args:
15776:    docuname: username or courseid of destination for the file
15777:    docudom: domain of user/course of destination for the file
15778:    fname: filname to delete (including any subdirs under userfiles)
15779: 
15780: =item *
15781: 
15782: removeuploadedurl(): convience function for removeuserfile()
15783: 
15784:   Args:
15785:    url:  a full /uploaded/... url to delete
15786: 
15787: =item * 
15788: 
15789: get_portfile_permissions():
15790:   Args:
15791:     domain: domain of user or course contain the portfolio files
15792:     user: name of user or num of course contain the portfolio files
15793:   Returns:
15794:     hashref of a dump of the proper file_permissions.db
15795:    
15796: 
15797: =item * 
15798: 
15799: get_access_controls():
15800: 
15801: Args:
15802:   current_permissions: the hash ref returned from get_portfile_permissions()
15803:   group: (optional) the group you want the files associated with
15804:   file: (optional) the file you want access info on
15805: 
15806: Returns:
15807:     a hash (keys are file names) of hashes containing
15808:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15809:         values are XML containing access control settings (see below) 
15810: 
15811: Internal notes:
15812: 
15813:  access controls are stored in file_permissions.db as key=value pairs.
15814:     key -> path to file/file_name\0uniqueID:scope_end_start
15815:         where scope -> public,guest,course,group,domains or users.
15816:               end -> UNIX time for end of access (0 -> no end date)
15817:               start -> UNIX time for start of access
15818: 
15819:     value -> XML description of access control
15820:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15821:             <start></start>
15822:             <end></end>
15823: 
15824:             <password></password>  for scope type = guest
15825: 
15826:             <domain></domain>     for scope type = course or group
15827:             <number></number>
15828:             <roles id="">
15829:              <role></role>
15830:              <access></access>
15831:              <section></section>
15832:              <group></group>
15833:             </roles>
15834: 
15835:             <dom></dom>         for scope type = domains
15836: 
15837:             <users>             for scope type = users
15838:              <user>
15839:               <uname></uname>
15840:               <udom></udom>
15841:              </user>
15842:             </users>
15843:            </scope> 
15844:               
15845:  Access data is also aggregated for each file in an additional key=value pair:
15846:  key -> path to file/file_name\0accesscontrol 
15847:  value -> reference to hash
15848:           hash contains key = value pairs
15849:           where key = uniqueID:scope_end_start
15850:                 value = UNIX time record was last updated
15851: 
15852:           Used to improve speed of look-ups of access controls for each file.  
15853:  
15854:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15855: 
15856: =item *
15857: 
15858: modify_access_controls():
15859: 
15860: Modifies access controls for a portfolio file
15861: Args
15862: 1. file name
15863: 2. reference to hash of required changes,
15864: 3. domain
15865: 4. username
15866:   where domain,username are the domain of the portfolio owner 
15867:   (either a user or a course) 
15868: 
15869: Returns:
15870: 1. result of additions or updates ('ok' or 'error', with error message). 
15871: 2. result of deletions ('ok' or 'error', with error message).
15872: 3. reference to hash of any new or updated access controls.
15873: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15874:    key = integer (inbound ID)
15875:    value = uniqueID
15876: 
15877: =item *
15878: 
15879: get_timebased_id():
15880: 
15881: Attempts to get a unique timestamp-based suffix for use with items added to a 
15882: course via the Course Editor (e.g., folders, composite pages, 
15883: group bulletin boards).
15884: 
15885: Args: (first three required; six others optional)
15886: 
15887: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15888:    docssequence, or name of group
15889: 
15890: 2. keyid (alphanumeric): name of temporary locking key in hash,
15891:    e.g., num, boardids
15892: 
15893: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15894:    file will be named nohist_namespace.db
15895: 
15896: 4. cdom: domain of course; default is current course domain from %env
15897: 
15898: 5. cnum: course number; default is current course number from %env
15899: 
15900: 6. idtype: set to concat if an additional digit is to be appended to the 
15901:    unix timestamp to form the suffix, if the plain timestamp is already
15902:    in use.  Default is to not do this, but simply increment the unix 
15903:    timestamp by 1 until a unique key is obtained.
15904: 
15905: 7. who: holder of locking key; defaults to user:domain for user.
15906: 
15907: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15908:    retrying); default is 3.
15909: 
15910: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15911: 
15912: Returns:
15913: 
15914: 1. suffix obtained (numeric)
15915: 
15916: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15917: 
15918: 3. error: contains (localized) error message if an error occurred.
15919: 
15920: 
15921: =back
15922: 
15923: =head2 HTTP Helper Routines
15924: 
15925: =over 4
15926: 
15927: =item *
15928: 
15929: escape() : unpack non-word characters into CGI-compatible hex codes
15930: 
15931: =item *
15932: 
15933: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15934: 
15935: =back
15936: 
15937: =head1 PRIVATE SUBROUTINES
15938: 
15939: =head2 Underlying communication routines (Shouldn't call)
15940: 
15941: =over 4
15942: 
15943: =item *
15944: 
15945: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15946: 
15947: =item *
15948: 
15949: reply() : uses subreply to send a message to remote machine, logs all failures
15950: 
15951: =item *
15952: 
15953: critical() : passes a critical message to another server; if cannot
15954: get through then place message in connection buffer directory and
15955: returns con_delayed, if incapable of saving message, returns
15956: con_failed
15957: 
15958: =item *
15959: 
15960: reconlonc() : tries to reconnect lonc client processes.
15961: 
15962: =back
15963: 
15964: =head2 Resource Access Logging
15965: 
15966: =over 4
15967: 
15968: =item *
15969: 
15970: flushcourselogs() : flush (save) buffer logs and access logs
15971: 
15972: =item *
15973: 
15974: courselog($what) : save message for course in hash
15975: 
15976: =item *
15977: 
15978: courseacclog($what) : save message for course using &courselog().  Perform
15979: special processing for specific resource types (problems, exams, quizzes, etc).
15980: 
15981: =item *
15982: 
15983: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15984: as a PerlChildExitHandler
15985: 
15986: =back
15987: 
15988: =head2 Other
15989: 
15990: =over 4
15991: 
15992: =item *
15993: 
15994: symblist($mapname,%newhash) : update symbolic storage links
15995: 
15996: =back
15997: 
15998: =cut
15999: 

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