File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1394: download - view: text, annotated - select for diffs
Sat Dec 8 15:17:25 2018 UTC (5 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Untie tied hashes.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1394 2018/12/08 15:17:25 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:         untie(%disk_env);
  715: 	return undef;
  716:     }
  717: 
  718:     if (ref($userhashref) eq 'HASH') {
  719:         $userhashref->{'name'} = $disk_env{'user.name'};
  720:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  721:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  722:         if ($userhashref->{'lti'}) {
  723:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  724:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  725:         }
  726:     }
  727:     untie(%disk_env);
  728: 
  729:     return $handle;
  730: }
  731: 
  732: sub timed_flock {
  733:     my ($file,$lock_type) = @_;
  734:     my $failed=0;
  735:     eval {
  736: 	local $SIG{__DIE__}='DEFAULT';
  737: 	local $SIG{ALRM}=sub {
  738: 	    $failed=1;
  739: 	    die("failed lock");
  740: 	};
  741: 	alarm(13);
  742: 	flock($file,$lock_type);
  743: 	alarm(0);
  744:     };
  745:     if ($failed) {
  746: 	return undef;
  747:     } else {
  748: 	return 1;
  749:     }
  750: }
  751: 
  752: sub get_sessionfile_vars {
  753:     my ($handle,$lonidsdir,$storearr) = @_;
  754:     my %returnhash;
  755:     unless (ref($storearr) eq 'ARRAY') {
  756:         return %returnhash;
  757:     }
  758:     if (-l "$lonidsdir/$handle.id") {
  759:         my $link = readlink("$lonidsdir/$handle.id");
  760:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  761:             $handle = $1;
  762:         }
  763:     }
  764:     if ((-e "$lonidsdir/$handle.id") &&
  765:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  766:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  767:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  768:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  769:                 flock($idf,LOCK_SH);
  770:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  771:                         &GDBM_READER(),0640)) {
  772:                     foreach my $item (@{$storearr}) {
  773:                         $returnhash{$item} = $disk_env{$item};
  774:                     }
  775:                     untie(%disk_env);
  776:                 }
  777:             }
  778:         }
  779:     }
  780:     return %returnhash;
  781: }
  782: 
  783: # ---------------------------------------------------------- Append Environment
  784: 
  785: sub appenv {
  786:     my ($newenv,$roles) = @_;
  787:     if (ref($newenv) eq 'HASH') {
  788:         foreach my $key (keys(%{$newenv})) {
  789:             my $refused = 0;
  790: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  791:                 $refused = 1;
  792:                 if (ref($roles) eq 'ARRAY') {
  793:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  794:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  795:                         $refused = 0;
  796:                     }
  797:                 }
  798:             }
  799:             if ($refused) {
  800:                 &logthis("<font color=\"blue\">WARNING: ".
  801:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  802:                          .'</font>');
  803: 	        delete($newenv->{$key});
  804:             } else {
  805:                 $env{$key}=$newenv->{$key};
  806:             }
  807:         }
  808:         my $lonids = $perlvar{'lonIDsDir'};
  809:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  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: 	        while (my ($key,$value) = each(%{$newenv})) {
  817: 	            $disk_env{$key} = $value;
  818: 	        }
  819: 	        untie(%disk_env);
  820:             }
  821:         }
  822:     }
  823:     return 'ok';
  824: }
  825: # ----------------------------------------------------- Delete from Environment
  826: 
  827: sub delenv {
  828:     my ($delthis,$regexp,$roles) = @_;
  829:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  830:         my $refused = 1;
  831:         if (ref($roles) eq 'ARRAY') {
  832:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  833:             if (grep(/^\Q$role\E$/,@{$roles})) {
  834:                 $refused = 0;
  835:             }
  836:         }
  837:         if ($refused) {
  838:             &logthis("<font color=\"blue\">WARNING: ".
  839:                      "Attempt to delete from environment ".$delthis);
  840:             return 'error';
  841:         }
  842:     }
  843:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  844:     if ($opened
  845: 	&& &timed_flock($env_file,LOCK_EX)
  846: 	&&
  847: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  848: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  849: 	foreach my $key (keys(%disk_env)) {
  850: 	    if ($regexp) {
  851:                 if ($key=~/^$delthis/) {
  852:                     delete($env{$key});
  853:                     delete($disk_env{$key});
  854:                 } 
  855:             } else {
  856:                 if ($key=~/^\Q$delthis\E/) {
  857: 		    delete($env{$key});
  858: 		    delete($disk_env{$key});
  859: 	        }
  860:             }
  861: 	}
  862: 	untie(%disk_env);
  863:     }
  864:     return 'ok';
  865: }
  866: 
  867: sub get_env_multiple {
  868:     my ($name) = @_;
  869:     my @values;
  870:     if (defined($env{$name})) {
  871:         # exists is it an array
  872:         if (ref($env{$name})) {
  873:             @values=@{ $env{$name} };
  874:         } else {
  875:             $values[0]=$env{$name};
  876:         }
  877:     }
  878:     return(@values);
  879: }
  880: 
  881: # ------------------------------------------------------------------- Locking
  882: 
  883: sub set_lock {
  884:     my ($text)=@_;
  885:     $locknum++;
  886:     my $id=$$.'-'.$locknum;
  887:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  888:              'session.lock.'.$id => $text});
  889:     return $id;
  890: }
  891: 
  892: sub get_locks {
  893:     my $num=0;
  894:     my %texts=();
  895:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  896:        if ($lock=~/\w/) {
  897:           $num++;
  898:           $texts{$lock}=$env{'session.lock.'.$lock};
  899:        }
  900:    }
  901:    return ($num,%texts);
  902: }
  903: 
  904: sub remove_lock {
  905:     my ($id)=@_;
  906:     my $newlocks='';
  907:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  908:        if (($lock=~/\w/) && ($lock ne $id)) {
  909:           $newlocks.=','.$lock;
  910:        }
  911:     }
  912:     &appenv({'session.locks' => $newlocks});
  913:     &delenv('session.lock.'.$id);
  914: }
  915: 
  916: sub remove_all_locks {
  917:     my $activelocks=$env{'session.locks'};
  918:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  919:        if ($lock=~/\w/) {
  920:           &remove_lock($lock);
  921:        }
  922:     }
  923: }
  924: 
  925: 
  926: # ------------------------------------------ Find out current server userload
  927: sub userload {
  928:     my $numusers=0;
  929:     {
  930: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  931: 	my $filename;
  932: 	my $curtime=time;
  933: 	while ($filename=readdir(LONIDS)) {
  934: 	    next if ($filename eq '.' || $filename eq '..');
  935: 	    next if ($filename =~ /publicuser_\d+\.id/);
  936:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  937: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  938: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  939: 	}
  940: 	closedir(LONIDS);
  941:     }
  942:     my $userloadpercent=0;
  943:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  944:     if ($maxuserload) {
  945: 	$userloadpercent=100*$numusers/$maxuserload;
  946:     }
  947:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  948:     return $userloadpercent;
  949: }
  950: 
  951: # ------------------------------ Find server with least workload from spare.tab
  952: 
  953: sub spareserver {
  954:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  955:     my $spare_server;
  956:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  957:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  958:                                                      :  $userloadpercent;
  959:     my ($uint_dom,$remotesessions);
  960:     if (($udom ne '') && (&domain($udom) ne '')) {
  961:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  962:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  963:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  964:         $remotesessions = $udomdefaults{'remotesessions'};
  965:     }
  966:     my $spareshash = &this_host_spares($udom);
  967:     if (ref($spareshash) eq 'HASH') {
  968:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  969:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  970:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  971:                                              $try_server));
  972: 	        ($spare_server, $lowest_load) =
  973: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  974:             }
  975:         }
  976: 
  977:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  978: 
  979:         if (!$found_server) {
  980:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  981: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  982:                     next unless (&spare_can_host($udom,$uint_dom,
  983:                                                  $remotesessions,$try_server));
  984: 	            ($spare_server, $lowest_load) =
  985: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  986:                 }
  987: 	    }
  988:         }
  989:     }
  990: 
  991:     if (!$want_server_name) {
  992:         my $protocol = 'http';
  993:         if ($protocol{$spare_server} eq 'https') {
  994:             $protocol = $protocol{$spare_server};
  995:         }
  996:         if (defined($spare_server)) {
  997:             my $hostname = &hostname($spare_server);
  998:             if (defined($hostname)) {
  999: 	        $spare_server = $protocol.'://'.$hostname;
 1000:             }
 1001:         }
 1002:     }
 1003:     return $spare_server;
 1004: }
 1005: 
 1006: sub compare_server_load {
 1007:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1008: 
 1009:     if ($required) {
 1010:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1011:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1012:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1013:         if (($major eq '' && $minor eq '') ||
 1014:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1015:             return ($spare_server,$lowest_load);
 1016:         }
 1017:     }
 1018: 
 1019:     my $loadans     = &reply('load',    $try_server);
 1020:     my $userloadans = &reply('userload',$try_server);
 1021: 
 1022:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1023: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1024:     }
 1025: 
 1026:     my $load;
 1027:     if ($loadans =~ /\d/) {
 1028: 	if ($userloadans =~ /\d/) {
 1029: 	    #both are numbers, pick the bigger one
 1030: 	    $load = ($loadans > $userloadans) ? $loadans 
 1031: 		                              : $userloadans;
 1032: 	} else {
 1033: 	    $load = $loadans;
 1034: 	}
 1035:     } else {
 1036: 	$load = $userloadans;
 1037:     }
 1038: 
 1039:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1040: 	$spare_server = $try_server;
 1041: 	$lowest_load  = $load;
 1042:     }
 1043:     return ($spare_server,$lowest_load);
 1044: }
 1045: 
 1046: # --------------------------- ask offload servers if user already has a session
 1047: sub find_existing_session {
 1048:     my ($udom,$uname) = @_;
 1049:     my $spareshash = &this_host_spares($udom);
 1050:     if (ref($spareshash) eq 'HASH') {
 1051:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1052:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1053:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1054:             }
 1055:         }
 1056:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1057:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1058:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1059:             }
 1060:         }
 1061:     }
 1062:     return;
 1063: }
 1064: 
 1065: # check if user's browser sent load balancer cookie and server still has session
 1066: # and is not overloaded.
 1067: sub check_for_balancer_cookie {
 1068:     my ($r,$update_mtime) = @_;
 1069:     my ($otherserver,$cookie);
 1070:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1071:     if (exists($cookies{'balanceID'})) {
 1072:         my $balid = $cookies{'balanceID'};
 1073:         $cookie=&LONCAPA::clean_handle($balid->value);
 1074:         my $balancedir=$r->dir_config('lonBalanceDir');
 1075:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1076:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1077:                 my ($possudom,$possuname) = ($1,$2);
 1078:                 my $has_session = 0;
 1079:                 if ((&domain($possudom) ne '') &&
 1080:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1081:                     my $try_server;
 1082:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1083:                     if ($opened) {
 1084:                         flock($idf,LOCK_SH);
 1085:                         while (my $line = <$idf>) {
 1086:                             chomp($line);
 1087:                             if (&hostname($line) ne '') {
 1088:                                 $try_server = $line;
 1089:                                 last;
 1090:                             }
 1091:                         }
 1092:                         close($idf);
 1093:                         if (($try_server) &&
 1094:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1095:                             my $lowest_load = 30000;
 1096:                             ($otherserver,$lowest_load) =
 1097:                                 &compare_server_load($try_server,undef,$lowest_load);
 1098:                             if ($otherserver ne '' && $lowest_load < 100) {
 1099:                                 $has_session = 1;
 1100:                             } else {
 1101:                                 undef($otherserver);
 1102:                             }
 1103:                         }
 1104:                     }
 1105:                 }
 1106:                 if ($has_session) {
 1107:                     if ($update_mtime) {
 1108:                         my $atime = my $mtime = time;
 1109:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1110:                     }
 1111:                 } else {
 1112:                     unlink("$balancedir/$cookie.id");
 1113:                 }
 1114:             }
 1115:         }
 1116:     }
 1117:     return ($otherserver,$cookie);
 1118: }
 1119: 
 1120: sub delbalcookie {
 1121:     my ($cookie,$balancer) =@_;
 1122:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1123:         my ($udom,$uname) = ($1,$2);
 1124:         my $uprimary_id = &domain($udom,'primary');
 1125:         my $uintdom = &internet_dom($uprimary_id);
 1126:         my $intdom = &internet_dom($balancer);
 1127:         my $serverhomedom = &host_domain($balancer);
 1128:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1129:             return &reply("delbalcookie:$cookie",$balancer);
 1130:         }
 1131:     }
 1132: }
 1133: 
 1134: # -------------------------------- ask if server already has a session for user
 1135: sub has_user_session {
 1136:     my ($lonid,$udom,$uname) = @_;
 1137:     my $result = &reply(join(':','userhassession',
 1138: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1139:     return 1 if ($result eq 'ok');
 1140: 
 1141:     return 0;
 1142: }
 1143: 
 1144: # --------- determine least loaded server in a user's domain which allows login
 1145: 
 1146: sub choose_server {
 1147:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1148:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1149:     my %servers = &get_servers($udom);
 1150:     my $lowest_load = 30000;
 1151:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1152:     if ($skiploadbal) {
 1153:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1154:         unless (defined($cached)) {
 1155:             my $cachetime = 60*60*24;
 1156:             my %domconfig =
 1157:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1158:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1159:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1160:                                            $cachetime);
 1161:             }
 1162:         }
 1163:     }
 1164:     foreach my $lonhost (keys(%servers)) {
 1165:         if ($skiploadbal) {
 1166:             if (ref($balancers) eq 'HASH') {
 1167:                 next if (exists($balancers->{$lonhost}));
 1168:             }
 1169:         }
 1170:         my $loginvia;
 1171:         if ($checkloginvia) {
 1172:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1173:             if ($loginvia) {
 1174:                 my ($server,$path) = split(/:/,$loginvia);
 1175:                 ($login_host, $lowest_load) =
 1176:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1177:                 if ($login_host eq $server) {
 1178:                     $portal_path = $path;
 1179:                     $isredirect = 1;
 1180:                 }
 1181:             } else {
 1182:                 ($login_host, $lowest_load) =
 1183:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1184:                 if ($login_host eq $lonhost) {
 1185:                     $portal_path = '';
 1186:                     $isredirect = ''; 
 1187:                 }
 1188:             }
 1189:         } else {
 1190:             ($login_host, $lowest_load) =
 1191:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1192:         }
 1193:     }
 1194:     if ($login_host ne '') {
 1195:         $hostname = &hostname($login_host);
 1196:     }
 1197:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1198: }
 1199: 
 1200: # --------------------------------------------- Try to change a user's password
 1201: 
 1202: sub changepass {
 1203:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1204:     $currentpass = &escape($currentpass);
 1205:     $newpass     = &escape($newpass);
 1206:     my $lonhost = $perlvar{'lonHostID'};
 1207:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1208: 		       $server);
 1209:     if (! $answer) {
 1210: 	&logthis("No reply on password change request to $server ".
 1211: 		 "by $uname in domain $udom.");
 1212:     } elsif ($answer =~ "^ok") {
 1213:         &logthis("$uname in $udom successfully changed their password ".
 1214: 		 "on $server.");
 1215:     } elsif ($answer =~ "^pwchange_failure") {
 1216: 	&logthis("$uname in $udom was unable to change their password ".
 1217: 		 "on $server.  The action was blocked by either lcpasswd ".
 1218: 		 "or pwchange");
 1219:     } elsif ($answer =~ "^non_authorized") {
 1220:         &logthis("$uname in $udom did not get their password correct when ".
 1221: 		 "attempting to change it on $server.");
 1222:     } elsif ($answer =~ "^auth_mode_error") {
 1223:         &logthis("$uname in $udom attempted to change their password despite ".
 1224: 		 "not being locally or internally authenticated on $server.");
 1225:     } elsif ($answer =~ "^unknown_user") {
 1226:         &logthis("$uname in $udom attempted to change their password ".
 1227: 		 "on $server but were unable to because $server is not ".
 1228: 		 "their home server.");
 1229:     } elsif ($answer =~ "^refused") {
 1230: 	&logthis("$server refused to change $uname in $udom password because ".
 1231: 		 "it was sent an unencrypted request to change the password.");
 1232:     } elsif ($answer =~ "invalid_client") {
 1233:         &logthis("$server refused to change $uname in $udom password because ".
 1234:                  "it was a reset by e-mail originating from an invalid server.");
 1235:     }
 1236:     return $answer;
 1237: }
 1238: 
 1239: # ----------------------- Try to determine user's current authentication scheme
 1240: 
 1241: sub queryauthenticate {
 1242:     my ($uname,$udom)=@_;
 1243:     my $uhome=&homeserver($uname,$udom);
 1244:     if (!$uhome) {
 1245: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1246: 	return 'no_host';
 1247:     }
 1248:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1249:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1250: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1251:     }
 1252:     return $answer;
 1253: }
 1254: 
 1255: # --------- Try to authenticate user from domain's lib servers (first this one)
 1256: 
 1257: sub authenticate {
 1258:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1259:     $upass=&escape($upass);
 1260:     $uname= &LONCAPA::clean_username($uname);
 1261:     my $uhome=&homeserver($uname,$udom,1);
 1262:     my $newhome;
 1263:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1264: # Maybe the machine was offline and only re-appeared again recently?
 1265:         &reconlonc();
 1266: # One more
 1267: 	$uhome=&homeserver($uname,$udom,1);
 1268:         if (($uhome eq 'no_host') && $checkdefauth) {
 1269:             if (defined(&domain($udom,'primary'))) {
 1270:                 $newhome=&domain($udom,'primary');
 1271:             }
 1272:             if ($newhome ne '') {
 1273:                 $uhome = $newhome;
 1274:             }
 1275:         }
 1276: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1277: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1278: 	    return 'no_host';
 1279:         }
 1280:     }
 1281:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1282:     if ($answer eq 'authorized') {
 1283:         if ($newhome) {
 1284:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1285:             return 'no_account_on_host'; 
 1286:         } else {
 1287:             &logthis("User $uname at $udom authorized by $uhome");
 1288:             return $uhome;
 1289:         }
 1290:     }
 1291:     if ($answer eq 'non_authorized') {
 1292: 	&logthis("User $uname at $udom rejected by $uhome");
 1293: 	return 'no_host'; 
 1294:     }
 1295:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1296:     return 'no_host';
 1297: }
 1298: 
 1299: sub can_host_session {
 1300:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1301:     my $canhost = 1;
 1302:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1303:     if (ref($remotesessions) eq 'HASH') {
 1304:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1305:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1306:                 $canhost = 0;
 1307:             } else {
 1308:                 $canhost = 1;
 1309:             }
 1310:         }
 1311:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1312:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1313:                 $canhost = 1;
 1314:             } else {
 1315:                 $canhost = 0;
 1316:             }
 1317:         }
 1318:         if ($canhost) {
 1319:             if ($remotesessions->{'version'} ne '') {
 1320:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1321:                 if ($reqmajor ne '' && $reqminor ne '') {
 1322:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1323:                         my $major = $1;
 1324:                         my $minor = $2;
 1325:                         if (($major < $reqmajor ) ||
 1326:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1327:                             $canhost = 0;
 1328:                         }
 1329:                     } else {
 1330:                         $canhost = 0;
 1331:                     }
 1332:                 }
 1333:             }
 1334:         }
 1335:     }
 1336:     if ($canhost) {
 1337:         if (ref($hostedsessions) eq 'HASH') {
 1338:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1339:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1340:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1341:                 if (($uint_dom ne '') && 
 1342:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1343:                     $canhost = 0;
 1344:                 } else {
 1345:                     $canhost = 1;
 1346:                 }
 1347:             }
 1348:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1349:                 if (($uint_dom ne '') && 
 1350:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1351:                     $canhost = 1;
 1352:                 } else {
 1353:                     $canhost = 0;
 1354:                 }
 1355:             }
 1356:         }
 1357:     }
 1358:     return $canhost;
 1359: }
 1360: 
 1361: sub spare_can_host {
 1362:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1363:     my $canhost=1;
 1364:     my $try_server_hostname = &hostname($try_server);
 1365:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1366:     my $serverhomedom = &host_domain($serverhomeID);
 1367:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1368:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1369:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1370:             $canhost = 0;
 1371:         }
 1372:     }
 1373:     if (($canhost) && ($uint_dom)) {
 1374:         my @intdoms;
 1375:         my $internet_names = &get_internet_names($try_server);
 1376:         if (ref($internet_names) eq 'ARRAY') {
 1377:             @intdoms = @{$internet_names};
 1378:         }
 1379:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1380:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1381:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1382:                                          $remotesessions,
 1383:                                          $defdomdefaults{'hostedsessions'});
 1384:         }
 1385:     }
 1386:     return $canhost;
 1387: }
 1388: 
 1389: sub this_host_spares {
 1390:     my ($dom) = @_;
 1391:     my ($dom_in_use,$lonhost_in_use,$result);
 1392:     my @hosts = &current_machine_ids();
 1393:     foreach my $lonhost (@hosts) {
 1394:         if (&host_domain($lonhost) eq $dom) {
 1395:             $dom_in_use = $dom;
 1396:             $lonhost_in_use = $lonhost;
 1397:             last;
 1398:         }
 1399:     }
 1400:     if ($dom_in_use ne '') {
 1401:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1402:     }
 1403:     if (ref($result) ne 'HASH') {
 1404:         $lonhost_in_use = $perlvar{'lonHostID'};
 1405:         $dom_in_use = &host_domain($lonhost_in_use);
 1406:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1407:         if (ref($result) ne 'HASH') {
 1408:             $result = \%spareid;
 1409:         }
 1410:     }
 1411:     return $result;
 1412: }
 1413: 
 1414: sub spares_for_offload  {
 1415:     my ($dom_in_use,$lonhost_in_use) = @_;
 1416:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1417:     if (defined($cached)) {
 1418:         return $result;
 1419:     } else {
 1420:         my $cachetime = 60*60*24;
 1421:         my %domconfig =
 1422:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1423:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1424:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1425:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1426:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return;
 1432: }
 1433: 
 1434: sub get_lonbalancer_config {
 1435:     my ($servers) = @_;
 1436:     my ($currbalancer,$currtargets);
 1437:     if (ref($servers) eq 'HASH') {
 1438:         foreach my $server (keys(%{$servers})) {
 1439:             my %what = (
 1440:                          spareid => 1,
 1441:                          perlvar => 1,
 1442:                        );
 1443:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1444:             if ($result eq 'ok') {
 1445:                 if (ref($returnhash) eq 'HASH') {
 1446:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1447:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1448:                             $currbalancer = $server;
 1449:                             $currtargets = {};
 1450:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1451:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1452:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1453:                                 }
 1454:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1455:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1456:                                 }
 1457:                             }
 1458:                             last;
 1459:                         }
 1460:                     }
 1461:                 }
 1462:             }
 1463:         }
 1464:     }
 1465:     return ($currbalancer,$currtargets);
 1466: }
 1467: 
 1468: sub check_loadbalancing {
 1469:     my ($uname,$udom,$caller) = @_;
 1470:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1471:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1472:     my $lonhost = $perlvar{'lonHostID'};
 1473:     my @hosts = &current_machine_ids();
 1474:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1475:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1476:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1477:     my $serverhomedom = &host_domain($lonhost);
 1478:     my $domneedscache;
 1479:     my $cachetime = 60*60*24;
 1480: 
 1481:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1482:         $dom_in_use = $udom;
 1483:         $homeintdom = 1;
 1484:     } else {
 1485:         $dom_in_use = $serverhomedom;
 1486:     }
 1487:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1488:     unless (defined($cached)) {
 1489:         my %domconfig =
 1490:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1491:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1492:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1493:         } else {
 1494:             $domneedscache = $dom_in_use;
 1495:         }
 1496:     }
 1497:     if (ref($result) eq 'HASH') {
 1498:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1499:             &check_balancer_result($result,@hosts);
 1500:         if ($is_balancer) {
 1501:             if (ref($currrules) eq 'HASH') {
 1502:                 if ($homeintdom) {
 1503:                     if ($uname ne '') {
 1504:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1505:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1506:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1507:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1508:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1509:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1510:                             }
 1511:                         }
 1512:                         if ($rule_in_effect eq '') {
 1513:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1514:                             if ($userenv{'inststatus'} ne '') {
 1515:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1516:                                 my ($othertitle,$usertypes,$types) =
 1517:                                     &Apache::loncommon::sorted_inst_types($udom);
 1518:                                 if (ref($types) eq 'ARRAY') {
 1519:                                     foreach my $type (@{$types}) {
 1520:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1521:                                             if (exists($currrules->{$type})) {
 1522:                                                 $rule_in_effect = $currrules->{$type};
 1523:                                             }
 1524:                                         }
 1525:                                     }
 1526:                                 }
 1527:                             } else {
 1528:                                 if (exists($currrules->{'default'})) {
 1529:                                     $rule_in_effect = $currrules->{'default'};
 1530:                                 }
 1531:                             }
 1532:                         }
 1533:                     } else {
 1534:                         if (exists($currrules->{'default'})) {
 1535:                             $rule_in_effect = $currrules->{'default'};
 1536:                         }
 1537:                     }
 1538:                 } else {
 1539:                     if ($currrules->{'_LC_external'} ne '') {
 1540:                         $rule_in_effect = $currrules->{'_LC_external'};
 1541:                     }
 1542:                 }
 1543:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1544:                                                        $uname,$udom);
 1545:             }
 1546:         }
 1547:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1548:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1549:         unless (defined($cached)) {
 1550:             my %domconfig =
 1551:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1552:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1553:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1554:             } else {
 1555:                 $domneedscache = $serverhomedom;
 1556:             }
 1557:         }
 1558:         if (ref($result) eq 'HASH') {
 1559:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1560:                 &check_balancer_result($result,@hosts);
 1561:             if ($is_balancer) {
 1562:                 if (ref($currrules) eq 'HASH') {
 1563:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1564:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1565:                     }
 1566:                 }
 1567:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1568:                                                        $uname,$udom);
 1569:             }
 1570:         } else {
 1571:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1572:                 $is_balancer = 1;
 1573:                 $offloadto = &this_host_spares($dom_in_use);
 1574:             }
 1575:             unless (defined($cached)) {
 1576:                 $domneedscache = $serverhomedom;
 1577:             }
 1578:         }
 1579:     } else {
 1580:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1581:             $is_balancer = 1;
 1582:             $offloadto = &this_host_spares($dom_in_use);
 1583:         }
 1584:         unless (defined($cached)) {
 1585:             $domneedscache = $serverhomedom;
 1586:         }
 1587:     }
 1588:     if ($domneedscache) {
 1589:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1590:     }
 1591:     if ($is_balancer) {
 1592:         my $lowest_load = 30000;
 1593:         if (ref($offloadto) eq 'HASH') {
 1594:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1595:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1596:                     ($otherserver,$lowest_load) =
 1597:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1598:                 }
 1599:             }
 1600:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1601: 
 1602:             if (!$found_server) {
 1603:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1604:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1605:                         ($otherserver,$lowest_load) =
 1606:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1607:                     }
 1608:                 }
 1609:             }
 1610:         } elsif (ref($offloadto) eq 'ARRAY') {
 1611:             if (@{$offloadto} == 1) {
 1612:                 $otherserver = $offloadto->[0];
 1613:             } elsif (@{$offloadto} > 1) {
 1614:                 foreach my $try_server (@{$offloadto}) {
 1615:                     ($otherserver,$lowest_load) =
 1616:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1617:                 }
 1618:             }
 1619:         }
 1620:         unless ($caller eq 'login') {
 1621:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1622:                 $is_balancer = 0;
 1623:                 if ($uname ne '' && $udom ne '') {
 1624:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1625:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1626:                                  'user.loadbalcheck.time' => time});
 1627:                     }
 1628:                 }
 1629:             }
 1630:         }
 1631:         unless ($homeintdom) {
 1632:             undef($setcookie);
 1633:         }
 1634:     }
 1635:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1636: }
 1637: 
 1638: sub check_balancer_result {
 1639:     my ($result,@hosts) = @_;
 1640:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1641:     if (ref($result) eq 'HASH') {
 1642:         if ($result->{'lonhost'} ne '') {
 1643:             my $currbalancer = $result->{'lonhost'};
 1644:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1645:                 $is_balancer = 1;
 1646:                 $currtargets = $result->{'targets'};
 1647:                 $currrules = $result->{'rules'};
 1648:             }
 1649:             $dom_balancers = $currbalancer;
 1650:         } else {
 1651:             if (keys(%{$result})) {
 1652:                 foreach my $key (keys(%{$result})) {
 1653:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1654:                         (ref($result->{$key}) eq 'HASH')) {
 1655:                         $is_balancer = 1;
 1656:                         $currrules = $result->{$key}{'rules'};
 1657:                         $currtargets = $result->{$key}{'targets'};
 1658:                         $setcookie = $result->{$key}{'cookie'};
 1659:                         last;
 1660:                     }
 1661:                 }
 1662:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1663:             }
 1664:         }
 1665:     }
 1666:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1667: }
 1668: 
 1669: sub get_loadbalancer_targets {
 1670:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1671:     my $offloadto;
 1672:     if ($rule_in_effect eq 'none') {
 1673:         return [$perlvar{'lonHostID'}];
 1674:     } elsif ($rule_in_effect eq '') {
 1675:         $offloadto = $currtargets;
 1676:     } else {
 1677:         if ($rule_in_effect eq 'homeserver') {
 1678:             my $homeserver = &homeserver($uname,$udom);
 1679:             if ($homeserver ne 'no_host') {
 1680:                 $offloadto = [$homeserver];
 1681:             }
 1682:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1683:             my %domconfig =
 1684:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1685:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1686:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1687:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1688:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1689:                     }
 1690:                 }
 1691:             } else {
 1692:                 my %servers = &internet_dom_servers($udom);
 1693:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1694:                 if (&hostname($remotebalancer) ne '') {
 1695:                     $offloadto = [$remotebalancer];
 1696:                 }
 1697:             }
 1698:         } elsif (&hostname($rule_in_effect) ne '') {
 1699:             $offloadto = [$rule_in_effect];
 1700:         }
 1701:     }
 1702:     return $offloadto;
 1703: }
 1704: 
 1705: sub internet_dom_servers {
 1706:     my ($dom) = @_;
 1707:     my (%uniqservers,%servers);
 1708:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1709:     my @machinedoms = &machine_domains($primaryserver);
 1710:     foreach my $mdom (@machinedoms) {
 1711:         my %currservers = %servers;
 1712:         my %server = &get_servers($mdom);
 1713:         %servers = (%currservers,%server);
 1714:     }
 1715:     my %by_hostname;
 1716:     foreach my $id (keys(%servers)) {
 1717:         push(@{$by_hostname{$servers{$id}}},$id);
 1718:     }
 1719:     foreach my $hostname (sort(keys(%by_hostname))) {
 1720:         if (@{$by_hostname{$hostname}} > 1) {
 1721:             my $match = 0;
 1722:             foreach my $id (@{$by_hostname{$hostname}}) {
 1723:                 if (&host_domain($id) eq $dom) {
 1724:                     $uniqservers{$id} = $hostname;
 1725:                     $match = 1;
 1726:                 }
 1727:             }
 1728:             unless ($match) {
 1729:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1730:             }
 1731:         } else {
 1732:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1733:         }
 1734:     }
 1735:     return %uniqservers;
 1736: }
 1737: 
 1738: sub trusted_domains {
 1739:     my ($cmdtype,$calldom) = @_;
 1740:     my ($trusted,$untrusted);
 1741:     if (&domain($calldom) eq '') {
 1742:         return ($trusted,$untrusted);
 1743:     }
 1744:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1745:         return ($trusted,$untrusted);
 1746:     }
 1747:     my $callprimary = &domain($calldom,'primary');
 1748:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1749:     if ($intcalldom eq '') {
 1750:         return ($trusted,$untrusted);
 1751:     }
 1752: 
 1753:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1754:     unless (defined($cached)) {
 1755:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1756:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1757:         $trustconfig = $domconfig{'trust'};
 1758:     }
 1759:     if (ref($trustconfig)) {
 1760:         my (%possexc,%possinc,@allexc,@allinc); 
 1761:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1762:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1763:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1764:             }
 1765:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1766:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1767:             }
 1768:         }
 1769:         if (keys(%possexc)) {
 1770:             if (keys(%possinc)) {
 1771:                 foreach my $key (sort(keys(%possexc))) {
 1772:                     next if ($key eq $intcalldom);
 1773:                     unless ($possinc{$key}) {
 1774:                         push(@allexc,$key);
 1775:                     }
 1776:                 }
 1777:             } else {
 1778:                 @allexc = sort(keys(%possexc));
 1779:             }
 1780:         }
 1781:         if (keys(%possinc)) {
 1782:             $possinc{$intcalldom} = 1;
 1783:             @allinc = sort(keys(%possinc));
 1784:         }
 1785:         if ((@allexc > 0) || (@allinc > 0)) {
 1786:             my %doms_by_intdom;
 1787:             my %allintdoms = &all_host_intdom();
 1788:             my %alldoms = &all_host_domain();
 1789:             foreach my $key (%allintdoms) {
 1790:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1791:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1792:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1793:                     }
 1794:                 } else {
 1795:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1796:                 }
 1797:             }
 1798:             foreach my $exc (@allexc) {
 1799:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1800:                     $untrusted = $doms_by_intdom{$exc};
 1801:                 }
 1802:             }
 1803:             foreach my $inc (@allinc) {
 1804:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1805:                     $trusted = $doms_by_intdom{$inc};
 1806:                 }
 1807:             }
 1808:         }
 1809:     }
 1810:     return ($trusted,$untrusted);
 1811: }
 1812: 
 1813: sub will_trust {
 1814:     my ($cmdtype,$domain,$possdom) = @_;
 1815:     return 1 if ($domain eq $possdom);
 1816:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1817:     my $willtrust; 
 1818:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1819:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1820:             $willtrust = 1;
 1821:         }
 1822:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1823:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1824:             $willtrust = 1;
 1825:         }
 1826:     } else {
 1827:         $willtrust = 1;
 1828:     }
 1829:     return $willtrust;
 1830: }
 1831: 
 1832: # ---------------------- Find the homebase for a user from domain's lib servers
 1833: 
 1834: my %homecache;
 1835: sub homeserver {
 1836:     my ($uname,$udom,$ignoreBadCache)=@_;
 1837:     my $index="$uname:$udom";
 1838: 
 1839:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1840: 
 1841:     my %servers = &get_servers($udom,'library');
 1842:     foreach my $tryserver (keys(%servers)) {
 1843:         next if ($ignoreBadCache ne 'true' && 
 1844: 		 exists($badServerCache{$tryserver}));
 1845: 
 1846: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1847: 	if ($answer eq 'found') {
 1848: 	    delete($badServerCache{$tryserver}); 
 1849: 	    return $homecache{$index}=$tryserver;
 1850: 	} elsif ($answer eq 'no_host') {
 1851: 	    $badServerCache{$tryserver}=1;
 1852: 	}
 1853:     }    
 1854:     return 'no_host';
 1855: }
 1856: 
 1857: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1858: 
 1859: sub idget {
 1860:     my ($udom,$idsref,$namespace)=@_;
 1861:     my %returnhash=();
 1862:     my @ids=(); 
 1863:     if (ref($idsref) eq 'ARRAY') {
 1864:         @ids = @{$idsref};
 1865:     } else {
 1866:         return %returnhash; 
 1867:     }
 1868:     if ($namespace eq '') {
 1869:         $namespace = 'ids';
 1870:     }
 1871:     
 1872:     my %servers = &get_servers($udom,'library');
 1873:     foreach my $tryserver (keys(%servers)) {
 1874: 	my $idlist=join('&', map { &escape($_); } @ids);
 1875: 	if ($namespace eq 'ids') {
 1876: 	    $idlist=~tr/A-Z/a-z/;
 1877: 	}
 1878: 	my $reply;
 1879: 	if ($namespace eq 'ids') {
 1880: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1881: 	} else {
 1882: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1883: 	}
 1884: 	my @answer=();
 1885: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1886: 	    @answer=split(/\&/,$reply);
 1887: 	}                    ;
 1888: 	my $i;
 1889: 	for ($i=0;$i<=$#ids;$i++) {
 1890: 	    if ($answer[$i]) {
 1891: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1892: 	    }
 1893: 	}
 1894:     }
 1895:     return %returnhash;
 1896: }
 1897: 
 1898: # ------------------------------------- Find the IDs behind a list of usernames
 1899: 
 1900: sub idrget {
 1901:     my ($udom,@unames)=@_;
 1902:     my %returnhash=();
 1903:     foreach my $uname (@unames) {
 1904:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1905:     }
 1906:     return %returnhash;
 1907: }
 1908: 
 1909: # Store away a list of names and associated student/employee IDs or clicker IDs
 1910: 
 1911: sub idput {
 1912:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1913:     my %servers=();
 1914:     my %ids=();
 1915:     my %byid = ();
 1916:     if (ref($idsref) eq 'HASH') {
 1917:         %ids=%{$idsref};
 1918:     }
 1919:     if ($namespace eq '') {
 1920:         $namespace = 'ids'; 
 1921:     }
 1922:     foreach my $uname (keys(%ids)) {
 1923: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1924:         if ($uhom eq '') {
 1925:             $uhom=&homeserver($uname,$udom);
 1926:         }
 1927:         if ($uhom ne 'no_host') {
 1928:             my $esc_unam=&escape($uname);
 1929:             if ($namespace eq 'ids') {
 1930:                 my $id=&escape($ids{$uname});
 1931:                 $id=~tr/A-Z/a-z/;
 1932:                 my $esc_unam=&escape($uname);
 1933:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1934:             } else {
 1935:                 my @currids = split(/,/,$ids{$uname});
 1936:                 foreach my $id (@currids) {
 1937:                     $byid{$uhom}{$id} .= $uname.',';
 1938:                 }
 1939:             }
 1940:         }
 1941:     }
 1942:     if ($namespace eq 'clickers') {
 1943:         foreach my $server (keys(%byid)) {
 1944:             if (ref($byid{$server}) eq 'HASH') {
 1945:                 foreach my $id (keys(%{$byid{$server}})) {
 1946:                     $byid{$server} =~ s/,$//;
 1947:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1948:                 }
 1949:             }
 1950:         }
 1951:     }
 1952:     foreach my $server (keys(%servers)) {
 1953:         $servers{$server} =~ s/\&$//;
 1954:         if ($namespace eq 'ids') {     
 1955:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1956:         } else {
 1957:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1958:         }
 1959:     }
 1960: }
 1961: 
 1962: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1963: 
 1964: sub iddel {
 1965:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1966:     my %result=();
 1967:     my %ids=();
 1968:     my %byid = ();
 1969:     if (ref($idshashref) eq 'HASH') {
 1970:         %ids=%{$idshashref};
 1971:     } else {
 1972:         return %result;
 1973:     }
 1974:     if ($namespace eq '') {
 1975:         $namespace = 'ids';
 1976:     }
 1977:     my %servers=();
 1978:     while (my ($id,$unamestr) = each(%ids)) {
 1979:         if ($namespace eq 'ids') {
 1980:             my $uhom = $uhome;
 1981:             if ($uhom eq '') { 
 1982:                 $uhom=&homeserver($unamestr,$udom);
 1983:             }
 1984:             if ($uhom ne 'no_host') {
 1985:                 $servers{$uhom}.='&'.&escape($id);
 1986:             }
 1987:          } else {
 1988:             my @curritems = split(/,/,$ids{$id});
 1989:             foreach my $uname (@curritems) {
 1990:                 my $uhom = $uhome;
 1991:                 if ($uhom eq '') {
 1992:                     $uhom=&homeserver($uname,$udom);
 1993:                 }
 1994:                 if ($uhom ne 'no_host') { 
 1995:                     $byid{$uhom}{$id} .= $uname.',';
 1996:                 }
 1997:             }
 1998:         }
 1999:     }
 2000:     if ($namespace eq 'clickers') {
 2001:         foreach my $server (keys(%byid)) {
 2002:             if (ref($byid{$server}) eq 'HASH') {
 2003:                 foreach my $id (keys(%{$byid{$server}})) {
 2004:                     $byid{$server}{$id} =~ s/,$//;
 2005:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2006:                 }
 2007:             }
 2008:         }
 2009:     }
 2010:     foreach my $server (keys(%servers)) {
 2011:         $servers{$server} =~ s/\&$//;
 2012:         if ($namespace eq 'ids') {
 2013:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2014:         } elsif ($namespace eq 'clickers') {
 2015:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2016:         }
 2017:     }
 2018:     return %result;
 2019: }
 2020: 
 2021: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2022: 
 2023: sub updateclickers {
 2024:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2025:     my %clickers;
 2026:     if (ref($idshashref) eq 'HASH') {
 2027:         %clickers=%{$idshashref};
 2028:     } else {
 2029:         return;
 2030:     }
 2031:     my $items='';
 2032:     foreach my $item (keys(%clickers)) {
 2033:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2034:     }
 2035:     $items=~s/\&$//;
 2036:     my $request = "updateclickers:$udom:$action:$items";
 2037:     if ($critical) {
 2038:         return &critical($request,$uhome);
 2039:     } else {
 2040:         return &reply($request,$uhome);
 2041:     }
 2042: }
 2043: 
 2044: # ------------------------------dump from db file owned by domainconfig user
 2045: sub dump_dom {
 2046:     my ($namespace, $udom, $regexp) = @_;
 2047: 
 2048:     $udom ||= $env{'user.domain'};
 2049: 
 2050:     return () unless $udom;
 2051: 
 2052:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2053: }
 2054: 
 2055: # ------------------------------------------ get items from domain db files   
 2056: 
 2057: sub get_dom {
 2058:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2059:     return if ($udom eq 'public');
 2060:     my $items='';
 2061:     foreach my $item (@$storearr) {
 2062:         $items.=&escape($item).'&';
 2063:     }
 2064:     $items=~s/\&$//;
 2065:     if (!$udom) {
 2066:         $udom=$env{'user.domain'};
 2067:         return if ($udom eq 'public');
 2068:         if (defined(&domain($udom,'primary'))) {
 2069:             $uhome=&domain($udom,'primary');
 2070:         } else {
 2071:             undef($uhome);
 2072:         }
 2073:     } else {
 2074:         if (!$uhome) {
 2075:             if (defined(&domain($udom,'primary'))) {
 2076:                 $uhome=&domain($udom,'primary');
 2077:             }
 2078:         }
 2079:     }
 2080:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2081:         my $rep;
 2082:         if ($namespace =~ /^enc/) {
 2083:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2084:         } else {
 2085:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2086:         }
 2087:         my %returnhash;
 2088:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2089:             return %returnhash;
 2090:         }
 2091:         my @pairs=split(/\&/,$rep);
 2092:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2093:             return @pairs;
 2094:         }
 2095:         my $i=0;
 2096:         foreach my $item (@$storearr) {
 2097:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2098:             $i++;
 2099:         }
 2100:         return %returnhash;
 2101:     } else {
 2102:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2103:     }
 2104: }
 2105: 
 2106: # -------------------------------------------- put items in domain db files 
 2107: 
 2108: sub put_dom {
 2109:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2110:     if (!$udom) {
 2111:         $udom=$env{'user.domain'};
 2112:         if (defined(&domain($udom,'primary'))) {
 2113:             $uhome=&domain($udom,'primary');
 2114:         } else {
 2115:             undef($uhome);
 2116:         }
 2117:     } else {
 2118:         if (!$uhome) {
 2119:             if (defined(&domain($udom,'primary'))) {
 2120:                 $uhome=&domain($udom,'primary');
 2121:             }
 2122:         }
 2123:     } 
 2124:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2125:         my $items='';
 2126:         foreach my $item (keys(%$storehash)) {
 2127:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2128:         }
 2129:         $items=~s/\&$//;
 2130:         if ($namespace =~ /^enc/) {
 2131:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2132:         } else {
 2133:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2134:         }
 2135:     } else {
 2136:         &logthis("put_dom failed - no homeserver and/or domain");
 2137:     }
 2138: }
 2139: 
 2140: # --------------------- newput for items in db file owned by domainconfig user
 2141: sub newput_dom {
 2142:     my ($namespace,$storehash,$udom) = @_;
 2143:     my $result;
 2144:     if (!$udom) {
 2145:         $udom=$env{'user.domain'};
 2146:     }
 2147:     if ($udom) {
 2148:         my $uname = &get_domainconfiguser($udom);
 2149:         $result = &newput($namespace,$storehash,$udom,$uname);
 2150:     }
 2151:     return $result;
 2152: }
 2153: 
 2154: # --------------------- delete for items in db file owned by domainconfig user
 2155: sub del_dom {
 2156:     my ($namespace,$storearr,$udom)=@_;
 2157:     if (ref($storearr) eq 'ARRAY') {
 2158:         if (!$udom) {
 2159:             $udom=$env{'user.domain'};
 2160:         }
 2161:         if ($udom) {
 2162:             my $uname = &get_domainconfiguser($udom); 
 2163:             return &del($namespace,$storearr,$udom,$uname);
 2164:         }
 2165:     }
 2166: }
 2167: 
 2168: # ----------------------------------construct domainconfig user for a domain 
 2169: sub get_domainconfiguser {
 2170:     my ($udom) = @_;
 2171:     return $udom.'-domainconfig';
 2172: }
 2173: 
 2174: sub retrieve_inst_usertypes {
 2175:     my ($udom) = @_;
 2176:     my (%returnhash,@order);
 2177:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2178:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2179:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2180:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2181:     } else {
 2182:         if (defined(&domain($udom,'primary'))) {
 2183:             my $uhome=&domain($udom,'primary');
 2184:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2185:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2186:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2187:                 return (\%returnhash,\@order);
 2188:             }
 2189:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2190:             my @pairs=split(/\&/,$hashitems);
 2191:             foreach my $item (@pairs) {
 2192:                 my ($key,$value)=split(/=/,$item,2);
 2193:                 $key = &unescape($key);
 2194:                 next if ($key =~ /^error: 2 /);
 2195:                 $returnhash{$key}=&thaw_unescape($value);
 2196:             }
 2197:             my @esc_order = split(/\&/,$orderitems);
 2198:             foreach my $item (@esc_order) {
 2199:                 push(@order,&unescape($item));
 2200:             }
 2201:         } else {
 2202:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2203:         }
 2204:         return (\%returnhash,\@order);
 2205:     }
 2206: }
 2207: 
 2208: sub is_domainimage {
 2209:     my ($url) = @_;
 2210:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2211:         if (&domain($1) ne '') {
 2212:             return '1';
 2213:         }
 2214:     }
 2215:     return;
 2216: }
 2217: 
 2218: sub inst_directory_query {
 2219:     my ($srch) = @_;
 2220:     my $udom = $srch->{'srchdomain'};
 2221:     my %results;
 2222:     my $homeserver = &domain($udom,'primary');
 2223:     my $outcome;
 2224:     if ($homeserver ne '') {
 2225:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2226:             if ($srch->{'srchby'} eq 'email') {
 2227:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2228:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2229:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2230:                     (($major == 2) && ($minor < 12))) {
 2231:                     return;
 2232:                 }
 2233:             }
 2234:         }
 2235: 	my $queryid=&reply("querysend:instdirsearch:".
 2236: 			   &escape($srch->{'srchby'}).':'.
 2237: 			   &escape($srch->{'srchterm'}).':'.
 2238: 			   &escape($srch->{'srchtype'}),$homeserver);
 2239: 	my $host=&hostname($homeserver);
 2240: 	if ($queryid !~/^\Q$host\E\_/) {
 2241: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2242: 	    return;
 2243: 	}
 2244: 	my $response = &get_query_reply($queryid);
 2245: 	my $maxtries = 5;
 2246: 	my $tries = 1;
 2247: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2248: 	    $response = &get_query_reply($queryid);
 2249: 	    $tries ++;
 2250: 	}
 2251: 
 2252:         if (!&error($response) && $response ne 'refused') {
 2253:             if ($response eq 'unavailable') {
 2254:                 $outcome = $response;
 2255:             } else {
 2256:                 $outcome = 'ok';
 2257:                 my @matches = split(/\n/,$response);
 2258:                 foreach my $match (@matches) {
 2259:                     my ($key,$value) = split(/=/,$match);
 2260:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2261:                 }
 2262:             }
 2263:         }
 2264:     }
 2265:     return ($outcome,%results);
 2266: }
 2267: 
 2268: sub usersearch {
 2269:     my ($srch) = @_;
 2270:     my $dom = $srch->{'srchdomain'};
 2271:     my %results;
 2272:     my %libserv = &all_library();
 2273:     my $query = 'usersearch';
 2274:     foreach my $tryserver (keys(%libserv)) {
 2275:         if (&host_domain($tryserver) eq $dom) {
 2276:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2277:                 if ($srch->{'srchby'} eq 'email') {
 2278:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2279:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2280:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2281:                              (($major == 2) && ($minor < 12)));
 2282:                 }
 2283:             }
 2284:             my $host=&hostname($tryserver);
 2285:             my $queryid=
 2286:                 &reply("querysend:".&escape($query).':'.
 2287:                        &escape($srch->{'srchby'}).':'.
 2288:                        &escape($srch->{'srchtype'}).':'.
 2289:                        &escape($srch->{'srchterm'}),$tryserver);
 2290:             if ($queryid !~/^\Q$host\E\_/) {
 2291:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2292:                 next;
 2293:             }
 2294:             my $reply = &get_query_reply($queryid);
 2295:             my $maxtries = 1;
 2296:             my $tries = 1;
 2297:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2298:                 $reply = &get_query_reply($queryid);
 2299:                 $tries ++;
 2300:             }
 2301:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2302:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2303:             } else {
 2304:                 my @matches;
 2305:                 if ($reply =~ /\n/) {
 2306:                     @matches = split(/\n/,$reply);
 2307:                 } else {
 2308:                     @matches = split(/\&/,$reply);
 2309:                 }
 2310:                 foreach my $match (@matches) {
 2311:                     my ($uname,$udom,%userhash);
 2312:                     foreach my $entry (split(/:/,$match)) {
 2313:                         my ($key,$value) =
 2314:                             map {&unescape($_);} split(/=/,$entry);
 2315:                         $userhash{$key} = $value;
 2316:                         if ($key eq 'username') {
 2317:                             $uname = $value;
 2318:                         } elsif ($key eq 'domain') {
 2319:                             $udom = $value;
 2320:                         }
 2321:                     }
 2322:                     $results{$uname.':'.$udom} = \%userhash;
 2323:                 }
 2324:             }
 2325:         }
 2326:     }
 2327:     return %results;
 2328: }
 2329: 
 2330: sub get_instuser {
 2331:     my ($udom,$uname,$id) = @_;
 2332:     my $homeserver = &domain($udom,'primary');
 2333:     my ($outcome,%results);
 2334:     if ($homeserver ne '') {
 2335:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2336:                            &escape($id).':'.&escape($udom),$homeserver);
 2337:         my $host=&hostname($homeserver);
 2338:         if ($queryid !~/^\Q$host\E\_/) {
 2339:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2340:             return;
 2341:         }
 2342:         my $response = &get_query_reply($queryid);
 2343:         my $maxtries = 5;
 2344:         my $tries = 1;
 2345:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2346:             $response = &get_query_reply($queryid);
 2347:             $tries ++;
 2348:         }
 2349:         if (!&error($response) && $response ne 'refused') {
 2350:             if ($response eq 'unavailable') {
 2351:                 $outcome = $response;
 2352:             } else {
 2353:                 $outcome = 'ok';
 2354:                 my @matches = split(/\n/,$response);
 2355:                 foreach my $match (@matches) {
 2356:                     my ($key,$value) = split(/=/,$match);
 2357:                     $results{&unescape($key)} = &thaw_unescape($value);
 2358:                 }
 2359:             }
 2360:         }
 2361:     }
 2362:     my %userinfo;
 2363:     if (ref($results{$uname}) eq 'HASH') {
 2364:         %userinfo = %{$results{$uname}};
 2365:     } 
 2366:     return ($outcome,%userinfo);
 2367: }
 2368: 
 2369: sub get_multiple_instusers {
 2370:     my ($udom,$users,$caller) = @_;
 2371:     my ($outcome,$results);
 2372:     if (ref($users) eq 'HASH') {
 2373:         my $count = keys(%{$users}); 
 2374:         my $requested = &freeze_escape($users);
 2375:         my $homeserver = &domain($udom,'primary');
 2376:         if ($homeserver ne '') {
 2377:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2378:             my $host=&hostname($homeserver);
 2379:             if ($queryid !~/^\Q$host\E\_/) {
 2380:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2381:                          ' for host: '.$homeserver.'in domain '.$udom);
 2382:                 return ($outcome,$results);
 2383:             }
 2384:             my $response = &get_query_reply($queryid);
 2385:             my $maxtries = 5;
 2386:             if ($count > 100) {
 2387:                 $maxtries = 1+int($count/20);
 2388:             }
 2389:             my $tries = 1;
 2390:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2391:                 $response = &get_query_reply($queryid);
 2392:                 $tries ++;
 2393:             }
 2394:             if ($response eq '') {
 2395:                 $results = {};
 2396:                 foreach my $key (keys(%{$users})) {
 2397:                     my ($uname,$id);
 2398:                     if ($caller eq 'id') {
 2399:                         $id = $key;
 2400:                     } else {
 2401:                         $uname = $key;
 2402:                     }
 2403:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2404:                     $outcome = $resp;
 2405:                     if ($resp eq 'ok') {
 2406:                         %{$results} = (%{$results}, %info);
 2407:                     } else {
 2408:                         last;
 2409:                     }
 2410:                 }
 2411:             } elsif(!&error($response) && ($response ne 'refused')) {
 2412:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2413:                     $outcome = $response;
 2414:                 } else {
 2415:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2416:                     if ($outcome eq 'ok') {
 2417:                         $results = &thaw_unescape($userdata); 
 2418:                     }
 2419:                 }
 2420:             }
 2421:         }
 2422:     }
 2423:     return ($outcome,$results);
 2424: }
 2425: 
 2426: sub inst_rulecheck {
 2427:     my ($udom,$uname,$id,$item,$rules) = @_;
 2428:     my %returnhash;
 2429:     if ($udom ne '') {
 2430:         if (ref($rules) eq 'ARRAY') {
 2431:             @{$rules} = map {&escape($_);} (@{$rules});
 2432:             my $rulestr = join(':',@{$rules});
 2433:             my $homeserver=&domain($udom,'primary');
 2434:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2435:                 my $response;
 2436:                 if ($item eq 'username') {                
 2437:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2438:                                               ':'.&escape($uname).':'.$rulestr,
 2439:                                               $homeserver));
 2440:                 } elsif ($item eq 'id') {
 2441:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2442:                                               ':'.&escape($id).':'.$rulestr,
 2443:                                               $homeserver));
 2444:                 } elsif ($item eq 'selfcreate') {
 2445:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2446:                                                &escape($udom).':'.&escape($uname).
 2447:                                               ':'.$rulestr,$homeserver));
 2448:                 }
 2449:                 if ($response ne 'refused') {
 2450:                     my @pairs=split(/\&/,$response);
 2451:                     foreach my $item (@pairs) {
 2452:                         my ($key,$value)=split(/=/,$item,2);
 2453:                         $key = &unescape($key);
 2454:                         next if ($key =~ /^error: 2 /);
 2455:                         $returnhash{$key}=&thaw_unescape($value);
 2456:                     }
 2457:                 }
 2458:             }
 2459:         }
 2460:     }
 2461:     return %returnhash;
 2462: }
 2463: 
 2464: sub inst_userrules {
 2465:     my ($udom,$check) = @_;
 2466:     my (%ruleshash,@ruleorder);
 2467:     if ($udom ne '') {
 2468:         my $homeserver=&domain($udom,'primary');
 2469:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2470:             my $response;
 2471:             if ($check eq 'id') {
 2472:                 $response=&reply('instidrules:'.&escape($udom),
 2473:                                  $homeserver);
 2474:             } elsif ($check eq 'email') {
 2475:                 $response=&reply('instemailrules:'.&escape($udom),
 2476:                                  $homeserver);
 2477:             } else {
 2478:                 $response=&reply('instuserrules:'.&escape($udom),
 2479:                                  $homeserver);
 2480:             }
 2481:             if (($response ne 'refused') && ($response ne 'error') && 
 2482:                 ($response ne 'unknown_cmd') && 
 2483:                 ($response ne 'no_such_host')) {
 2484:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2485:                 my @pairs=split(/\&/,$hashitems);
 2486:                 foreach my $item (@pairs) {
 2487:                     my ($key,$value)=split(/=/,$item,2);
 2488:                     $key = &unescape($key);
 2489:                     next if ($key =~ /^error: 2 /);
 2490:                     $ruleshash{$key}=&thaw_unescape($value);
 2491:                 }
 2492:                 my @esc_order = split(/\&/,$orderitems);
 2493:                 foreach my $item (@esc_order) {
 2494:                     push(@ruleorder,&unescape($item));
 2495:                 }
 2496:             }
 2497:         }
 2498:     }
 2499:     return (\%ruleshash,\@ruleorder);
 2500: }
 2501: 
 2502: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2503: 
 2504: sub get_domain_defaults {
 2505:     my ($domain,$ignore_cache) = @_;
 2506:     return if (($domain eq '') || ($domain eq 'public'));
 2507:     my $cachetime = 60*60*24;
 2508:     unless ($ignore_cache) {
 2509:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2510:         if (defined($cached)) {
 2511:             if (ref($result) eq 'HASH') {
 2512:                 return %{$result};
 2513:             }
 2514:         }
 2515:     }
 2516:     my %domdefaults;
 2517:     my %domconfig =
 2518:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2519:                                   'requestcourses','inststatus',
 2520:                                   'coursedefaults','usersessions',
 2521:                                   'requestauthor','selfenrollment',
 2522:                                   'coursecategories','ssl','autoenroll',
 2523:                                   'trust','helpsettings'],$domain);
 2524:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2525:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2526:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2527:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2528:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2529:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2530:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2531:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2532:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2533:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2534:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2535:     } else {
 2536:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2537:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2538:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2539:     }
 2540:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2541:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2542:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2543:         } else {
 2544:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2545:         }
 2546:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2547:         foreach my $item (@usertools) {
 2548:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2549:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2550:             }
 2551:         }
 2552:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2553:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2554:         }
 2555:     }
 2556:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2557:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2558:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2559:         }
 2560:     }
 2561:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2562:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2563:     }
 2564:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2565:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2566:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2567:         }
 2568:     }
 2569:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2570:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2571:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2572:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2573:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2574:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2575:         }
 2576:         foreach my $type (@coursetypes) {
 2577:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2578:                 unless ($type eq 'community') {
 2579:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2580:                 }
 2581:             }
 2582:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2583:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2584:             }
 2585:             if ($domdefaults{'postsubmit'} eq 'on') {
 2586:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2587:                     $domdefaults{$type.'postsubtimeout'} = 
 2588:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2589:                 }
 2590:             }
 2591:         }
 2592:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2593:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2594:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2595:                 if (@clonecodes) {
 2596:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2597:                 }
 2598:             }
 2599:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2600:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2601:         }
 2602:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2603:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2604:         } 
 2605:     }
 2606:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2607:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2608:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2609:         }
 2610:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2611:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2612:         }
 2613:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2614:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2615:         }
 2616:     }
 2617:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2618:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2619:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2620:                             'approval','limit');
 2621:             foreach my $type (@coursetypes) {
 2622:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2623:                     my @mgrdc = ();
 2624:                     foreach my $item (@settings) {
 2625:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2626:                             push(@mgrdc,$item);
 2627:                         }
 2628:                     }
 2629:                     if (@mgrdc) {
 2630:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2631:                     }
 2632:                 }
 2633:             }
 2634:         }
 2635:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2636:             foreach my $type (@coursetypes) {
 2637:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2638:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2639:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2640:                     }
 2641:                 }
 2642:             }
 2643:         }
 2644:     }
 2645:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2646:         $domdefaults{'catauth'} = 'std';
 2647:         $domdefaults{'catunauth'} = 'std';
 2648:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2649:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2650:         }
 2651:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2652:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2653:         }
 2654:     }
 2655:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2656:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2657:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2658:         }
 2659:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2660:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2661:         }
 2662:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2663:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2664:         }
 2665:     }
 2666:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2667:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2668:         foreach my $prefix (@prefixes) {
 2669:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2670:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2671:             }
 2672:         }
 2673:     }
 2674:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2675:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2676:     }
 2677:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2678:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2679:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2680:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2681:         }
 2682:     }
 2683:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2684:     return %domdefaults;
 2685: }
 2686: 
 2687: sub course_portal_url {
 2688:     my ($cnum,$cdom) = @_;
 2689:     my $chome = &homeserver($cnum,$cdom);
 2690:     my $hostname = &hostname($chome);
 2691:     my $protocol = $protocol{$chome};
 2692:     $protocol = 'http' if ($protocol ne 'https');
 2693:     my %domdefaults = &get_domain_defaults($cdom);
 2694:     my $firsturl;
 2695:     if ($domdefaults{'portal_def'}) {
 2696:         $firsturl = $domdefaults{'portal_def'};
 2697:     } else {
 2698:         $firsturl = $protocol.'://'.$hostname;
 2699:     }
 2700:     return $firsturl;
 2701: }
 2702: 
 2703: # --------------------------------------------------- Assign a key to a student
 2704: 
 2705: sub assign_access_key {
 2706: #
 2707: # a valid key looks like uname:udom#comments
 2708: # comments are being appended
 2709: #
 2710:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2711:     $kdom=
 2712:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2713:     $knum=
 2714:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2715:     $cdom=
 2716:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2717:     $cnum=
 2718:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2719:     $udom=$env{'user.name'} unless (defined($udom));
 2720:     $uname=$env{'user.domain'} unless (defined($uname));
 2721:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2722:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2723:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2724:                                                   # assigned to this person
 2725:                                                   # - this should not happen,
 2726:                                                   # unless something went wrong
 2727:                                                   # the first time around
 2728: # ready to assign
 2729:         $logentry=$1.'; '.$logentry;
 2730:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2731:                                                  $kdom,$knum) eq 'ok') {
 2732: # key now belongs to user
 2733: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2734:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2735:                 &appenv({'environment.'.$envkey => $ckey});
 2736:                 return 'ok';
 2737:             } else {
 2738:                 return 
 2739:   'error: Count not permanently assign key, will need to be re-entered later.';
 2740: 	    }
 2741:         } else {
 2742:             return 'error: Could not assign key, try again later.';
 2743:         }
 2744:     } elsif (!$existing{$ckey}) {
 2745: # the key does not exist
 2746: 	return 'error: The key does not exist';
 2747:     } else {
 2748: # the key is somebody else's
 2749: 	return 'error: The key is already in use';
 2750:     }
 2751: }
 2752: 
 2753: # ------------------------------------------ put an additional comment on a key
 2754: 
 2755: sub comment_access_key {
 2756: #
 2757: # a valid key looks like uname:udom#comments
 2758: # comments are being appended
 2759: #
 2760:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2761:     $cdom=
 2762:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2763:     $cnum=
 2764:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2765:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2766:     if ($existing{$ckey}) {
 2767:         $existing{$ckey}.='; '.$logentry;
 2768: # ready to assign
 2769:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2770:                                                  $cdom,$cnum) eq 'ok') {
 2771: 	    return 'ok';
 2772:         } else {
 2773: 	    return 'error: Count not store comment.';
 2774:         }
 2775:     } else {
 2776: # the key does not exist
 2777: 	return 'error: The key does not exist';
 2778:     }
 2779: }
 2780: 
 2781: # ------------------------------------------------------ Generate a set of keys
 2782: 
 2783: sub generate_access_keys {
 2784:     my ($number,$cdom,$cnum,$logentry)=@_;
 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:     unless (&allowed('mky',$cdom)) { return 0; }
 2790:     unless (($cdom) && ($cnum)) { return 0; }
 2791:     if ($number>10000) { return 0; }
 2792:     sleep(2); # make sure don't get same seed twice
 2793:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2794:     my $total=0;
 2795:     for (my $i=1;$i<=$number;$i++) {
 2796:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2797:                   sprintf("%lx",int(100000*rand)).'-'.
 2798:                   sprintf("%lx",int(100000*rand));
 2799:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2800:        $newkey=~s/0/h/g; # and also 0 and O
 2801:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2802:        if ($existing{$newkey}) {
 2803:            $i--;
 2804:        } else {
 2805: 	  if (&put('accesskeys',
 2806:               { $newkey => '# generated '.localtime().
 2807:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2808:                            '; '.$logentry },
 2809: 		   $cdom,$cnum) eq 'ok') {
 2810:               $total++;
 2811: 	  }
 2812:        }
 2813:     }
 2814:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2815:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2816:     return $total;
 2817: }
 2818: 
 2819: # ------------------------------------------------------- Validate an accesskey
 2820: 
 2821: sub validate_access_key {
 2822:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2823:     $cdom=
 2824:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2825:     $cnum=
 2826:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2827:     $udom=$env{'user.domain'} unless (defined($udom));
 2828:     $uname=$env{'user.name'} unless (defined($uname));
 2829:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2830:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2831: }
 2832: 
 2833: # ------------------------------------- Find the section of student in a course
 2834: sub devalidate_getsection_cache {
 2835:     my ($udom,$unam,$courseid)=@_;
 2836:     my $hashid="$udom:$unam:$courseid";
 2837:     &devalidate_cache_new('getsection',$hashid);
 2838: }
 2839: 
 2840: sub courseid_to_courseurl {
 2841:     my ($courseid) = @_;
 2842:     #already url style courseid
 2843:     return $courseid if ($courseid =~ m{^/});
 2844: 
 2845:     if (exists($env{'course.'.$courseid.'.num'})) {
 2846: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2847: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2848: 	return "/$cdom/$cnum";
 2849:     }
 2850: 
 2851:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2852:     if (exists($courseinfo{'num'})) {
 2853: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2854:     }
 2855: 
 2856:     return undef;
 2857: }
 2858: 
 2859: sub getsection {
 2860:     my ($udom,$unam,$courseid)=@_;
 2861:     my $cachetime=1800;
 2862: 
 2863:     my $hashid="$udom:$unam:$courseid";
 2864:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2865:     if (defined($cached)) { return $result; }
 2866: 
 2867:     my %Pending; 
 2868:     my %Expired;
 2869:     #
 2870:     # Each role can either have not started yet (pending), be active, 
 2871:     #    or have expired.
 2872:     #
 2873:     # If there is an active role, we are done.
 2874:     #
 2875:     # If there is more than one role which has not started yet, 
 2876:     #     choose the one which will start sooner
 2877:     # If there is one role which has not started yet, return it.
 2878:     #
 2879:     # If there is more than one expired role, choose the one which ended last.
 2880:     # If there is a role which has expired, return it.
 2881:     #
 2882:     $courseid = &courseid_to_courseurl($courseid);
 2883:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2884:     foreach my $key (keys(%roleshash)) {
 2885:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2886:         my $section=$1;
 2887:         if ($key eq $courseid.'_st') { $section=''; }
 2888:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2889:         my $now=time;
 2890:         if (defined($end) && $end && ($now > $end)) {
 2891:             $Expired{$end}=$section;
 2892:             next;
 2893:         }
 2894:         if (defined($start) && $start && ($now < $start)) {
 2895:             $Pending{$start}=$section;
 2896:             next;
 2897:         }
 2898:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2899:     }
 2900:     #
 2901:     # Presumedly there will be few matching roles from the above
 2902:     # loop and the sorting time will be negligible.
 2903:     if (scalar(keys(%Pending))) {
 2904:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2905:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2906:     } 
 2907:     if (scalar(keys(%Expired))) {
 2908:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2909:         my $time = pop(@sorted);
 2910:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2911:     }
 2912:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2913: }
 2914: 
 2915: sub save_cache {
 2916:     &purge_remembered();
 2917:     #&Apache::loncommon::validate_page();
 2918:     undef(%env);
 2919:     undef($env_loaded);
 2920: }
 2921: 
 2922: my $to_remember=-1;
 2923: my %remembered;
 2924: my %accessed;
 2925: my $kicks=0;
 2926: my $hits=0;
 2927: sub make_key {
 2928:     my ($name,$id) = @_;
 2929:     if (length($id) > 65 
 2930: 	&& length(&escape($id)) > 200) {
 2931: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2932:     }
 2933:     return &escape($name.':'.$id);
 2934: }
 2935: 
 2936: sub devalidate_cache_new {
 2937:     my ($name,$id,$debug) = @_;
 2938:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2939:     my $remembered_id=$name.':'.$id;
 2940:     $id=&make_key($name,$id);
 2941:     $memcache->delete($id);
 2942:     delete($remembered{$remembered_id});
 2943:     delete($accessed{$remembered_id});
 2944: }
 2945: 
 2946: sub is_cached_new {
 2947:     my ($name,$id,$debug) = @_;
 2948:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2949:     if (exists($remembered{$remembered_id})) {
 2950: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2951: 	$accessed{$remembered_id}=[&gettimeofday()];
 2952: 	$hits++;
 2953: 	return ($remembered{$remembered_id},1);
 2954:     }
 2955:     $id=&make_key($name,$id);
 2956:     my $value = $memcache->get($id);
 2957:     if (!(defined($value))) {
 2958: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2959: 	return (undef,undef);
 2960:     }
 2961:     if ($value eq '__undef__') {
 2962: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2963: 	$value=undef;
 2964:     }
 2965:     &make_room($remembered_id,$value,$debug);
 2966:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2967:     return ($value,1);
 2968: }
 2969: 
 2970: sub do_cache_new {
 2971:     my ($name,$id,$value,$time,$debug) = @_;
 2972:     my $remembered_id=$name.':'.$id;
 2973:     $id=&make_key($name,$id);
 2974:     my $setvalue=$value;
 2975:     if (!defined($setvalue)) {
 2976: 	$setvalue='__undef__';
 2977:     }
 2978:     if (!defined($time) ) {
 2979: 	$time=600;
 2980:     }
 2981:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2982:     my $result = $memcache->set($id,$setvalue,$time);
 2983:     if (! $result) {
 2984: 	&logthis("caching of id -> $id  failed");
 2985: 	$memcache->disconnect_all();
 2986:     }
 2987:     # need to make a copy of $value
 2988:     &make_room($remembered_id,$value,$debug);
 2989:     return $value;
 2990: }
 2991: 
 2992: sub make_room {
 2993:     my ($remembered_id,$value,$debug)=@_;
 2994: 
 2995:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2996:                                     : $value;
 2997:     if ($to_remember<0) { return; }
 2998:     $accessed{$remembered_id}=[&gettimeofday()];
 2999:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3000:     my $to_kick;
 3001:     my $max_time=0;
 3002:     foreach my $other (keys(%accessed)) {
 3003: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3004: 	    $to_kick=$other;
 3005: 	    $max_time=&tv_interval($accessed{$other});
 3006: 	}
 3007:     }
 3008:     delete($remembered{$to_kick});
 3009:     delete($accessed{$to_kick});
 3010:     $kicks++;
 3011:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3012:     return;
 3013: }
 3014: 
 3015: sub purge_remembered {
 3016:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3017:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3018:     undef(%remembered);
 3019:     undef(%accessed);
 3020: }
 3021: # ------------------------------------- Read an entry from a user's environment
 3022: 
 3023: sub userenvironment {
 3024:     my ($udom,$unam,@what)=@_;
 3025:     my $items;
 3026:     foreach my $item (@what) {
 3027:         $items.=&escape($item).'&';
 3028:     }
 3029:     $items=~s/\&$//;
 3030:     my %returnhash=();
 3031:     my $uhome = &homeserver($unam,$udom);
 3032:     unless ($uhome eq 'no_host') {
 3033:         my @answer=split(/\&/, 
 3034:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3035:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3036:             return %returnhash;
 3037:         }
 3038:         my $i;
 3039:         for ($i=0;$i<=$#what;$i++) {
 3040: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3041:         }
 3042:     }
 3043:     return %returnhash;
 3044: }
 3045: 
 3046: # ---------------------------------------------------------- Get a studentphoto
 3047: sub studentphoto {
 3048:     my ($udom,$unam,$ext) = @_;
 3049:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3050:     if (defined($env{'request.course.id'})) {
 3051:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3052:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3053:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3054:             } else {
 3055:                 my ($result,$perm_reqd)=
 3056: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3057:                 if ($result eq 'ok') {
 3058:                     if (!($perm_reqd eq 'yes')) {
 3059:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3060:                     }
 3061:                 }
 3062:             }
 3063:         }
 3064:     } else {
 3065:         my ($result,$perm_reqd) = 
 3066: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3067:         if ($result eq 'ok') {
 3068:             if (!($perm_reqd eq 'yes')) {
 3069:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3070:             }
 3071:         }
 3072:     }
 3073:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3074: }
 3075: 
 3076: sub retrievestudentphoto {
 3077:     my ($udom,$unam,$ext,$type) = @_;
 3078:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3079:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3080:     if ($ret eq 'ok') {
 3081:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3082:         if ($type eq 'thumbnail') {
 3083:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3084:         }
 3085:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3086:         return $tokenurl;
 3087:     } else {
 3088:         if ($type eq 'thumbnail') {
 3089:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3090:         } else { 
 3091:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3092:         }
 3093:     }
 3094: }
 3095: 
 3096: # -------------------------------------------------------------------- New chat
 3097: 
 3098: sub chatsend {
 3099:     my ($newentry,$anon,$group)=@_;
 3100:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3101:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3102:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3103:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3104: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3105: 		   &escape($newentry)).':'.$group,$chome);
 3106: }
 3107: 
 3108: # ------------------------------------------ Find current version of a resource
 3109: 
 3110: sub getversion {
 3111:     my $fname=&clutter(shift);
 3112:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3113:     return &currentversion(&filelocation('',$fname));
 3114: }
 3115: 
 3116: sub currentversion {
 3117:     my $fname=shift;
 3118:     my $author=$fname;
 3119:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3120:     my ($udom,$uname)=split(/\//,$author);
 3121:     my $home=&homeserver($uname,$udom);
 3122:     if ($home eq 'no_host') { 
 3123:         return -1; 
 3124:     }
 3125:     my $answer=&reply("currentversion:$fname",$home);
 3126:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3127: 	return -1;
 3128:     }
 3129:     return $answer;
 3130: }
 3131: 
 3132: #
 3133: # Return special version number of resource if set by override, empty otherwise
 3134: #
 3135: sub usedversion {
 3136:     my $fname=shift;
 3137:     unless ($fname) { $fname=$env{'request.uri'}; }
 3138:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3139:     if ($urlversion) { return $urlversion; }
 3140:     return '';
 3141: }
 3142: 
 3143: # ----------------------------- Subscribe to a resource, return URL if possible
 3144: 
 3145: sub subscribe {
 3146:     my $fname=shift;
 3147:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3148:     $fname=~s/[\n\r]//g;
 3149:     my $author=$fname;
 3150:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3151:     my ($udom,$uname)=split(/\//,$author);
 3152:     my $home=homeserver($uname,$udom);
 3153:     if ($home eq 'no_host') {
 3154:         return 'not_found';
 3155:     }
 3156:     my $answer=reply("sub:$fname",$home);
 3157:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3158: 	$answer.=' by '.$home;
 3159:     }
 3160:     return $answer;
 3161: }
 3162:     
 3163: # -------------------------------------------------------------- Replicate file
 3164: 
 3165: sub repcopy {
 3166:     my $filename=shift;
 3167:     $filename=~s/\/+/\//g;
 3168:     my $londocroot = $perlvar{'lonDocRoot'};
 3169:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3170:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3171:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3172: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3173: 	return &repcopy_userfile($filename);
 3174:     }
 3175:     $filename=~s/[\n\r]//g;
 3176:     my $transname="$filename.in.transfer";
 3177: # FIXME: this should flock
 3178:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3179:     my $remoteurl=subscribe($filename);
 3180:     if ($remoteurl =~ /^con_lost by/) {
 3181: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3182:            return 'unavailable';
 3183:     } elsif ($remoteurl eq 'not_found') {
 3184: 	   #&logthis("Subscribe returned not_found: $filename");
 3185: 	   return 'not_found';
 3186:     } elsif ($remoteurl =~ /^rejected by/) {
 3187: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3188:            return 'forbidden';
 3189:     } elsif ($remoteurl eq 'directory') {
 3190:            return 'ok';
 3191:     } else {
 3192:         my $author=$filename;
 3193:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3194:         my ($udom,$uname)=split(/\//,$author);
 3195:         my $home=homeserver($uname,$udom);
 3196:         unless ($home eq $perlvar{'lonHostID'}) {
 3197:            my @parts=split(/\//,$filename);
 3198:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3199:            if ($path ne "$londocroot/res") {
 3200:                &logthis("Malconfiguration for replication: $filename");
 3201: 	       return 'bad_request';
 3202:            }
 3203:            my $count;
 3204:            for ($count=5;$count<$#parts;$count++) {
 3205:                $path.="/$parts[$count]";
 3206:                if ((-e $path)!=1) {
 3207: 		   mkdir($path,0777);
 3208:                }
 3209:            }
 3210:            my $request=new HTTP::Request('GET',"$remoteurl");
 3211:            my $response;
 3212:            if ($remoteurl =~ m{/raw/}) {
 3213:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3214:            } else {
 3215:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3216:            }
 3217:            if ($response->is_error()) {
 3218: 	       unlink($transname);
 3219:                my $message=$response->status_line;
 3220:                &logthis("<font color=\"blue\">WARNING:"
 3221:                        ." LWP get: $message: $filename</font>");
 3222:                return 'unavailable';
 3223:            } else {
 3224: 	       if ($remoteurl!~/\.meta$/) {
 3225:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3226:                   my $mresponse;
 3227:                   if ($remoteurl =~ m{/raw/}) {
 3228:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3229:                   } else {
 3230:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3231:                   }
 3232:                   if ($mresponse->is_error()) {
 3233: 		      unlink($filename.'.meta');
 3234:                       &logthis(
 3235:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3236:                   }
 3237: 	       }
 3238:                rename($transname,$filename);
 3239:                return 'ok';
 3240:            }
 3241:        }
 3242:     }
 3243: }
 3244: 
 3245: # ------------------------------------------------ Get server side include body
 3246: sub ssi_body {
 3247:     my ($filelink,%form)=@_;
 3248:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3249:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3250:     }
 3251:     my $output='';
 3252:     my $response;
 3253:     if ($filelink=~/^https?\:/) {
 3254:        ($output,$response)=&externalssi($filelink);
 3255:     } else {
 3256:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3257:        $filelink .= 'inhibitmenu=yes';
 3258:        ($output,$response)=&ssi($filelink,%form);
 3259:     }
 3260:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3261:     $output=~s/^.*?\<body[^\>]*\>//si;
 3262:     $output=~s/\<\/body\s*\>.*?$//si;
 3263:     if (wantarray) {
 3264:         return ($output, $response);
 3265:     } else {
 3266:         return $output;
 3267:     }
 3268: }
 3269: 
 3270: # --------------------------------------------------------- Server Side Include
 3271: 
 3272: sub absolute_url {
 3273:     my ($host_name) = @_;
 3274:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3275:     if ($host_name eq '') {
 3276: 	$host_name = $ENV{'SERVER_NAME'};
 3277:     }
 3278:     return $protocol.$host_name;
 3279: }
 3280: 
 3281: #
 3282: #   Server side include.
 3283: # Parameters:
 3284: #  fn     Possibly encrypted resource name/id.
 3285: #  form   Hash that describes how the rendering should be done
 3286: #         and other things.
 3287: # Returns:
 3288: #   Scalar context: The content of the response.
 3289: #   Array context:  2 element list of the content and the full response object.
 3290: #     
 3291: sub ssi {
 3292: 
 3293:     my ($fn,%form)=@_;
 3294:     my $request;
 3295: 
 3296:     $form{'no_update_last_known'}=1;
 3297:     &Apache::lonenc::check_encrypt(\$fn);
 3298:     if (%form) {
 3299:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3300:       $request->content(join('&',map { 
 3301:             my $name = escape($_);
 3302:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3303:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3304:             : &escape($form{$_}) );    
 3305:         } keys(%form)));
 3306:     } else {
 3307:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3308:     }
 3309: 
 3310:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3311:     my $lonhost = $perlvar{'lonHostID'};
 3312:     my $islocal;
 3313:     if (($env{'request.course.id'}) &&
 3314:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3315:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3316:         ($form{'grade_symb'} ne '') &&
 3317:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3318:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3319:         $islocal = 1;
 3320:     }
 3321:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3322:                                                 '','','',$islocal);
 3323: 
 3324:     if (wantarray) {
 3325: 	return ($response->content, $response);
 3326:     } else {
 3327: 	return $response->content;
 3328:     }
 3329: }
 3330: 
 3331: sub externalssi {
 3332:     my ($url)=@_;
 3333:     my $request=new HTTP::Request('GET',$url);
 3334:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3335:     if (wantarray) {
 3336:         return ($response->content, $response);
 3337:     } else {
 3338:         return $response->content;
 3339:     }
 3340: }
 3341: 
 3342: 
 3343: # If the local copy of a replicated resource is outdated, trigger a  
 3344: # connection from the homeserver to flush the delayed queue. If no update 
 3345: # happens, remove local copies of outdated resource (and corresponding
 3346: # metadata file).
 3347: 
 3348: sub remove_stale_resfile {
 3349:     my ($url) = @_;
 3350:     my $removed;
 3351:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3352:         my $audom = $1;
 3353:         my $auname = $2;
 3354:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3355:             my $homeserver = &homeserver($auname,$audom);
 3356:             unless (($homeserver eq 'no_host') ||
 3357:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3358:                 my $fname = &filelocation('',$url);
 3359:                 if (-e $fname) {
 3360:                     my $protocol = $protocol{$homeserver};
 3361:                     $protocol = 'http' if ($protocol ne 'https');
 3362:                     my $hostname = &hostname($homeserver);
 3363:                     if ($hostname) {
 3364:                         my $uri = &declutter($url);
 3365:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3366:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3367:                         if ($response->is_success()) {
 3368:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3369:                             my $locmodtime = (stat($fname))[9];
 3370:                             if ($locmodtime < $remmodtime) {
 3371:                                 my $stale;
 3372:                                 my $answer = &reply('pong',$homeserver);
 3373:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3374:                                     sleep(0.2);
 3375:                                     $locmodtime = (stat($fname))[9];
 3376:                                     if ($locmodtime < $remmodtime) {
 3377:                                         my $posstransfer = $fname.'.in.transfer';
 3378:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3379:                                             $removed = 1;
 3380:                                         } else {
 3381:                                             $stale = 1;
 3382:                                         }
 3383:                                     } else {
 3384:                                         $removed = 1;
 3385:                                     }
 3386:                                 } else {
 3387:                                     $stale = 1;
 3388:                                 }
 3389:                                 if ($stale) {
 3390:                                     unlink($fname);
 3391:                                     if ($uri!~/\.meta$/) {
 3392:                                         unlink($fname.'.meta');
 3393:                                     }
 3394:                                     &reply("unsub:$fname",$homeserver);
 3395:                                     $removed = 1;
 3396:                                 }
 3397:                             }
 3398:                         }
 3399:                     }
 3400:                 }
 3401:             }
 3402:         }
 3403:     }
 3404:     return $removed;
 3405: }
 3406: 
 3407: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3408: 
 3409: sub allowuploaded {
 3410:     my ($srcurl,$url)=@_;
 3411:     $url=&clutter(&declutter($url));
 3412:     my $dir=$url;
 3413:     $dir=~s/\/[^\/]+$//;
 3414:     my %httpref=();
 3415:     my $httpurl=&hreflocation('',$url);
 3416:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3417:     &Apache::lonnet::appenv(\%httpref);
 3418: }
 3419: 
 3420: #
 3421: # Determine if the current user should be able to edit a particular resource,
 3422: # when viewing in course context.
 3423: # (a) When viewing resource used to determine if "Edit" item is included in 
 3424: #     Functions.
 3425: # (b) When displaying folder contents in course editor, used to determine if
 3426: #     "Edit" link will be displayed alongside resource.
 3427: #
 3428: #  input: six args -- filename (decluttered), course number, course domain,
 3429: #                   url, symb (if registered) and group (if this is a group
 3430: #                   item -- e.g., bulletin board, group page etc.).
 3431: #  output: array of five scalars -- 
 3432: #          $cfile -- url for file editing if editable on current server
 3433: #          $home -- homeserver of resource (i.e., for author if published,
 3434: #                                           or course if uploaded.).
 3435: #          $switchserver --  1 if server switch will be needed.
 3436: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3437: #          $forceview -- 1 if icon/link should be to go to view mode
 3438: #
 3439: 
 3440: sub can_edit_resource {
 3441:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3442:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3443: #
 3444: # For aboutme pages user can only edit his/her own.
 3445: #
 3446:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3447:         my ($sdom,$sname) = ($1,$2);
 3448:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3449:             $home = $env{'user.home'};
 3450:             $cfile = $resurl;
 3451:             if ($env{'form.forceedit'}) {
 3452:                 $forceview = 1;
 3453:             } else {
 3454:                 $forceedit = 1;
 3455:             }
 3456:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3457:         } else {
 3458:             return;
 3459:         }
 3460:     }
 3461: 
 3462:     if ($env{'request.course.id'}) {
 3463:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3464:         if ($group ne '') {
 3465: # if this is a group homepage or group bulletin board, check group privs
 3466:             my $allowed = 0;
 3467:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3468:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3469:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3470:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3471:                     $allowed = 1;
 3472:                 }
 3473:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3474:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3475:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3476:                     $allowed = 1;
 3477:                 }
 3478:             }
 3479:             if ($allowed) {
 3480:                 $home=&homeserver($cnum,$cdom);
 3481:                 if ($env{'form.forceedit'}) {
 3482:                     $forceview = 1;
 3483:                 } else {
 3484:                     $forceedit = 1;
 3485:                 }
 3486:                 $cfile = $resurl;
 3487:             } else {
 3488:                 return;
 3489:             }
 3490:         } else {
 3491:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3492:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3493:                     return;
 3494:                 }
 3495:             } elsif (!$crsedit) {
 3496: #
 3497: # No edit allowed where CC has switched to student role.
 3498: #
 3499:                 return;
 3500:             }
 3501:         }
 3502:     }
 3503: 
 3504:     if ($file ne '') {
 3505:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3506:             if (&is_course_upload($file,$cnum,$cdom)) {
 3507:                 $uploaded = 1;
 3508:                 $incourse = 1;
 3509:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3510:                     $cfile = &hreflocation('',$file);
 3511:                     if ($env{'form.forceedit'}) {
 3512:                         $forceview = 1;
 3513:                     } else {
 3514:                         $forceedit = 1;
 3515:                     }
 3516:                 }
 3517:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3518:                 $incourse = 1;
 3519:                 if ($env{'form.forceedit'}) {
 3520:                     $forceview = 1;
 3521:                 } else {
 3522:                     $forceedit = 1;
 3523:                 }
 3524:                 $cfile = $resurl;
 3525:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3526:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3527:                     $incourse = 1;
 3528:                     if ($env{'form.forceedit'}) {
 3529:                         $forceview = 1;
 3530:                     } else {
 3531:                         $forceedit = 1;
 3532:                     }
 3533:                     $cfile = $resurl;
 3534:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3535:                     $incourse = 1;
 3536:                     $cfile = $resurl.'/smpedit';
 3537:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3538:                     $incourse = 1;
 3539:                     if ($env{'form.forceedit'}) {
 3540:                         $forceview = 1;
 3541:                     } else {
 3542:                         $forceedit = 1;
 3543:                     }
 3544:                     $cfile = $resurl;
 3545:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3546:                     $incourse = 1;
 3547:                     if ($env{'form.forceedit'}) {
 3548:                         $forceview = 1;
 3549:                     } else {
 3550:                         $forceedit = 1;
 3551:                     }
 3552:                     $cfile = $resurl;
 3553:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3554:                     $incourse = 1;
 3555:                     if ($env{'form.forceedit'}) {
 3556:                         $forceview = 1;
 3557:                     } else {
 3558:                         $forceedit = 1;
 3559:                     }
 3560:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3561:                 }
 3562:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3563:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3564:                 if (&is_on_map($template)) { 
 3565:                     $incourse = 1;
 3566:                     $forceview = 1;
 3567:                     $cfile = $template;
 3568:                 }
 3569:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3570:                     $incourse = 1;
 3571:                     if ($env{'form.forceedit'}) {
 3572:                         $forceview = 1;
 3573:                     } else {
 3574:                         $forceedit = 1;
 3575:                     }
 3576:                     $cfile = $resurl;
 3577:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3578:                 $incourse = 1;
 3579:                 if ($env{'form.forceedit'}) {
 3580:                     $forceview = 1;
 3581:                 } else {
 3582:                     $forceedit = 1;
 3583:                 }
 3584:                 $cfile = $resurl;
 3585:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3586:                 $incourse = 1;
 3587:                 $forceview = 1;
 3588:                 if ($symb) {
 3589:                     my ($map,$id,$res)=&decode_symb($symb);
 3590:                     $env{'request.symb'} = $symb;
 3591:                     $cfile = &clutter($res);
 3592:                 } else {
 3593:                     $cfile = $env{'form.suppurl'};
 3594:                     my $escfile = &unescape($cfile);
 3595:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3596:                         $cfile = '/adm/wrapper'.$escfile;
 3597:                     } else {
 3598:                         $escfile =~ s{^http://}{};
 3599:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3600:                     }
 3601:                 }
 3602:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3603:                 if ($env{'form.forceedit'}) {
 3604:                     $forceview = 1;
 3605:                 } else {
 3606:                     $forceedit = 1;
 3607:                 }
 3608:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3609:             }
 3610:         }
 3611:         if ($uploaded || $incourse) {
 3612:             $home=&homeserver($cnum,$cdom);
 3613:         } elsif ($file !~ m{/$}) {
 3614:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3615:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3616:             # Check that the user has permission to edit this resource
 3617:             my $setpriv = 1;
 3618:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3619:             if (defined($cfudom)) {
 3620:                 $home=&homeserver($cfuname,$cfudom);
 3621:                 $cfile=$file;
 3622:             }
 3623:         }
 3624:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3625:             (($home ne '') && ($home ne 'no_host'))) {
 3626:             my @ids=&current_machine_ids();
 3627:             unless (grep(/^\Q$home\E$/,@ids)) {
 3628:                 $switchserver=1;
 3629:             }
 3630:         }
 3631:     }
 3632:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3633: }
 3634: 
 3635: sub is_course_upload {
 3636:     my ($file,$cnum,$cdom) = @_;
 3637:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3638:     $uploadpath =~ s{^\/}{};
 3639:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3640:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3641:         return 1;
 3642:     }
 3643:     return;
 3644: }
 3645: 
 3646: sub in_course {
 3647:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3648:     if ($hideprivileged) {
 3649:         my $skipuser;
 3650:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3651:         my @possdoms = ($cdom);  
 3652:         if ($coursehash{'checkforpriv'}) { 
 3653:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3654:         }
 3655:         if (&privileged($uname,$udom,\@possdoms)) {
 3656:             $skipuser = 1;
 3657:             if ($coursehash{'nothideprivileged'}) {
 3658:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3659:                     my $user;
 3660:                     if ($item =~ /:/) {
 3661:                         $user = $item;
 3662:                     } else {
 3663:                         $user = join(':',split(/[\@]/,$item));
 3664:                     }
 3665:                     if ($user eq $uname.':'.$udom) {
 3666:                         undef($skipuser);
 3667:                         last;
 3668:                     }
 3669:                 }
 3670:             }
 3671:             if ($skipuser) {
 3672:                 return 0;
 3673:             }
 3674:         }
 3675:     }
 3676:     $type ||= 'any';
 3677:     if (!defined($cdom) || !defined($cnum)) {
 3678:         my $cid  = $env{'request.course.id'};
 3679:         $cdom = $env{'course.'.$cid.'.domain'};
 3680:         $cnum = $env{'course.'.$cid.'.num'};
 3681:     }
 3682:     my $typesref;
 3683:     if (($type eq 'any') || ($type eq 'all')) {
 3684:         $typesref = ['active','previous','future'];
 3685:     } elsif ($type eq 'previous' || $type eq 'future') {
 3686:         $typesref = [$type];
 3687:     }
 3688:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3689:                               $typesref,undef,[$cdom]);
 3690:     my ($tmp) = keys(%roles);
 3691:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3692:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3693:     if (@course_roles > 0) {
 3694:         return 1;
 3695:     }
 3696:     return 0;
 3697: }
 3698: 
 3699: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3700: # input: action, courseID, current domain, intended
 3701: #        path to file, source of file, instruction to parse file for objects,
 3702: #        ref to hash for embedded objects,
 3703: #        ref to hash for codebase of java objects.
 3704: #        reference to scalar to accommodate mime type determined
 3705: #          from File::MMagic if $parser = parse.
 3706: #
 3707: # output: url to file (if action was uploaddoc), 
 3708: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3709: #
 3710: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3711: # course.
 3712: #
 3713: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3714: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3715: #          course's home server.
 3716: #
 3717: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3718: #          be copied from $source (current location) to 
 3719: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3720: #         and will then be copied to
 3721: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3722: #         course's home server.
 3723: #
 3724: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3725: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3726: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3727: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3728: #         in course's home server.
 3729: #
 3730: 
 3731: sub process_coursefile {
 3732:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3733:         $mimetype)=@_;
 3734:     my $fetchresult;
 3735:     my $home=&homeserver($docuname,$docudom);
 3736:     if ($action eq 'propagate') {
 3737:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3738: 			     $home);
 3739:     } else {
 3740:         my $fpath = '';
 3741:         my $fname = $file;
 3742:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3743:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3744:         my $filepath = &build_filepath($fpath);
 3745:         if ($action eq 'copy') {
 3746:             if ($source eq '') {
 3747:                 $fetchresult = 'no source file';
 3748:                 return $fetchresult;
 3749:             } else {
 3750:                 my $destination = $filepath.'/'.$fname;
 3751:                 rename($source,$destination);
 3752:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3753:                                  $home);
 3754:             }
 3755:         } elsif ($action eq 'uploaddoc') {
 3756:             open(my $fh,'>',$filepath.'/'.$fname);
 3757:             print $fh $env{'form.'.$source};
 3758:             close($fh);
 3759:             if ($parser eq 'parse') {
 3760:                 my $mm = new File::MMagic;
 3761:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3762:                 if ($type eq 'text/html') {
 3763:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3764:                     unless ($parse_result eq 'ok') {
 3765:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3766:                     }
 3767:                 }
 3768:                 if (ref($mimetype)) {
 3769:                     $$mimetype = $type;
 3770:                 } 
 3771:             }
 3772:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3773:                                  $home);
 3774:             if ($fetchresult eq 'ok') {
 3775:                 return '/uploaded/'.$fpath.'/'.$fname;
 3776:             } else {
 3777:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3778:                         ' to host '.$home.': '.$fetchresult);
 3779:                 return '/adm/notfound.html';
 3780:             }
 3781:         }
 3782:     }
 3783:     unless ( $fetchresult eq 'ok') {
 3784:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3785:              ' to host '.$home.': '.$fetchresult);
 3786:     }
 3787:     return $fetchresult;
 3788: }
 3789: 
 3790: sub build_filepath {
 3791:     my ($fpath) = @_;
 3792:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3793:     unless ($fpath eq '') {
 3794:         my @parts=split('/',$fpath);
 3795:         foreach my $part (@parts) {
 3796:             $filepath.= '/'.$part;
 3797:             if ((-e $filepath)!=1) {
 3798:                 mkdir($filepath,0777);
 3799:             }
 3800:         }
 3801:     }
 3802:     return $filepath;
 3803: }
 3804: 
 3805: sub store_edited_file {
 3806:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3807:     my $file = $primary_url;
 3808:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3809:     my $fpath = '';
 3810:     my $fname = $file;
 3811:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3812:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3813:     my $filepath = &build_filepath($fpath);
 3814:     open(my $fh,'>',$filepath.'/'.$fname);
 3815:     print $fh $content;
 3816:     close($fh);
 3817:     my $home=&homeserver($docuname,$docudom);
 3818:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3819: 			  $home);
 3820:     if ($$fetchresult eq 'ok') {
 3821:         return '/uploaded/'.$fpath.'/'.$fname;
 3822:     } else {
 3823:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3824: 		 ' to host '.$home.': '.$$fetchresult);
 3825:         return '/adm/notfound.html';
 3826:     }
 3827: }
 3828: 
 3829: sub clean_filename {
 3830:     my ($fname,$args)=@_;
 3831: # Replace Windows backslashes by forward slashes
 3832:     $fname=~s/\\/\//g;
 3833:     if (!$args->{'keep_path'}) {
 3834:         # Get rid of everything but the actual filename
 3835: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3836:     }
 3837: # Replace spaces by underscores
 3838:     $fname=~s/\s+/\_/g;
 3839: # Replace all other weird characters by nothing
 3840:     $fname=~s{[^/\w\.\-]}{}g;
 3841: # Replace all .\d. sequences with _\d. so they no longer look like version
 3842: # numbers
 3843:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3844:     return $fname;
 3845: }
 3846: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3847: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3848: # image with the same aspect ratio as the original, but with dimensions which do 
 3849: # not exceed $resizewidth and $resizeheight.
 3850:  
 3851: sub resizeImage {
 3852:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3853:     my $ima = Image::Magick->new;
 3854:     my $resized;
 3855:     if (-e $img_path) {
 3856:         $ima->Read($img_path);
 3857:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3858:             my $width = $ima->Get('width');
 3859:             my $height = $ima->Get('height');
 3860:             if ($width > $resizewidth) {
 3861: 	        my $factor = $width/$resizewidth;
 3862:                 my $newheight = $height/$factor;
 3863:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3864:                 $resized = 1;
 3865:             }
 3866:         }
 3867:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3868:             my $width = $ima->Get('width');
 3869:             my $height = $ima->Get('height');
 3870:             if ($height > $resizeheight) {
 3871:                 my $factor = $height/$resizeheight;
 3872:                 my $newwidth = $width/$factor;
 3873:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3874:                 $resized = 1;
 3875:             }
 3876:         }
 3877:         if ($resized) {
 3878:             $ima->Write($img_path);
 3879:         }
 3880:     }
 3881:     return;
 3882: }
 3883: 
 3884: # --------------- Take an uploaded file and put it into the userfiles directory
 3885: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3886: #                    the desired filename is in $env{"form.$formname.filename"}
 3887: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3888: #                                    canceloverwrite, or ''. 
 3889: #                   if 'coursedoc': upload to the current course
 3890: #                   if 'existingfile': write file to tmp/overwrites directory 
 3891: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3892: #                   $context is passed as argument to &finishuserfileupload
 3893: #        $subdir - directory in userfile to store the file into
 3894: #        $parser - instruction to parse file for objects ($parser = parse)    
 3895: #        $allfiles - reference to hash for embedded objects
 3896: #        $codebase - reference to hash for codebase of java objects
 3897: #        $desuname - username for permanent storage of uploaded file
 3898: #        $dsetudom - domain for permanaent storage of uploaded file
 3899: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3900: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3901: #        $resizewidth - width (pixels) to which to resize uploaded image
 3902: #        $resizeheight - height (pixels) to which to resize uploaded image
 3903: #        $mimetype - reference to scalar to accommodate mime type determined
 3904: #                    from File::MMagic.
 3905: # 
 3906: # output: url of file in userspace, or error: <message> 
 3907: #             or /adm/notfound.html if failure to upload occurse
 3908: 
 3909: sub userfileupload {
 3910:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3911:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3912:     if (!defined($subdir)) { $subdir='unknown'; }
 3913:     my $fname=$env{'form.'.$formname.'.filename'};
 3914:     $fname=&clean_filename($fname);
 3915:     # See if there is anything left
 3916:     unless ($fname) { return 'error: no uploaded file'; }
 3917:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3918:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3919:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3920:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3921:         my $now = time;
 3922:         my $filepath;
 3923:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3924:              $filepath = 'tmp/helprequests/'.$now;
 3925:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3926:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3927:                          '_'.$env{'user.domain'}.'/pending';
 3928:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3929:             my ($docuname,$docudom);
 3930:             if ($destudom =~ /^$match_domain$/) {
 3931:                 $docudom = $destudom;
 3932:             } else {
 3933:                 $docudom = $env{'user.domain'};
 3934:             }
 3935:             if ($destuname =~ /^$match_username$/) {
 3936:                 $docuname = $destuname;
 3937:             } else {
 3938:                 $docuname = $env{'user.name'};
 3939:             }
 3940:             if (exists($env{'form.group'})) {
 3941:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3942:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3943:             }
 3944:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3945:             if ($context eq 'canceloverwrite') {
 3946:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3947:                 if (-e  $tempfile) {
 3948:                     my @info = stat($tempfile);
 3949:                     if ($info[9] eq $env{'form.timestamp'}) {
 3950:                         unlink($tempfile);
 3951:                     }
 3952:                 }
 3953:                 return;
 3954:             }
 3955:         }
 3956:         # Create the directory if not present
 3957:         my @parts=split(/\//,$filepath);
 3958:         my $fullpath = $perlvar{'lonDaemons'};
 3959:         for (my $i=0;$i<@parts;$i++) {
 3960:             $fullpath .= '/'.$parts[$i];
 3961:             if ((-e $fullpath)!=1) {
 3962:                 mkdir($fullpath,0777);
 3963:             }
 3964:         }
 3965:         open(my $fh,'>',$fullpath.'/'.$fname);
 3966:         print $fh $env{'form.'.$formname};
 3967:         close($fh);
 3968:         if ($context eq 'existingfile') {
 3969:             my @info = stat($fullpath.'/'.$fname);
 3970:             return ($fullpath.'/'.$fname,$info[9]);
 3971:         } else {
 3972:             return $fullpath.'/'.$fname;
 3973:         }
 3974:     }
 3975:     if ($subdir eq 'scantron') {
 3976:         $fname = 'scantron_orig_'.$fname;
 3977:     } else {
 3978:         $fname="$subdir/$fname";
 3979:     }
 3980:     if ($context eq 'coursedoc') {
 3981: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3982: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3983:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3984:             return &finishuserfileupload($docuname,$docudom,
 3985: 					 $formname,$fname,$parser,$allfiles,
 3986: 					 $codebase,$thumbwidth,$thumbheight,
 3987:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3988:         } else {
 3989:             if ($env{'form.folder'}) {
 3990:                 $fname=$env{'form.folder'}.'/'.$fname;
 3991:             }
 3992:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3993: 				       $fname,$formname,$parser,
 3994: 				       $allfiles,$codebase,$mimetype);
 3995:         }
 3996:     } elsif (defined($destuname)) {
 3997:         my $docuname=$destuname;
 3998:         my $docudom=$destudom;
 3999: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4000: 				     $parser,$allfiles,$codebase,
 4001:                                      $thumbwidth,$thumbheight,
 4002:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4003:     } else {
 4004:         my $docuname=$env{'user.name'};
 4005:         my $docudom=$env{'user.domain'};
 4006:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4007:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4008:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4009:         }
 4010: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4011: 				     $parser,$allfiles,$codebase,
 4012:                                      $thumbwidth,$thumbheight,
 4013:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4014:     }
 4015: }
 4016: 
 4017: sub finishuserfileupload {
 4018:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4019:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4020:     my $path=$docudom.'/'.$docuname.'/';
 4021:     my $filepath=$perlvar{'lonDocRoot'};
 4022:   
 4023:     my ($fnamepath,$file,$fetchthumb);
 4024:     $file=$fname;
 4025:     if ($fname=~m|/|) {
 4026:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4027: 	$path.=$fnamepath.'/';
 4028:     }
 4029:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4030:     my $count;
 4031:     for ($count=4;$count<=$#parts;$count++) {
 4032:         $filepath.="/$parts[$count]";
 4033:         if ((-e $filepath)!=1) {
 4034: 	    mkdir($filepath,0777);
 4035:         }
 4036:     }
 4037: 
 4038: # Save the file
 4039:     {
 4040: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4041: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4042: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4043: 	    return '/adm/notfound.html';
 4044: 	}
 4045:         if ($context eq 'overwrite') {
 4046:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4047:             my $target = $filepath.'/'.$file;
 4048:             if (-e $source) {
 4049:                 my @info = stat($source);
 4050:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4051:                     unless (&File::Copy::move($source,$target)) {
 4052:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4053:                         return "Moving from $source failed";
 4054:                     }
 4055:                 } else {
 4056:                     return "Temporary file: $source had unexpected date/time for last modification";
 4057:                 }
 4058:             } else {
 4059:                 return "Temporary file: $source missing";
 4060:             }
 4061:         } elsif (!print FH ($env{'form.'.$formname})) {
 4062: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4063: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4064: 	    return '/adm/notfound.html';
 4065: 	}
 4066: 	close(FH);
 4067:         if ($resizewidth && $resizeheight) {
 4068:             my $mm = new File::MMagic;
 4069:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4070:             if ($mime_type =~ m{^image/}) {
 4071: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4072:             }  
 4073: 	}
 4074:     }
 4075:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4076:         if (ref($mimetype)) {
 4077:             if ($$mimetype eq '') {
 4078:                 my $mm = new File::MMagic;
 4079:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4080:                 $$mimetype = $type;
 4081:             }
 4082:         }
 4083:     }
 4084:     if ($parser eq 'parse') {
 4085:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4086:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4087:                                                        $allfiles,$codebase);
 4088:             unless ($parse_result eq 'ok') {
 4089:                 &logthis('Failed to parse '.$filepath.$file.
 4090: 	   	         ' for embedded media: '.$parse_result); 
 4091:             }
 4092:         }
 4093:     }
 4094:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4095:         my $input = $filepath.'/'.$file;
 4096:         my $output = $filepath.'/'.'tn-'.$file;
 4097:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4098:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4099:         system({$args[0]} @args);
 4100:         if (-e $filepath.'/'.'tn-'.$file) {
 4101:             $fetchthumb  = 1; 
 4102:         }
 4103:     }
 4104:  
 4105: # Notify homeserver to grep it
 4106: #
 4107:     my $docuhome=&homeserver($docuname,$docudom);	
 4108:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4109:     if ($fetchresult eq 'ok') {
 4110:         if ($fetchthumb) {
 4111:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4112:             if ($thumbresult ne 'ok') {
 4113:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4114:                          $docuhome.': '.$thumbresult);
 4115:             }
 4116:         }
 4117: #
 4118: # Return the URL to it
 4119:         return '/uploaded/'.$path.$file;
 4120:     } else {
 4121:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4122: 		 ': '.$fetchresult);
 4123:         return '/adm/notfound.html';
 4124:     }
 4125: }
 4126: 
 4127: sub extract_embedded_items {
 4128:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4129:     my @state = ();
 4130:     my (%lastids,%related,%shockwave,%flashvars);
 4131:     my %javafiles = (
 4132:                       codebase => '',
 4133:                       code => '',
 4134:                       archive => ''
 4135:                     );
 4136:     my %mediafiles = (
 4137:                       src => '',
 4138:                       movie => '',
 4139:                      );
 4140:     my $p;
 4141:     if ($content) {
 4142:         $p = HTML::LCParser->new($content);
 4143:     } else {
 4144:         $p = HTML::LCParser->new($fullpath);
 4145:     }
 4146:     while (my $t=$p->get_token()) {
 4147: 	if ($t->[0] eq 'S') {
 4148: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4149: 	    push(@state, $tagname);
 4150:             if (lc($tagname) eq 'allow') {
 4151:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4152:             }
 4153: 	    if (lc($tagname) eq 'img') {
 4154: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4155: 	    }
 4156: 	    if (lc($tagname) eq 'a') {
 4157:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4158:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4159:                 }
 4160: 	    }
 4161:             if (lc($tagname) eq 'script') {
 4162:                 my $src;
 4163:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4164:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4165:                 } else {
 4166:                     if ($attr->{'src'} ne '') {
 4167:                         $src = $attr->{'src'};
 4168:                         &add_filetype($allfiles,$src,'src');
 4169:                     }
 4170:                 }
 4171:                 my $text = $p->get_trimmed_text();
 4172:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4173:                     my @swfargs = split(/,/,$1);
 4174:                     foreach my $item (@swfargs) {
 4175:                         $item =~ s/["']//g;
 4176:                         $item =~ s/^\s+//;
 4177:                         $item =~ s/\s+$//;
 4178:                     }
 4179:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4180:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4181:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4182:                         } else {
 4183:                             $related{$swfargs[0]} = [$swfargs[2]];
 4184:                         }
 4185:                     }
 4186:                 }
 4187:             }
 4188:             if (lc($tagname) eq 'link') {
 4189:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4190:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4191:                 }
 4192:             }
 4193: 	    if (lc($tagname) eq 'object' ||
 4194: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4195: 		foreach my $item (keys(%javafiles)) {
 4196: 		    $javafiles{$item} = '';
 4197: 		}
 4198:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4199:                     $lastids{lc($tagname)} = $attr->{'id'};
 4200:                 }
 4201: 	    }
 4202: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4203: 		my $name = lc($attr->{'name'});
 4204: 		foreach my $item (keys(%javafiles)) {
 4205: 		    if ($name eq $item) {
 4206: 			$javafiles{$item} = $attr->{'value'};
 4207: 			last;
 4208: 		    }
 4209: 		}
 4210:                 my $pathfrom;
 4211: 		foreach my $item (keys(%mediafiles)) {
 4212: 		    if ($name eq $item) {
 4213:                         $pathfrom = $attr->{'value'};
 4214:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4215: 			&add_filetype($allfiles,$pathfrom,$name);
 4216: 			last;
 4217: 		    }
 4218: 		}
 4219:                 if ($name eq 'flashvars') {
 4220:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4221:                 }
 4222:                 if ($pathfrom ne '') {
 4223:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4224:                                          $pathfrom);
 4225:                 }
 4226: 	    }
 4227: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4228: 		foreach my $item (keys(%javafiles)) {
 4229: 		    if ($attr->{$item}) {
 4230: 			$javafiles{$item} = $attr->{$item};
 4231: 			last;
 4232: 		    }
 4233: 		}
 4234: 		foreach my $item (keys(%mediafiles)) {
 4235: 		    if ($attr->{$item}) {
 4236: 			&add_filetype($allfiles,$attr->{$item},$item);
 4237: 			last;
 4238: 		    }
 4239: 		}
 4240:                 if (lc($tagname) eq 'embed') {
 4241:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4242:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4243:                                              $attr->{'src'});
 4244:                     }
 4245:                 }
 4246: 	    }
 4247:             if (lc($tagname) eq 'iframe') {
 4248:                 my $src = $attr->{'src'} ;
 4249:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4250:                     &add_filetype($allfiles,$src,'src');
 4251:                 } elsif ($src =~ m{^/}) {
 4252:                     if ($env{'request.course.id'}) {
 4253:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4254:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4255:                         my $url = &hreflocation('',$fullpath);
 4256:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4257:                             my $relpath = $1;
 4258:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4259:                                 &add_filetype($allfiles,$1,'src');
 4260:                             }
 4261:                         }
 4262:                     }
 4263:                 }
 4264:             }
 4265:             if ($t->[4] =~ m{/>$}) {
 4266:                 pop(@state);
 4267:             }
 4268: 	} elsif ($t->[0] eq 'E') {
 4269: 	    my ($tagname) = ($t->[1]);
 4270: 	    if ($javafiles{'codebase'} ne '') {
 4271: 		$javafiles{'codebase'} .= '/';
 4272: 	    }  
 4273: 	    if (lc($tagname) eq 'applet' ||
 4274: 		lc($tagname) eq 'object' ||
 4275: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4276: 		) {
 4277: 		foreach my $item (keys(%javafiles)) {
 4278: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4279: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4280: 			&add_filetype($allfiles,$file,$item);
 4281: 		    }
 4282: 		}
 4283: 	    } 
 4284: 	    pop @state;
 4285: 	}
 4286:     }
 4287:     foreach my $id (sort(keys(%flashvars))) {
 4288:         if ($shockwave{$id} ne '') {
 4289:             my @pairs = split(/\&/,$flashvars{$id});
 4290:             foreach my $pair (@pairs) {
 4291:                 my ($key,$value) = split(/\=/,$pair);
 4292:                 if ($key eq 'thumb') {
 4293:                     &add_filetype($allfiles,$value,$key);
 4294:                 } elsif ($key eq 'content') {
 4295:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4296:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4297:                     if ($ext ne '') {
 4298:                         &add_filetype($allfiles,$path.$value,$ext);
 4299:                     }
 4300:                 }
 4301:             }
 4302:         }
 4303:     }
 4304:     return 'ok';
 4305: }
 4306: 
 4307: sub add_filetype {
 4308:     my ($allfiles,$file,$type)=@_;
 4309:     if (exists($allfiles->{$file})) {
 4310: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4311: 	    push(@{$allfiles->{$file}}, &escape($type));
 4312: 	}
 4313:     } else {
 4314: 	@{$allfiles->{$file}} = (&escape($type));
 4315:     }
 4316: }
 4317: 
 4318: sub embedded_dependency {
 4319:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4320:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4321:         if (($identifier ne '') &&
 4322:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4323:             ($pathfrom ne '')) {
 4324:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4325:             foreach my $dep (@{$related->{$identifier}}) {
 4326:                 &add_filetype($allfiles,$path.$dep,'object');
 4327:             }
 4328:         }
 4329:     }
 4330:     return;
 4331: }
 4332: 
 4333: sub removeuploadedurl {
 4334:     my ($url)=@_;	
 4335:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4336:     return &removeuserfile($uname,$udom,$fname);
 4337: }
 4338: 
 4339: sub removeuserfile {
 4340:     my ($docuname,$docudom,$fname)=@_;
 4341:     my $home=&homeserver($docuname,$docudom);    
 4342:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4343:     if ($result eq 'ok') {	
 4344:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4345:             my $metafile = $fname.'.meta';
 4346:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4347: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4348:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4349:             my $sqlresult = 
 4350:                 &update_portfolio_table($docuname,$docudom,$file,
 4351:                                         'portfolio_metadata',$group,
 4352:                                         'delete');
 4353:         }
 4354:     }
 4355:     return $result;
 4356: }
 4357: 
 4358: sub mkdiruserfile {
 4359:     my ($docuname,$docudom,$dir)=@_;
 4360:     my $home=&homeserver($docuname,$docudom);
 4361:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4362: }
 4363: 
 4364: sub renameuserfile {
 4365:     my ($docuname,$docudom,$old,$new)=@_;
 4366:     my $home=&homeserver($docuname,$docudom);
 4367:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4368:                         &escape("$old").':'.&escape("$new"),$home);
 4369:     if ($result eq 'ok') {
 4370:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4371:             my $oldmeta = $old.'.meta';
 4372:             my $newmeta = $new.'.meta';
 4373:             my $metaresult = 
 4374:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4375: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4376:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4377:             my $sqlresult = 
 4378:                 &update_portfolio_table($docuname,$docudom,$file,
 4379:                                         'portfolio_metadata',$group,
 4380:                                         'delete');
 4381:         }
 4382:     }
 4383:     return $result;
 4384: }
 4385: 
 4386: # ------------------------------------------------------------------------- Log
 4387: 
 4388: sub log {
 4389:     my ($dom,$nam,$hom,$what)=@_;
 4390:     return critical("log:$dom:$nam:$what",$hom);
 4391: }
 4392: 
 4393: # ------------------------------------------------------------------ Course Log
 4394: #
 4395: # This routine flushes several buffers of non-mission-critical nature
 4396: #
 4397: 
 4398: sub flushcourselogs {
 4399:     &logthis('Flushing log buffers');
 4400: #
 4401: # course logs
 4402: # This is a log of all transactions in a course, which can be used
 4403: # for data mining purposes
 4404: #
 4405: # It also collects the courseid database, which lists last transaction
 4406: # times and course titles for all courseids
 4407: #
 4408:     my %courseidbuffer=();
 4409:     foreach my $crsid (keys(%courselogs)) {
 4410:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4411: 		          &escape($courselogs{$crsid}),
 4412: 		          $coursehombuf{$crsid}) eq 'ok') {
 4413: 	    delete $courselogs{$crsid};
 4414:         } else {
 4415:             &logthis('Failed to flush log buffer for '.$crsid);
 4416:             if (length($courselogs{$crsid})>40000) {
 4417:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4418:                         " exceeded maximum size, deleting.</font>");
 4419:                delete $courselogs{$crsid};
 4420:             }
 4421:         }
 4422:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4423:             'description' => $coursedescrbuf{$crsid},
 4424:             'inst_code'    => $courseinstcodebuf{$crsid},
 4425:             'type'        => $coursetypebuf{$crsid},
 4426:             'owner'       => $courseownerbuf{$crsid},
 4427:         };
 4428:     }
 4429: #
 4430: # Write course id database (reverse lookup) to homeserver of courses 
 4431: # Is used in pickcourse
 4432: #
 4433:     foreach my $crs_home (keys(%courseidbuffer)) {
 4434:         my $response = &courseidput(&host_domain($crs_home),
 4435:                                     $courseidbuffer{$crs_home},
 4436:                                     $crs_home,'timeonly');
 4437:     }
 4438: #
 4439: # File accesses
 4440: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4441: #
 4442:     foreach my $entry (keys(%accesshash)) {
 4443:         if ($entry =~ /___count$/) {
 4444:             my ($dom,$name);
 4445:             ($dom,$name,undef)=
 4446: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4447:             if (! defined($dom) || $dom eq '' || 
 4448:                 ! defined($name) || $name eq '') {
 4449:                 my $cid = $env{'request.course.id'};
 4450:                 $dom  = $env{'request.'.$cid.'.domain'};
 4451:                 $name = $env{'request.'.$cid.'.num'};
 4452:             }
 4453:             my $value = $accesshash{$entry};
 4454:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4455:             my %temphash=($url => $value);
 4456:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4457:             if ($result eq 'ok') {
 4458:                 delete $accesshash{$entry};
 4459:             }
 4460:         } else {
 4461:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4462:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4463:             my %temphash=($entry => $accesshash{$entry});
 4464:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4465:                 delete $accesshash{$entry};
 4466:             }
 4467:         }
 4468:     }
 4469: #
 4470: # Roles
 4471: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4472: #
 4473:     foreach my $entry (keys(%userrolehash)) {
 4474:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4475: 	    split(/\:/,$entry);
 4476:         if (&Apache::lonnet::put('nohist_userroles',
 4477:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4478:                 $rudom,$runame) eq 'ok') {
 4479: 	    delete $userrolehash{$entry};
 4480:         }
 4481:     }
 4482: #
 4483: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4484: #
 4485:     my %domrolebuffer = ();
 4486:     foreach my $entry (keys(%domainrolehash)) {
 4487:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4488:         if ($domrolebuffer{$rudom}) {
 4489:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4490:                       '='.&escape($domainrolehash{$entry});
 4491:         } else {
 4492:             $domrolebuffer{$rudom}.=&escape($entry).
 4493:                       '='.&escape($domainrolehash{$entry});
 4494:         }
 4495:         delete $domainrolehash{$entry};
 4496:     }
 4497:     foreach my $dom (keys(%domrolebuffer)) {
 4498: 	my %servers;
 4499: 	if (defined(&domain($dom,'primary'))) {
 4500: 	    my $primary=&domain($dom,'primary');
 4501: 	    my $hostname=&hostname($primary);
 4502: 	    $servers{$primary} = $hostname;
 4503: 	} else { 
 4504: 	    %servers = &get_servers($dom,'library');
 4505: 	}
 4506: 	foreach my $tryserver (keys(%servers)) {
 4507: 	    if (&reply('domroleput:'.$dom.':'.
 4508: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4509: 		last;
 4510: 	    } else {  
 4511: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4512: 	    }
 4513:         }
 4514:     }
 4515:     $dumpcount++;
 4516: }
 4517: 
 4518: sub courselog {
 4519:     my $what=shift;
 4520:     $what=time.':'.$what;
 4521:     unless ($env{'request.course.id'}) { return ''; }
 4522:     $coursedombuf{$env{'request.course.id'}}=
 4523:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4524:     $coursenumbuf{$env{'request.course.id'}}=
 4525:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4526:     $coursehombuf{$env{'request.course.id'}}=
 4527:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4528:     $coursedescrbuf{$env{'request.course.id'}}=
 4529:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4530:     $courseinstcodebuf{$env{'request.course.id'}}=
 4531:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4532:     $courseownerbuf{$env{'request.course.id'}}=
 4533:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4534:     $coursetypebuf{$env{'request.course.id'}}=
 4535:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4536:     if (defined $courselogs{$env{'request.course.id'}}) {
 4537: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4538:     } else {
 4539: 	$courselogs{$env{'request.course.id'}}.=$what;
 4540:     }
 4541:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4542: 	&flushcourselogs();
 4543:     }
 4544: }
 4545: 
 4546: sub courseacclog {
 4547:     my $fnsymb=shift;
 4548:     unless ($env{'request.course.id'}) { return ''; }
 4549:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4550:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4551:         $what.=':POST';
 4552:         # FIXME: Probably ought to escape things....
 4553: 	foreach my $key (keys(%env)) {
 4554:             if ($key=~/^form\.(.*)/) {
 4555:                 my $formitem = $1;
 4556:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4557:                     $what.=':'.$formitem.'='.$env{$key};
 4558:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4559:                     $what.=':'.$formitem.'='.$env{$key};
 4560:                 }
 4561:             }
 4562:         }
 4563:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4564:         # FIXME: We should not be depending on a form parameter that someone
 4565:         # editing lonsearchcat.pm might change in the future.
 4566:         if ($env{'form.phase'} eq 'course_search') {
 4567:             $what.= ':POST';
 4568:             # FIXME: Probably ought to escape things....
 4569:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4570:                                  'crsdiscuss') {
 4571:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4572:             }
 4573:         }
 4574:     }
 4575:     &courselog($what);
 4576: }
 4577: 
 4578: sub countacc {
 4579:     my $url=&declutter(shift);
 4580:     return if (! defined($url) || $url eq '');
 4581:     unless ($env{'request.course.id'}) { return ''; }
 4582: #
 4583: # Mark that this url was used in this course
 4584: #
 4585:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4586: #
 4587: # Increase the access count for this resource in this child process
 4588: #
 4589:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4590:     $accesshash{$key}++;
 4591: }
 4592: 
 4593: sub linklog {
 4594:     my ($from,$to)=@_;
 4595:     $from=&declutter($from);
 4596:     $to=&declutter($to);
 4597:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4598:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4599: }
 4600: 
 4601: sub statslog {
 4602:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4603:     if ($users<2) { return; }
 4604:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4605:             'course'       => $env{'request.course.id'},
 4606:             'sections'     => '"all"',
 4607:             'num_students' => $users,
 4608:             'part'         => $part,
 4609:             'symb'         => $symb,
 4610:             'mean_tries'   => $av_attempts,
 4611:             'deg_of_diff'  => $degdiff});
 4612:     foreach my $key (keys(%dynstore)) {
 4613:         $accesshash{$key}=$dynstore{$key};
 4614:     }
 4615: }
 4616:   
 4617: sub userrolelog {
 4618:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4619:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4620:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4621:        $userrolehash
 4622:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4623:                     =$tend.':'.$tstart;
 4624:     }
 4625:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4626:        $userrolehash
 4627:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4628:                     =$tend.':'.$tstart;
 4629:     }
 4630:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4631:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4632:        $domainrolehash
 4633:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4634:                     = $tend.':'.$tstart;
 4635:     }
 4636: }
 4637: 
 4638: sub courserolelog {
 4639:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4640:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4641:         my $cdom = $1;
 4642:         my $cnum = $2;
 4643:         my $sec = $3;
 4644:         my $namespace = 'rolelog';
 4645:         my %storehash = (
 4646:                            role    => $trole,
 4647:                            start   => $tstart,
 4648:                            end     => $tend,
 4649:                            selfenroll => $selfenroll,
 4650:                            context    => $context,
 4651:                         );
 4652:         if ($trole eq 'gr') {
 4653:             $namespace = 'groupslog';
 4654:             $storehash{'group'} = $sec;
 4655:         } else {
 4656:             $storehash{'section'} = $sec;
 4657:         }
 4658:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4659:                    $domain,$cnum,$cdom);
 4660:         if (($trole ne 'st') || ($sec ne '')) {
 4661:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4662:         }
 4663:     }
 4664:     return;
 4665: }
 4666: 
 4667: sub domainrolelog {
 4668:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4669:     if ($area =~ m{^/($match_domain)/$}) {
 4670:         my $cdom = $1;
 4671:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4672:         my $namespace = 'rolelog';
 4673:         my %storehash = (
 4674:                            role    => $trole,
 4675:                            start   => $tstart,
 4676:                            end     => $tend,
 4677:                            context => $context,
 4678:                         );
 4679:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4680:                    $domain,$domconfiguser,$cdom);
 4681:     }
 4682:     return;
 4683: 
 4684: }
 4685: 
 4686: sub coauthorrolelog {
 4687:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4688:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4689:         my $audom = $1;
 4690:         my $auname = $2;
 4691:         my $namespace = 'rolelog';
 4692:         my %storehash = (
 4693:                            role    => $trole,
 4694:                            start   => $tstart,
 4695:                            end     => $tend,
 4696:                            context => $context,
 4697:                         );
 4698:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4699:                    $domain,$auname,$audom);
 4700:     }
 4701:     return;
 4702: }
 4703: 
 4704: sub get_course_adv_roles {
 4705:     my ($cid,$codes) = @_;
 4706:     $cid=$env{'request.course.id'} unless (defined($cid));
 4707:     my %coursehash=&coursedescription($cid);
 4708:     my $crstype = &Apache::loncommon::course_type($cid);
 4709:     my %nothide=();
 4710:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4711:         if ($user !~ /:/) {
 4712: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4713:         } else {
 4714:             $nothide{$user}=1;
 4715:         }
 4716:     }
 4717:     my @possdoms = ($coursehash{'domain'});
 4718:     if ($coursehash{'checkforpriv'}) {
 4719:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4720:     }
 4721:     my %returnhash=();
 4722:     my %dumphash=
 4723:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4724:     my $now=time;
 4725:     my %privileged;
 4726:     foreach my $entry (keys(%dumphash)) {
 4727: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4728:         if (($tstart) && ($tstart<0)) { next; }
 4729:         if (($tend) && ($tend<$now)) { next; }
 4730:         if (($tstart) && ($now<$tstart)) { next; }
 4731:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4732: 	if ($username eq '' || $domain eq '') { next; }
 4733:         if ((&privileged($username,$domain,\@possdoms)) &&
 4734:             (!$nothide{$username.':'.$domain})) { next; }
 4735: 	if ($role eq 'cr') { next; }
 4736:         if ($codes) {
 4737:             if ($section) { $role .= ':'.$section; }
 4738:             if ($returnhash{$role}) {
 4739:                 $returnhash{$role}.=','.$username.':'.$domain;
 4740:             } else {
 4741:                 $returnhash{$role}=$username.':'.$domain;
 4742:             }
 4743:         } else {
 4744:             my $key=&plaintext($role,$crstype);
 4745:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4746:             if ($returnhash{$key}) {
 4747: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4748:             } else {
 4749:                 $returnhash{$key}=$username.':'.$domain;
 4750:             }
 4751:         }
 4752:     }
 4753:     return %returnhash;
 4754: }
 4755: 
 4756: sub get_my_roles {
 4757:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4758:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4759:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4760:     my (%dumphash,%nothide);
 4761:     if ($context eq 'userroles') {
 4762:         %dumphash = &dump('roles',$udom,$uname);
 4763:     } else {
 4764:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4765:         if ($hidepriv) {
 4766:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4767:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4768:                 if ($user !~ /:/) {
 4769:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4770:                 } else {
 4771:                     $nothide{$user} = 1;
 4772:                 }
 4773:             }
 4774:         }
 4775:     }
 4776:     my %returnhash=();
 4777:     my $now=time;
 4778:     my %privileged;
 4779:     foreach my $entry (keys(%dumphash)) {
 4780:         my ($role,$tend,$tstart);
 4781:         if ($context eq 'userroles') {
 4782:             next if ($entry =~ /^rolesdef/);
 4783: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4784:         } else {
 4785:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4786:         }
 4787:         if (($tstart) && ($tstart<0)) { next; }
 4788:         my $status = 'active';
 4789:         if (($tend) && ($tend<=$now)) {
 4790:             $status = 'previous';
 4791:         } 
 4792:         if (($tstart) && ($now<$tstart)) {
 4793:             $status = 'future';
 4794:         }
 4795:         if (ref($types) eq 'ARRAY') {
 4796:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4797:                 next;
 4798:             } 
 4799:         } else {
 4800:             if ($status ne 'active') {
 4801:                 next;
 4802:             }
 4803:         }
 4804:         my ($rolecode,$username,$domain,$section,$area);
 4805:         if ($context eq 'userroles') {
 4806:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4807:             (undef,$domain,$username,$section) = split(/\//,$area);
 4808:         } else {
 4809:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4810:         }
 4811:         if (ref($roledoms) eq 'ARRAY') {
 4812:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4813:                 next;
 4814:             }
 4815:         }
 4816:         if (ref($roles) eq 'ARRAY') {
 4817:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4818:                 if ($role =~ /^cr\//) {
 4819:                     if (!grep(/^cr$/,@{$roles})) {
 4820:                         next;
 4821:                     }
 4822:                 } elsif ($role =~ /^gr\//) {
 4823:                     if (!grep(/^gr$/,@{$roles})) {
 4824:                         next;
 4825:                     }
 4826:                 } else {
 4827:                     next;
 4828:                 }
 4829:             }
 4830:         }
 4831:         if ($hidepriv) {
 4832:             my @privroles = ('dc','su');
 4833:             if ($context eq 'userroles') {
 4834:                 next if (grep(/^\Q$role\E$/,@privroles));
 4835:             } else {
 4836:                 my $possdoms = [$domain];
 4837:                 if (ref($roledoms) eq 'ARRAY') {
 4838:                    push(@{$possdoms},@{$roledoms}); 
 4839:                 }
 4840:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4841:                     if (!$nothide{$username.':'.$domain}) {
 4842:                         next;
 4843:                     }
 4844:                 }
 4845:             }
 4846:         }
 4847:         if ($withsec) {
 4848:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4849:                 $tstart.':'.$tend;
 4850:         } else {
 4851:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4852:         }
 4853:     }
 4854:     return %returnhash;
 4855: }
 4856: 
 4857: sub get_all_adhocroles {
 4858:     my ($dom) = @_;
 4859:     my @roles_by_num = ();
 4860:     my %domdefaults = &get_domain_defaults($dom);
 4861:     my (%description,%access_in_dom,%access_info);
 4862:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4863:         my $count = 0;
 4864:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4865:         my %ordered;
 4866:         foreach my $role (sort(keys(%domcurrent))) {
 4867:             my ($order,$desc,$access_in_dom);
 4868:             if (ref($domcurrent{$role}) eq 'HASH') {
 4869:                 $order = $domcurrent{$role}{'order'};
 4870:                 $desc = $domcurrent{$role}{'desc'};
 4871:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4872:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4873:             }
 4874:             if ($order eq '') {
 4875:                 $order = $count;
 4876:             }
 4877:             $ordered{$order} = $role;
 4878:             if ($desc ne '') {
 4879:                 $description{$role} = $desc;
 4880:             } else {
 4881:                 $description{$role}= $role;
 4882:             }
 4883:             $count++;
 4884:         }
 4885:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4886:             push(@roles_by_num,$ordered{$item});
 4887:         }
 4888:     }
 4889:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4890: }
 4891: 
 4892: sub get_my_adhocroles {
 4893:     my ($cid,$checkreg) = @_;
 4894:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4895:     if ($env{'request.course.id'} eq $cid) {
 4896:         $cdom = $env{'course.'.$cid.'.domain'};
 4897:         $cnum = $env{'course.'.$cid.'.num'};
 4898:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4899:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4900:         $cdom = $1;
 4901:         $cnum = $2;
 4902:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4903:                                      $cdom,$cnum);
 4904:     }
 4905:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4906:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4907:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4908:         if ($rosterhash{$user} ne '') {
 4909:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4910:             return ([],{}) if ($type eq 'auto');
 4911:         }
 4912:     }
 4913:     if (($cdom ne '') && ($cnum ne ''))  {
 4914:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4915:             my $then=$env{'user.login.time'};
 4916:             my $update=$env{'user.update.time'};
 4917:             if (!$update) {
 4918:                 $update = $then;
 4919:             }
 4920:             my @liveroles;
 4921:             foreach my $role ('dh','da') {
 4922:                 if ($env{"user.role.$role./$cdom/"}) {
 4923:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4924:                     my $limit = $update;
 4925:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4926:                         $limit = $then;
 4927:                     }
 4928:                     my $activerole = 1;
 4929:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4930:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4931:                     if ($activerole) {
 4932:                         push(@liveroles,$role);
 4933:                     }
 4934:                 }
 4935:             }
 4936:             if (@liveroles) {
 4937:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4938:                     my ($accessref,$accessinfo,%access_in_dom);
 4939:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4940:                     if (ref($roles_by_num) eq 'ARRAY') {
 4941:                         if (@{$roles_by_num}) {
 4942:                             my %settings;
 4943:                             if ($env{'request.course.id'} eq $cid) {
 4944:                                 foreach my $envkey (keys(%env)) {
 4945:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4946:                                         $settings{$1} = $env{$envkey};
 4947:                                     }
 4948:                                 }
 4949:                             } else {
 4950:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4951:                             }
 4952:                             my %setincrs;
 4953:                             if ($settings{'internal.adhocaccess'}) {
 4954:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4955:                             }
 4956:                             my @statuses;
 4957:                             if ($env{'environment.inststatus'}) {
 4958:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4959:                             }
 4960:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4961:                             if (ref($accessref) eq 'HASH') {
 4962:                                 %access_in_dom = %{$accessref};
 4963:                             }
 4964:                             foreach my $role (@{$roles_by_num}) {
 4965:                                 my ($curraccess,@okstatus,@personnel);
 4966:                                 if ($setincrs{$role}) {
 4967:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4968:                                     if ($curraccess eq 'status') {
 4969:                                         @okstatus = split(/\&/,$rest);
 4970:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4971:                                         @personnel = split(/\&/,$rest);
 4972:                                     }
 4973:                                 } else {
 4974:                                     $curraccess = $access_in_dom{$role};
 4975:                                     if (ref($accessinfo) eq 'HASH') {
 4976:                                         if ($curraccess eq 'status') {
 4977:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4978:                                                 @okstatus = @{$accessinfo->{$role}};
 4979:                                             }
 4980:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4981:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4982:                                                 @personnel = @{$accessinfo->{$role}};
 4983:                                             }
 4984:                                         }
 4985:                                     }
 4986:                                 }
 4987:                                 if ($curraccess eq 'none') {
 4988:                                     next;
 4989:                                 } elsif ($curraccess eq 'all') {
 4990:                                     push(@possroles,$role);
 4991:                                 } elsif ($curraccess eq 'dh') {
 4992:                                     if (grep(/^dh$/,@liveroles)) {
 4993:                                         push(@possroles,$role);
 4994:                                     } else {
 4995:                                         next;
 4996:                                     }
 4997:                                 } elsif ($curraccess eq 'da') {
 4998:                                     if (grep(/^da$/,@liveroles)) {
 4999:                                         push(@possroles,$role);
 5000:                                     } else {
 5001:                                         next;
 5002:                                     }
 5003:                                 } elsif ($curraccess eq 'status') {
 5004:                                     if (@okstatus) {
 5005:                                         if (!@statuses) {
 5006:                                             if (grep(/^default$/,@okstatus)) {
 5007:                                                 push(@possroles,$role);
 5008:                                             }
 5009:                                         } else {
 5010:                                             foreach my $status (@okstatus) {
 5011:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5012:                                                     push(@possroles,$role);
 5013:                                                     last;
 5014:                                                 }
 5015:                                             }
 5016:                                         }
 5017:                                     }
 5018:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5019:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5020:                                         if ($curraccess eq 'exc') {
 5021:                                             push(@possroles,$role);
 5022:                                         }
 5023:                                     } elsif ($curraccess eq 'inc') {
 5024:                                         push(@possroles,$role);
 5025:                                     }
 5026:                                 }
 5027:                             }
 5028:                         }
 5029:                     }
 5030:                 }
 5031:             }
 5032:         }
 5033:     }
 5034:     unless (ref($description) eq 'HASH') {
 5035:         if (ref($roles_by_num) eq 'ARRAY') {
 5036:             my %desc;
 5037:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5038:             $description = \%desc;
 5039:         } else {
 5040:             $description = {};
 5041:         }
 5042:     }
 5043:     return (\@possroles,$description);
 5044: }
 5045: 
 5046: # ----------------------------------------------------- Frontpage Announcements
 5047: #
 5048: #
 5049: 
 5050: sub postannounce {
 5051:     my ($server,$text)=@_;
 5052:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5053:     unless ($text=~/\w/) { $text=''; }
 5054:     return &reply('setannounce:'.&escape($text),$server);
 5055: }
 5056: 
 5057: sub getannounce {
 5058: 
 5059:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5060: 	my $announcement='';
 5061: 	while (my $line = <$fh>) { $announcement .= $line; }
 5062: 	close($fh);
 5063: 	if ($announcement=~/\w/) { 
 5064: 	    return 
 5065:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5066:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5067: 	} else {
 5068: 	    return '';
 5069: 	}
 5070:     } else {
 5071: 	return '';
 5072:     }
 5073: }
 5074: 
 5075: # ---------------------------------------------------------- Course ID routines
 5076: # Deal with domain's nohist_courseid.db files
 5077: #
 5078: 
 5079: sub courseidput {
 5080:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5081:     return unless (ref($storehash) eq 'HASH');
 5082:     my $outcome;
 5083:     if ($caller eq 'timeonly') {
 5084:         my $cids = '';
 5085:         foreach my $item (keys(%$storehash)) {
 5086:             $cids.=&escape($item).'&';
 5087:         }
 5088:         $cids=~s/\&$//;
 5089:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5090:                           $coursehome);       
 5091:     } else {
 5092:         my $items = '';
 5093:         foreach my $item (keys(%$storehash)) {
 5094:             $items.= &escape($item).'='.
 5095:                      &freeze_escape($$storehash{$item}).'&';
 5096:         }
 5097:         $items=~s/\&$//;
 5098:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5099:                           $coursehome);
 5100:     }
 5101:     if ($outcome eq 'unknown_cmd') {
 5102:         my $what;
 5103:         foreach my $cid (keys(%$storehash)) {
 5104:             $what .= &escape($cid).'=';
 5105:             foreach my $item ('description','inst_code','owner','type') {
 5106:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5107:             }
 5108:             $what =~ s/\:$/&/;
 5109:         }
 5110:         $what =~ s/\&$//;  
 5111:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5112:     } else {
 5113:         return $outcome;
 5114:     }
 5115: }
 5116: 
 5117: sub courseiddump {
 5118:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5119:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5120:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5121:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5122:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5123:     my $as_hash = 1;
 5124:     my %returnhash;
 5125:     if (!$domfilter) { $domfilter=''; }
 5126:     my %libserv = &all_library();
 5127:     foreach my $tryserver (keys(%libserv)) {
 5128:         if ( (  $hostidflag == 1 
 5129: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5130: 	     || (!defined($hostidflag)) ) {
 5131: 
 5132: 	    if (($domfilter eq '') ||
 5133: 		(&host_domain($tryserver) eq $domfilter)) {
 5134:                 my $rep;
 5135:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5136:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5137:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5138:                                 &escape($descfilter), &escape($instcodefilter), 
 5139:                                 &escape($ownerfilter), &escape($coursefilter),
 5140:                                 &escape($typefilter), &escape($regexp_ok), 
 5141:                                 $as_hash, &escape($selfenrollonly), 
 5142:                                 &escape($catfilter), $showhidden, $caller, 
 5143:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5144:                                 &escape($createdbefore), &escape($createdafter), 
 5145:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5146:                                 $reqcrsdom,&escape($reqinstcode))));
 5147:                 } else {
 5148:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5149:                              $sincefilter.':'.&escape($descfilter).':'.
 5150:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5151:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5152:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5153:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5154:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5155:                              &escape($cc_clone).':'.$cloneonly.':'.
 5156:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5157:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5158:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5159:                 }
 5160:                      
 5161:                 my @pairs=split(/\&/,$rep);
 5162:                 foreach my $item (@pairs) {
 5163:                     my ($key,$value)=split(/\=/,$item,2);
 5164:                     $key = &unescape($key);
 5165:                     next if ($key =~ /^error: 2 /);
 5166:                     my $result = &thaw_unescape($value);
 5167:                     if (ref($result) eq 'HASH') {
 5168:                         $returnhash{$key}=$result;
 5169:                     } else {
 5170:                         my @responses = split(/:/,$value);
 5171:                         my @items = ('description','inst_code','owner','type');
 5172:                         for (my $i=0; $i<@responses; $i++) {
 5173:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5174:                         }
 5175:                     }
 5176:                 }
 5177:             }
 5178:         }
 5179:     }
 5180:     return %returnhash;
 5181: }
 5182: 
 5183: sub courselastaccess {
 5184:     my ($cdom,$cnum,$hostidref) = @_;
 5185:     my %returnhash;
 5186:     if ($cdom && $cnum) {
 5187:         my $chome = &homeserver($cnum,$cdom);
 5188:         if ($chome ne 'no_host') {
 5189:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5190:             &extract_lastaccess(\%returnhash,$rep);
 5191:         }
 5192:     } else {
 5193:         if (!$cdom) { $cdom=''; }
 5194:         my %libserv = &all_library();
 5195:         foreach my $tryserver (keys(%libserv)) {
 5196:             if (ref($hostidref) eq 'ARRAY') {
 5197:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5198:             } 
 5199:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5200:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5201:                 &extract_lastaccess(\%returnhash,$rep);
 5202:             }
 5203:         }
 5204:     }
 5205:     return %returnhash;
 5206: }
 5207: 
 5208: sub extract_lastaccess {
 5209:     my ($returnhash,$rep) = @_;
 5210:     if (ref($returnhash) eq 'HASH') {
 5211:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5212:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5213:                  $rep eq '') {
 5214:             my @pairs=split(/\&/,$rep);
 5215:             foreach my $item (@pairs) {
 5216:                 my ($key,$value)=split(/\=/,$item,2);
 5217:                 $key = &unescape($key);
 5218:                 next if ($key =~ /^error: 2 /);
 5219:                 $returnhash->{$key} = &thaw_unescape($value);
 5220:             }
 5221:         }
 5222:     }
 5223:     return;
 5224: }
 5225: 
 5226: # ---------------------------------------------------------- DC e-mail
 5227: 
 5228: sub dcmailput {
 5229:     my ($domain,$msgid,$message,$server)=@_;
 5230:     my $status = &Apache::lonnet::critical(
 5231:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5232:        &escape($message),$server);
 5233:     return $status;
 5234: }
 5235: 
 5236: sub dcmaildump {
 5237:     my ($dom,$startdate,$enddate,$senders) = @_;
 5238:     my %returnhash=();
 5239: 
 5240:     if (defined(&domain($dom,'primary'))) {
 5241:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5242:                                                          &escape($enddate).':';
 5243: 	my @esc_senders=map { &escape($_)} @$senders;
 5244: 	$cmd.=&escape(join('&',@esc_senders));
 5245: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5246:             my ($key,$value) = split(/\=/,$line,2);
 5247:             if (($key) && ($value)) {
 5248:                 $returnhash{&unescape($key)} = &unescape($value);
 5249:             }
 5250:         }
 5251:     }
 5252:     return %returnhash;
 5253: }
 5254: # ---------------------------------------------------------- Domain roles
 5255: 
 5256: sub get_domain_roles {
 5257:     my ($dom,$roles,$startdate,$enddate)=@_;
 5258:     if ((!defined($startdate)) || ($startdate eq '')) {
 5259:         $startdate = '.';
 5260:     }
 5261:     if ((!defined($enddate)) || ($enddate eq '')) {
 5262:         $enddate = '.';
 5263:     }
 5264:     my $rolelist;
 5265:     if (ref($roles) eq 'ARRAY') {
 5266:         $rolelist = join('&',@{$roles});
 5267:     }
 5268:     my %personnel = ();
 5269: 
 5270:     my %servers = &get_servers($dom,'library');
 5271:     foreach my $tryserver (keys(%servers)) {
 5272: 	%{$personnel{$tryserver}}=();
 5273: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5274: 					    &escape($startdate).':'.
 5275: 					    &escape($enddate).':'.
 5276: 					    &escape($rolelist), $tryserver))) {
 5277: 	    my ($key,$value) = split(/\=/,$line,2);
 5278: 	    if (($key) && ($value)) {
 5279: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5280: 	    }
 5281: 	}
 5282:     }
 5283:     return %personnel;
 5284: }
 5285: 
 5286: sub get_active_domroles {
 5287:     my ($dom,$roles) = @_;
 5288:     return () unless (ref($roles) eq 'ARRAY');
 5289:     my $now = time;
 5290:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5291:     my %domroles;
 5292:     foreach my $server (keys(%dompersonnel)) {
 5293:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5294:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5295:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5296:         }
 5297:     }
 5298:     return %domroles;
 5299: }
 5300: 
 5301: # ----------------------------------------------------------- Interval timing 
 5302: 
 5303: {
 5304: # Caches needed for speedup of navmaps
 5305: # We don't want to cache this for very long at all (5 seconds at most)
 5306: # 
 5307: # The user for whom we cache
 5308: my $cachedkey='';
 5309: # The cached times for this user
 5310: my %cachedtimes=();
 5311: # When this was last done
 5312: my $cachedtime='';
 5313: 
 5314: sub load_all_first_access {
 5315:     my ($uname,$udom,$ignorecache)=@_;
 5316:     if (($cachedkey eq $uname.':'.$udom) &&
 5317:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5318:         (!$ignorecache)) {
 5319:         return;
 5320:     }
 5321:     $cachedtime=time;
 5322:     $cachedkey=$uname.':'.$udom;
 5323:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5324: }
 5325: 
 5326: sub get_first_access {
 5327:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5328:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5329:     if ($argsymb) { $symb=$argsymb; }
 5330:     my ($map,$id,$res)=&decode_symb($symb);
 5331:     if ($argmap) { $map = $argmap; }
 5332:     if ($type eq 'course') {
 5333: 	$res='course';
 5334:     } elsif ($type eq 'map') {
 5335: 	$res=&symbread($map);
 5336:     } else {
 5337: 	$res=$symb;
 5338:     }
 5339:     &load_all_first_access($uname,$udom,$ignorecache);
 5340:     return $cachedtimes{"$courseid\0$res"};
 5341: }
 5342: 
 5343: sub set_first_access {
 5344:     my ($type,$interval)=@_;
 5345:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5346:     my ($map,$id,$res)=&decode_symb($symb);
 5347:     if ($type eq 'course') {
 5348: 	$res='course';
 5349:     } elsif ($type eq 'map') {
 5350: 	$res=&symbread($map);
 5351:     } else {
 5352: 	$res=$symb;
 5353:     }
 5354:     $cachedkey='';
 5355:     my $firstaccess=&get_first_access($type,$symb,$map);
 5356:     if ($firstaccess) {
 5357:         &logthis("First access time already set ($firstaccess) when attempting ".
 5358:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5359:                  "in $courseid");
 5360:         return 'already_set';
 5361:     } else {
 5362:         my $start = time;
 5363: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5364:                           $udom,$uname);
 5365:         if ($putres eq 'ok') {
 5366:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5367:                  $udom,$uname); 
 5368:             &appenv(
 5369:                      {
 5370:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5371:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5372:                      }
 5373:                   );
 5374:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5375:                 $cachedtimes{"$courseid\0$res"} = $start;
 5376:             }
 5377:         } elsif ($putres ne 'refused') {
 5378:             &logthis("Result: $putres when attempting to set first access time ".
 5379:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5380:         }
 5381:         return $putres;
 5382:     }
 5383:     return 'already_set';
 5384: }
 5385: }
 5386: 
 5387: # --------------------------------------------- Set Expire Date for Spreadsheet
 5388: 
 5389: sub expirespread {
 5390:     my ($uname,$udom,$stype,$usymb)=@_;
 5391:     my $cid=$env{'request.course.id'}; 
 5392:     if ($cid) {
 5393:        my $now=time;
 5394:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5395:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5396:                             $env{'course.'.$cid.'.num'}.
 5397: 	        	    ':nohist_expirationdates:'.
 5398:                             &escape($key).'='.$now,
 5399:                             $env{'course.'.$cid.'.home'})
 5400:     }
 5401:     return 'ok';
 5402: }
 5403: 
 5404: # ----------------------------------------------------- Devalidate Spreadsheets
 5405: 
 5406: sub devalidate {
 5407:     my ($symb,$uname,$udom)=@_;
 5408:     my $cid=$env{'request.course.id'}; 
 5409:     if ($cid) {
 5410:         # delete the stored spreadsheets for
 5411:         # - the student level sheet of this user in course's homespace
 5412:         # - the assessment level sheet for this resource 
 5413:         #   for this user in user's homespace
 5414: 	# - current conditional state info
 5415: 	my $key=$uname.':'.$udom.':';
 5416:         my $status=
 5417: 	    &del('nohist_calculatedsheets',
 5418: 		 [$key.'studentcalc:'],
 5419: 		 $env{'course.'.$cid.'.domain'},
 5420: 		 $env{'course.'.$cid.'.num'})
 5421: 		.' '.
 5422: 	    &del('nohist_calculatedsheets_'.$cid,
 5423: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5424:         unless ($status eq 'ok ok') {
 5425:            &logthis('Could not devalidate spreadsheet '.
 5426:                     $uname.' at '.$udom.' for '.
 5427: 		    $symb.': '.$status);
 5428:         }
 5429: 	&delenv('user.state.'.$cid);
 5430:     }
 5431: }
 5432: 
 5433: sub get_scalar {
 5434:     my ($string,$end) = @_;
 5435:     my $value;
 5436:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5437: 	$value = $1;
 5438:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5439: 	$value = $1;
 5440:     }
 5441:     return &unescape($value);
 5442: }
 5443: 
 5444: sub array2str {
 5445:   my (@array) = @_;
 5446:   my $result=&arrayref2str(\@array);
 5447:   $result=~s/^__ARRAY_REF__//;
 5448:   $result=~s/__END_ARRAY_REF__$//;
 5449:   return $result;
 5450: }
 5451: 
 5452: sub arrayref2str {
 5453:   my ($arrayref) = @_;
 5454:   my $result='__ARRAY_REF__';
 5455:   foreach my $elem (@$arrayref) {
 5456:     if(ref($elem) eq 'ARRAY') {
 5457:       $result.=&arrayref2str($elem).'&';
 5458:     } elsif(ref($elem) eq 'HASH') {
 5459:       $result.=&hashref2str($elem).'&';
 5460:     } elsif(ref($elem)) {
 5461:       #print("Got a ref of ".(ref($elem))." skipping.");
 5462:     } else {
 5463:       $result.=&escape($elem).'&';
 5464:     }
 5465:   }
 5466:   $result=~s/\&$//;
 5467:   $result .= '__END_ARRAY_REF__';
 5468:   return $result;
 5469: }
 5470: 
 5471: sub hash2str {
 5472:   my (%hash) = @_;
 5473:   my $result=&hashref2str(\%hash);
 5474:   $result=~s/^__HASH_REF__//;
 5475:   $result=~s/__END_HASH_REF__$//;
 5476:   return $result;
 5477: }
 5478: 
 5479: sub hashref2str {
 5480:   my ($hashref)=@_;
 5481:   my $result='__HASH_REF__';
 5482:   foreach my $key (sort(keys(%$hashref))) {
 5483:     if (ref($key) eq 'ARRAY') {
 5484:       $result.=&arrayref2str($key).'=';
 5485:     } elsif (ref($key) eq 'HASH') {
 5486:       $result.=&hashref2str($key).'=';
 5487:     } elsif (ref($key)) {
 5488:       $result.='=';
 5489:       #print("Got a ref of ".(ref($key))." skipping.");
 5490:     } else {
 5491: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5492:     }
 5493: 
 5494:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5495:       $result.=&arrayref2str($hashref->{$key}).'&';
 5496:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5497:       $result.=&hashref2str($hashref->{$key}).'&';
 5498:     } elsif(ref($hashref->{$key})) {
 5499:        $result.='&';
 5500:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5501:     } else {
 5502:       $result.=&escape($hashref->{$key}).'&';
 5503:     }
 5504:   }
 5505:   $result=~s/\&$//;
 5506:   $result .= '__END_HASH_REF__';
 5507:   return $result;
 5508: }
 5509: 
 5510: sub str2hash {
 5511:     my ($string)=@_;
 5512:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5513:     return %$hash;
 5514: }
 5515: 
 5516: sub str2hashref {
 5517:   my ($string) = @_;
 5518: 
 5519:   my %hash;
 5520: 
 5521:   if($string !~ /^__HASH_REF__/) {
 5522:       if (! ($string eq '' || !defined($string))) {
 5523: 	  $hash{'error'}='Not hash reference';
 5524:       }
 5525:       return (\%hash, $string);
 5526:   }
 5527: 
 5528:   $string =~ s/^__HASH_REF__//;
 5529: 
 5530:   while($string !~ /^__END_HASH_REF__/) {
 5531:       #key
 5532:       my $key='';
 5533:       if($string =~ /^__HASH_REF__/) {
 5534:           ($key, $string)=&str2hashref($string);
 5535:           if(defined($key->{'error'})) {
 5536:               $hash{'error'}='Bad data';
 5537:               return (\%hash, $string);
 5538:           }
 5539:       } elsif($string =~ /^__ARRAY_REF__/) {
 5540:           ($key, $string)=&str2arrayref($string);
 5541:           if($key->[0] eq 'Array reference error') {
 5542:               $hash{'error'}='Bad data';
 5543:               return (\%hash, $string);
 5544:           }
 5545:       } else {
 5546:           $string =~ s/^(.*?)=//;
 5547: 	  $key=&unescape($1);
 5548:       }
 5549:       $string =~ s/^=//;
 5550: 
 5551:       #value
 5552:       my $value='';
 5553:       if($string =~ /^__HASH_REF__/) {
 5554:           ($value, $string)=&str2hashref($string);
 5555:           if(defined($value->{'error'})) {
 5556:               $hash{'error'}='Bad data';
 5557:               return (\%hash, $string);
 5558:           }
 5559:       } elsif($string =~ /^__ARRAY_REF__/) {
 5560:           ($value, $string)=&str2arrayref($string);
 5561:           if($value->[0] eq 'Array reference error') {
 5562:               $hash{'error'}='Bad data';
 5563:               return (\%hash, $string);
 5564:           }
 5565:       } else {
 5566: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5567:       }
 5568:       $string =~ s/^&//;
 5569: 
 5570:       $hash{$key}=$value;
 5571:   }
 5572: 
 5573:   $string =~ s/^__END_HASH_REF__//;
 5574: 
 5575:   return (\%hash, $string);
 5576: }
 5577: 
 5578: sub str2array {
 5579:     my ($string)=@_;
 5580:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5581:     return @$array;
 5582: }
 5583: 
 5584: sub str2arrayref {
 5585:   my ($string) = @_;
 5586:   my @array;
 5587: 
 5588:   if($string !~ /^__ARRAY_REF__/) {
 5589:       if (! ($string eq '' || !defined($string))) {
 5590: 	  $array[0]='Array reference error';
 5591:       }
 5592:       return (\@array, $string);
 5593:   }
 5594: 
 5595:   $string =~ s/^__ARRAY_REF__//;
 5596: 
 5597:   while($string !~ /^__END_ARRAY_REF__/) {
 5598:       my $value='';
 5599:       if($string =~ /^__HASH_REF__/) {
 5600:           ($value, $string)=&str2hashref($string);
 5601:           if(defined($value->{'error'})) {
 5602:               $array[0] ='Array reference error';
 5603:               return (\@array, $string);
 5604:           }
 5605:       } elsif($string =~ /^__ARRAY_REF__/) {
 5606:           ($value, $string)=&str2arrayref($string);
 5607:           if($value->[0] eq 'Array reference error') {
 5608:               $array[0] ='Array reference error';
 5609:               return (\@array, $string);
 5610:           }
 5611:       } else {
 5612: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5613:       }
 5614:       $string =~ s/^&//;
 5615: 
 5616:       push(@array, $value);
 5617:   }
 5618: 
 5619:   $string =~ s/^__END_ARRAY_REF__//;
 5620: 
 5621:   return (\@array, $string);
 5622: }
 5623: 
 5624: # -------------------------------------------------------------------Temp Store
 5625: 
 5626: sub tmpreset {
 5627:   my ($symb,$namespace,$domain,$stuname) = @_;
 5628:   if (!$symb) {
 5629:     $symb=&symbread();
 5630:     if (!$symb) { $symb= $env{'request.url'}; }
 5631:   }
 5632:   $symb=escape($symb);
 5633: 
 5634:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5635:   $namespace=~s/\//\_/g;
 5636:   $namespace=~s/\W//g;
 5637: 
 5638:   if (!$domain) { $domain=$env{'user.domain'}; }
 5639:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5640:   if ($domain eq 'public' && $stuname eq 'public') {
 5641:       $stuname=$ENV{'REMOTE_ADDR'};
 5642:   }
 5643:   my $path=LONCAPA::tempdir();
 5644:   my %hash;
 5645:   if (tie(%hash,'GDBM_File',
 5646: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5647: 	  &GDBM_WRCREAT(),0640)) {
 5648:     foreach my $key (keys(%hash)) {
 5649:       if ($key=~ /:$symb/) {
 5650: 	delete($hash{$key});
 5651:       }
 5652:     }
 5653:   }
 5654: }
 5655: 
 5656: sub tmpstore {
 5657:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5658: 
 5659:   if (!$symb) {
 5660:     $symb=&symbread();
 5661:     if (!$symb) { $symb= $env{'request.url'}; }
 5662:   }
 5663:   $symb=escape($symb);
 5664: 
 5665:   if (!$namespace) {
 5666:     # I don't think we would ever want to store this for a course.
 5667:     # it seems this will only be used if we don't have a course.
 5668:     #$namespace=$env{'request.course.id'};
 5669:     #if (!$namespace) {
 5670:       $namespace=$env{'request.state'};
 5671:     #}
 5672:   }
 5673:   $namespace=~s/\//\_/g;
 5674:   $namespace=~s/\W//g;
 5675:   if (!$domain) { $domain=$env{'user.domain'}; }
 5676:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5677:   if ($domain eq 'public' && $stuname eq 'public') {
 5678:       $stuname=$ENV{'REMOTE_ADDR'};
 5679:   }
 5680:   my $now=time;
 5681:   my %hash;
 5682:   my $path=LONCAPA::tempdir();
 5683:   if (tie(%hash,'GDBM_File',
 5684: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5685: 	  &GDBM_WRCREAT(),0640)) {
 5686:     $hash{"version:$symb"}++;
 5687:     my $version=$hash{"version:$symb"};
 5688:     my $allkeys=''; 
 5689:     foreach my $key (keys(%$storehash)) {
 5690:       $allkeys.=$key.':';
 5691:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5692:     }
 5693:     $hash{"$version:$symb:timestamp"}=$now;
 5694:     $allkeys.='timestamp';
 5695:     $hash{"$version:keys:$symb"}=$allkeys;
 5696:     if (untie(%hash)) {
 5697:       return 'ok';
 5698:     } else {
 5699:       return "error:$!";
 5700:     }
 5701:   } else {
 5702:     return "error:$!";
 5703:   }
 5704: }
 5705: 
 5706: # -----------------------------------------------------------------Temp Restore
 5707: 
 5708: sub tmprestore {
 5709:   my ($symb,$namespace,$domain,$stuname) = @_;
 5710: 
 5711:   if (!$symb) {
 5712:     $symb=&symbread();
 5713:     if (!$symb) { $symb= $env{'request.url'}; }
 5714:   }
 5715:   $symb=escape($symb);
 5716: 
 5717:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5718: 
 5719:   if (!$domain) { $domain=$env{'user.domain'}; }
 5720:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5721:   if ($domain eq 'public' && $stuname eq 'public') {
 5722:       $stuname=$ENV{'REMOTE_ADDR'};
 5723:   }
 5724:   my %returnhash;
 5725:   $namespace=~s/\//\_/g;
 5726:   $namespace=~s/\W//g;
 5727:   my %hash;
 5728:   my $path=LONCAPA::tempdir();
 5729:   if (tie(%hash,'GDBM_File',
 5730: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5731: 	  &GDBM_READER(),0640)) {
 5732:     my $version=$hash{"version:$symb"};
 5733:     $returnhash{'version'}=$version;
 5734:     my $scope;
 5735:     for ($scope=1;$scope<=$version;$scope++) {
 5736:       my $vkeys=$hash{"$scope:keys:$symb"};
 5737:       my @keys=split(/:/,$vkeys);
 5738:       my $key;
 5739:       $returnhash{"$scope:keys"}=$vkeys;
 5740:       foreach $key (@keys) {
 5741: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5742: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5743:       }
 5744:     }
 5745:     if (!(untie(%hash))) {
 5746:       return "error:$!";
 5747:     }
 5748:   } else {
 5749:     return "error:$!";
 5750:   }
 5751:   return %returnhash;
 5752: }
 5753: 
 5754: # ----------------------------------------------------------------------- Store
 5755: 
 5756: sub store {
 5757:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5758:     my $home='';
 5759: 
 5760:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5761: 
 5762:     $symb=&symbclean($symb);
 5763:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5764: 
 5765:     if (!$domain) { $domain=$env{'user.domain'}; }
 5766:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5767: 
 5768:     &devalidate($symb,$stuname,$domain);
 5769: 
 5770:     $symb=escape($symb);
 5771:     if (!$namespace) { 
 5772:        unless ($namespace=$env{'request.course.id'}) { 
 5773:           return ''; 
 5774:        } 
 5775:     }
 5776:     if (!$home) { $home=$env{'user.home'}; }
 5777: 
 5778:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5779:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5780: 
 5781:     my $namevalue='';
 5782:     foreach my $key (keys(%$storehash)) {
 5783:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5784:     }
 5785:     $namevalue=~s/\&$//;
 5786:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5787:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5788: }
 5789: 
 5790: # -------------------------------------------------------------- Critical Store
 5791: 
 5792: sub cstore {
 5793:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5794:     my $home='';
 5795: 
 5796:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5797: 
 5798:     $symb=&symbclean($symb);
 5799:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5800: 
 5801:     if (!$domain) { $domain=$env{'user.domain'}; }
 5802:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5803: 
 5804:     &devalidate($symb,$stuname,$domain);
 5805: 
 5806:     $symb=escape($symb);
 5807:     if (!$namespace) { 
 5808:        unless ($namespace=$env{'request.course.id'}) { 
 5809:           return ''; 
 5810:        } 
 5811:     }
 5812:     if (!$home) { $home=$env{'user.home'}; }
 5813: 
 5814:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5815:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5816: 
 5817:     my $namevalue='';
 5818:     foreach my $key (keys(%$storehash)) {
 5819:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5820:     }
 5821:     $namevalue=~s/\&$//;
 5822:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5823:     return critical
 5824:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5825: }
 5826: 
 5827: # --------------------------------------------------------------------- Restore
 5828: 
 5829: sub restore {
 5830:     my ($symb,$namespace,$domain,$stuname) = @_;
 5831:     my $home='';
 5832: 
 5833:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5834: 
 5835:     if (!$symb) {
 5836:         return if ($namespace eq 'courserequests');
 5837:         unless ($symb=escape(&symbread())) { return ''; }
 5838:     } else {
 5839:         unless ($namespace eq 'courserequests') {
 5840:             $symb=&escape(&symbclean($symb));
 5841:         }
 5842:     }
 5843:     if (!$namespace) { 
 5844:        unless ($namespace=$env{'request.course.id'}) { 
 5845:           return ''; 
 5846:        } 
 5847:     }
 5848:     if (!$domain) { $domain=$env{'user.domain'}; }
 5849:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5850:     if (!$home) { $home=$env{'user.home'}; }
 5851:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5852: 
 5853:     my %returnhash=();
 5854:     foreach my $line (split(/\&/,$answer)) {
 5855: 	my ($name,$value)=split(/\=/,$line);
 5856:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5857:     }
 5858:     my $version;
 5859:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5860:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5861:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5862:        }
 5863:     }
 5864:     return %returnhash;
 5865: }
 5866: 
 5867: # ---------------------------------------------------------- Course Description
 5868: #
 5869: #  
 5870: 
 5871: sub coursedescription {
 5872:     my ($courseid,$args)=@_;
 5873:     $courseid=~s/^\///;
 5874:     $courseid=~s/\_/\//g;
 5875:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5876:     my $chome=&homeserver($cnum,$cdomain);
 5877:     my $normalid=$cdomain.'_'.$cnum;
 5878:     # need to always cache even if we get errors otherwise we keep 
 5879:     # trying and trying and trying to get the course description.
 5880:     my %envhash=();
 5881:     my %returnhash=();
 5882:     
 5883:     my $expiretime=600;
 5884:     if ($env{'request.course.id'} eq $normalid) {
 5885: 	$expiretime=120;
 5886:     }
 5887: 
 5888:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5889:     if (!$args->{'freshen_cache'}
 5890: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5891: 	foreach my $key (keys(%env)) {
 5892: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5893: 	    my ($setting) = $1;
 5894: 	    $returnhash{$setting} = $env{$key};
 5895: 	}
 5896: 	return %returnhash;
 5897:     }
 5898: 
 5899:     # get the data again
 5900: 
 5901:     if (!$args->{'one_time'}) {
 5902: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5903:     }
 5904: 
 5905:     if ($chome ne 'no_host') {
 5906:        %returnhash=&dump('environment',$cdomain,$cnum);
 5907:        if (!exists($returnhash{'con_lost'})) {
 5908: 	   my $username = $env{'user.name'}; # Defult username
 5909: 	   if(defined $args->{'user'}) {
 5910: 	       $username = $args->{'user'};
 5911: 	   }
 5912:            $returnhash{'home'}= $chome;
 5913: 	   $returnhash{'domain'} = $cdomain;
 5914: 	   $returnhash{'num'} = $cnum;
 5915:            if (!defined($returnhash{'type'})) {
 5916:                $returnhash{'type'} = 'Course';
 5917:            }
 5918:            while (my ($name,$value) = each %returnhash) {
 5919:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5920:            }
 5921:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5922:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5923: 	       $username.'_'.$cdomain.'_'.$cnum;
 5924:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5925:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5926:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5927:        }
 5928:     }
 5929:     if (!$args->{'one_time'}) {
 5930: 	&appenv(\%envhash);
 5931:     }
 5932:     return %returnhash;
 5933: }
 5934: 
 5935: sub update_released_required {
 5936:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5937:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5938:         $cid = $env{'request.course.id'};
 5939:         $cdom = $env{'course.'.$cid.'.domain'};
 5940:         $cnum = $env{'course.'.$cid.'.num'};
 5941:         $chome = $env{'course.'.$cid.'.home'};
 5942:     }
 5943:     if ($needsrelease) {
 5944:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5945:         my $needsupdate;
 5946:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5947:             $needsupdate = 1;
 5948:         } else {
 5949:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5950:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5951:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5952:                 $needsupdate = 1;
 5953:             }
 5954:         }
 5955:         if ($needsupdate) {
 5956:             my %needshash = (
 5957:                              'internal.releaserequired' => $needsrelease,
 5958:                             );
 5959:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5960:             if ($putresult eq 'ok') {
 5961:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5962:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5963:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5964:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5965:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5966:                 }
 5967:             }
 5968:         }
 5969:     }
 5970:     return;
 5971: }
 5972: 
 5973: # -------------------------------------------------See if a user is privileged
 5974: 
 5975: sub privileged {
 5976:     my ($username,$domain,$possdomains,$possroles)=@_;
 5977:     my $now = time;
 5978:     my $roles;
 5979:     if (ref($possroles) eq 'ARRAY') {
 5980:         $roles = $possroles; 
 5981:     } else {
 5982:         $roles = ['dc','su'];
 5983:     }
 5984:     if (ref($possdomains) eq 'ARRAY') {
 5985:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5986:         foreach my $dom (@{$possdomains}) {
 5987:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5988:                 (ref($privileged{$dom}) eq 'HASH')) {
 5989:                 foreach my $role (@{$roles}) {
 5990:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5991:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5992:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5993:                             return 1 unless (($end && $end < $now) ||
 5994:                                              ($start && $start > $now));
 5995:                         }
 5996:                     }
 5997:                 }
 5998:             }
 5999:         }
 6000:     } else {
 6001:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6002:         my $now = time;
 6003: 
 6004:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6005:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6006:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6007:                 return 1 unless ($tend && $tend < $now) 
 6008:                         or ($tstart && $tstart > $now);
 6009:             }
 6010:         }
 6011:     }
 6012:     return 0;
 6013: }
 6014: 
 6015: sub privileged_by_domain {
 6016:     my ($domains,$roles) = @_;
 6017:     my %privileged = ();
 6018:     my $cachetime = 60*60*24;
 6019:     my $now = time;
 6020:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6021:         return %privileged;
 6022:     }
 6023:     foreach my $dom (@{$domains}) {
 6024:         next if (ref($privileged{$dom}) eq 'HASH');
 6025:         my $needroles;
 6026:         foreach my $role (@{$roles}) {
 6027:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6028:             if (defined($cached)) {
 6029:                 if (ref($result) eq 'HASH') {
 6030:                     $privileged{$dom}{$role} = $result;
 6031:                 }
 6032:             } else {
 6033:                 $needroles = 1;
 6034:             }
 6035:         }
 6036:         if ($needroles) {
 6037:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6038:             $privileged{$dom} = {};
 6039:             foreach my $server (keys(%dompersonnel)) {
 6040:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6041:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6042:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6043:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6044:                         next if ($end && $end < $now);
 6045:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6046:                             $dompersonnel{$server}{$item};
 6047:                     }
 6048:                 }
 6049:             }
 6050:             if (ref($privileged{$dom}) eq 'HASH') {
 6051:                 foreach my $role (@{$roles}) {
 6052:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6053:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6054:                     } else {
 6055:                         my %hash = ();
 6056:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6057:                     }
 6058:                 }
 6059:             }
 6060:         }
 6061:     }
 6062:     return %privileged;
 6063: }
 6064: 
 6065: # -------------------------------------------------------- Get user privileges
 6066: 
 6067: sub rolesinit {
 6068:     my ($domain, $username) = @_;
 6069:     my %userroles = ('user.login.time' => time);
 6070:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6071: 
 6072:     # firstaccess and timerinterval are related to timed maps/resources. 
 6073:     # also, blocking can be triggered by an activating timer
 6074:     # it's saved in the user's %env.
 6075:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6076:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6077:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6078:         %timerintchk, %timerintenv);
 6079: 
 6080:     foreach my $key (keys(%firstaccess)) {
 6081:         my ($cid, $rest) = split(/\0/, $key);
 6082:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6083:     }
 6084: 
 6085:     foreach my $key (keys(%timerinterval)) {
 6086:         my ($cid,$rest) = split(/\0/,$key);
 6087:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6088:     }
 6089: 
 6090:     my %allroles=();
 6091:     my %allgroups=();
 6092: 
 6093:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6094:         my $role = $rolesdump{$area};
 6095:         $area =~ s/\_\w\w$//;
 6096: 
 6097:         my ($trole, $tend, $tstart, $group_privs);
 6098: 
 6099:         if ($role =~ /^cr/) {
 6100:         # Custom role, defined by a user 
 6101:         # e.g., user.role.cr/msu/smith/mynewrole
 6102:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6103:                 $trole = $1;
 6104:                 ($tend, $tstart) = split('_', $2);
 6105:             } else {
 6106:                 $trole = $role;
 6107:             }
 6108:         } elsif ($role =~ m|^gr/|) {
 6109:         # Role of member in a group, defined within a course/community
 6110:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6111:             ($trole, $tend, $tstart) = split(/_/, $role);
 6112:             next if $tstart eq '-1';
 6113:             ($trole, $group_privs) = split(/\//, $trole);
 6114:             $group_privs = &unescape($group_privs);
 6115:         } else {
 6116:         # Just a normal role, defined in roles.tab
 6117:             ($trole, $tend, $tstart) = split(/_/,$role);
 6118:         }
 6119: 
 6120:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6121:                  $username);
 6122:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6123: 
 6124:         # role expired or not available yet?
 6125:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6126:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6127: 
 6128:         next if $area eq '' or $trole eq '';
 6129: 
 6130:         my $spec = "$trole.$area";
 6131:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6132: 
 6133:         if ($trole =~ /^cr\//) {
 6134:         # Custom role, defined by a user
 6135:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6136:         } elsif ($trole eq 'gr') {
 6137:         # Role of a member in a group, defined within a course/community
 6138:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6139:             next;
 6140:         } else {
 6141:         # Normal role, defined in roles.tab
 6142:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6143:         }
 6144: 
 6145:         my $cid = $tdomain.'_'.$trest;
 6146:         unless ($firstaccchk{$cid}) {
 6147:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6148:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6149:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6150:                         $coursetimerstarts{$cid}{$item}; 
 6151:                 }
 6152:             }
 6153:             $firstaccchk{$cid} = 1;
 6154:         }
 6155:         unless ($timerintchk{$cid}) {
 6156:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6157:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6158:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6159:                        $coursetimerintervals{$cid}{$item};
 6160:                 }
 6161:             }
 6162:             $timerintchk{$cid} = 1;
 6163:         }
 6164:     }
 6165: 
 6166:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6167:                                                           \%allroles, \%allgroups);
 6168:     $env{'user.adv'} = $userroles{'user.adv'};
 6169:     $env{'user.rar'} = $userroles{'user.rar'};
 6170: 
 6171:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6172: }
 6173: 
 6174: sub set_arearole {
 6175:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6176:     unless ($nolog) {
 6177: # log the associated role with the area
 6178:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6179:     }
 6180:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6181: }
 6182: 
 6183: sub custom_roleprivs {
 6184:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6185:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6186:     my $homsvr = &homeserver($rauthor,$rdomain);
 6187:     if (&hostname($homsvr) ne '') {
 6188:         my ($rdummy,$roledef)=
 6189:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6190:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6191:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6192:             if (defined($syspriv)) {
 6193:                 if ($trest =~ /^$match_community$/) {
 6194:                     $syspriv =~ s/bre\&S//; 
 6195:                 }
 6196:                 $$allroles{'cm./'}.=':'.$syspriv;
 6197:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6198:             }
 6199:             if ($tdomain ne '') {
 6200:                 if (defined($dompriv)) {
 6201:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6202:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6203:                 }
 6204:                 if (($trest ne '') && (defined($coursepriv))) {
 6205:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6206:                         my $rolename = $1;
 6207:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6208:                     }
 6209:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6210:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6211:                 }
 6212:             }
 6213:         }
 6214:     }
 6215: }
 6216: 
 6217: sub course_adhocrole_privs {
 6218:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6219:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6220:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6221:         my (%currprivs,%storeprivs);
 6222:         foreach my $item (split(/:/,$coursepriv)) {
 6223:             my ($priv,$restrict) = split(/\&/,$item);
 6224:             $currprivs{$priv} = $restrict;
 6225:         }
 6226:         my (%possadd,%possremove,%full);
 6227:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6228:             my ($priv,$restrict)=split(/\&/,$item);
 6229:             $full{$priv} = $restrict;
 6230:         }
 6231:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6232:              next if ($item eq '');
 6233:              my ($rule,$rest) = split(/=/,$item);
 6234:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6235:              foreach my $priv (split(/:/,$rest)) {
 6236:                  if ($priv ne '') {
 6237:                      if ($rule eq 'off') {
 6238:                          $possremove{$priv} = 1;
 6239:                      } else {
 6240:                          $possadd{$priv} = 1;
 6241:                      }
 6242:                  }
 6243:              }
 6244:          }
 6245:          foreach my $priv (sort(keys(%full))) {
 6246:              if (exists($currprivs{$priv})) {
 6247:                  unless (exists($possremove{$priv})) {
 6248:                      $storeprivs{$priv} = $currprivs{$priv};
 6249:                  }
 6250:              } elsif (exists($possadd{$priv})) {
 6251:                  $storeprivs{$priv} = $full{$priv};
 6252:              }
 6253:          }
 6254:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6255:      }
 6256:      return $coursepriv;
 6257: }
 6258: 
 6259: sub group_roleprivs {
 6260:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6261:     my $access = 1;
 6262:     my $now = time;
 6263:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6264:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6265:     if ($access) {
 6266:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6267:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6268:     }
 6269: }
 6270: 
 6271: sub standard_roleprivs {
 6272:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6273:     if (defined($pr{$trole.':s'})) {
 6274:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6275:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6276:     }
 6277:     if ($tdomain ne '') {
 6278:         if (defined($pr{$trole.':d'})) {
 6279:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6280:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6281:         }
 6282:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6283:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6284:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6285:         }
 6286:     }
 6287: }
 6288: 
 6289: sub set_userprivs {
 6290:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6291:     my $author=0;
 6292:     my $adv=0;
 6293:     my $rar=0;
 6294:     my %grouproles = ();
 6295:     if (keys(%{$allgroups}) > 0) {
 6296:         my @groupkeys; 
 6297:         foreach my $role (keys(%{$allroles})) {
 6298:             push(@groupkeys,$role);
 6299:         }
 6300:         if (ref($groups_roles) eq 'HASH') {
 6301:             foreach my $key (keys(%{$groups_roles})) {
 6302:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6303:                     push(@groupkeys,$key);
 6304:                 }
 6305:             }
 6306:         }
 6307:         if (@groupkeys > 0) {
 6308:             foreach my $role (@groupkeys) {
 6309:                 my ($trole,$area,$sec,$extendedarea);
 6310:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6311:                     $trole = $1;
 6312:                     $area = $2;
 6313:                     $sec = $3;
 6314:                     $extendedarea = $area.$sec;
 6315:                     if (exists($$allgroups{$area})) {
 6316:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6317:                             my $spec = $trole.'.'.$extendedarea;
 6318:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6319:                                                 $$allgroups{$area}{$group};
 6320:                         }
 6321:                     }
 6322:                 }
 6323:             }
 6324:         }
 6325:     }
 6326:     foreach my $group (keys(%grouproles)) {
 6327:         $$allroles{$group} = $grouproles{$group};
 6328:     }
 6329:     foreach my $role (keys(%{$allroles})) {
 6330:         my %thesepriv;
 6331:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6332:         foreach my $item (split(/:/,$$allroles{$role})) {
 6333:             if ($item ne '') {
 6334:                 my ($privilege,$restrictions)=split(/&/,$item);
 6335:                 if ($restrictions eq '') {
 6336:                     $thesepriv{$privilege}='F';
 6337:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6338:                     $thesepriv{$privilege}.=$restrictions;
 6339:                 }
 6340:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6341:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6342:             }
 6343:         }
 6344:         my $thesestr='';
 6345:         foreach my $priv (sort(keys(%thesepriv))) {
 6346: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6347: 	}
 6348:         $userroles->{'user.priv.'.$role} = $thesestr;
 6349:     }
 6350:     return ($author,$adv,$rar);
 6351: }
 6352: 
 6353: sub role_status {
 6354:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6355:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6356:         my ($one,$two) = split(m{\./},$rolekey,2);
 6357:         (undef,undef,$$role) = split(/\./,$one,3);
 6358:         unless (!defined($$role) || $$role eq '') {
 6359:             $$where = '/'.$two;
 6360:             $$trolecode=$$role.'.'.$$where;
 6361:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6362:             $$tstatus='is';
 6363:             if ($$tstart && $$tstart>$update) {
 6364:                 $$tstatus='future';
 6365:                 if ($$tstart<$now) {
 6366:                     if ($$tstart && $$tstart>$refresh) {
 6367:                         if (($$where ne '') && ($$role ne '')) {
 6368:                             my (%allroles,%allgroups,$group_privs,
 6369:                                 %groups_roles,@rolecodes);
 6370:                             my %userroles = (
 6371:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6372:                             );
 6373:                             @rolecodes = ('cm'); 
 6374:                             my $spec=$$role.'.'.$$where;
 6375:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6376:                             if ($$role =~ /^cr\//) {
 6377:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6378:                                 push(@rolecodes,'cr');
 6379:                             } elsif ($$role eq 'gr') {
 6380:                                 push(@rolecodes,$$role);
 6381:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6382:                                                     $env{'user.name'});
 6383:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6384:                                 (undef,my $group_privs) = split(/\//,$trole);
 6385:                                 $group_privs = &unescape($group_privs);
 6386:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6387:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6388:                                 &get_groups_roles($tdomain,$trest,
 6389:                                                   \%course_roles,\@rolecodes,
 6390:                                                   \%groups_roles);
 6391:                             } else {
 6392:                                 push(@rolecodes,$$role);
 6393:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6394:                             }
 6395:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6396:                                                                    \%groups_roles);
 6397:                             &appenv(\%userroles,\@rolecodes);
 6398:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6399:                         }
 6400:                     }
 6401:                     $$tstatus = 'is';
 6402:                 }
 6403:             }
 6404:             if ($$tend) {
 6405:                 if ($$tend<$update) {
 6406:                     $$tstatus='expired';
 6407:                 } elsif ($$tend<$now) {
 6408:                     $$tstatus='will_not';
 6409:                 }
 6410:             }
 6411:         }
 6412:     }
 6413: }
 6414: 
 6415: sub get_groups_roles {
 6416:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6417:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6418:                   (ref($rolecodes) eq 'ARRAY') && 
 6419:                   (ref($groups_roles) eq 'HASH')); 
 6420:     if (keys(%{$cdom_courseroles}) > 0) {
 6421:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6422:         if ($cdom ne '' && $cnum ne '') {
 6423:             foreach my $key (keys(%{$cdom_courseroles})) {
 6424:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6425:                     my $crsrole = $1;
 6426:                     my $crssec = $2;
 6427:                     if ($crsrole =~ /^cr/) {
 6428:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6429:                             push(@{$rolecodes},'cr');
 6430:                         }
 6431:                     } else {
 6432:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6433:                             push(@{$rolecodes},$crsrole);
 6434:                         }
 6435:                     }
 6436:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6437:                     if ($crssec ne '') {
 6438:                         $rolekey .= "/$crssec";
 6439:                     }
 6440:                     $rolekey .= './';
 6441:                     $groups_roles->{$rolekey} = $rolecodes;
 6442:                 }
 6443:             }
 6444:         }
 6445:     }
 6446:     return;
 6447: }
 6448: 
 6449: sub delete_env_groupprivs {
 6450:     my ($where,$courseroles,$possroles) = @_;
 6451:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6452:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6453:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6454:         %{$courseroles->{$udom}} =
 6455:             &get_my_roles('','','userroles',['active'],
 6456:                           $possroles,[$udom],1);
 6457:     }
 6458:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6459:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6460:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6461:             my $area = '/'.$cdom.'/'.$cnum;
 6462:             my $privkey = "user.priv.$crsrole.$area";
 6463:             if ($crssec ne '') {
 6464:                 $privkey .= '/'.$crssec;
 6465:             }
 6466:             $privkey .= ".$area/$group";
 6467:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6468:         }
 6469:     }
 6470:     return;
 6471: }
 6472: 
 6473: sub check_adhoc_privs {
 6474:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6475:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6476:     if ($sec) {
 6477:         $cckey .= '/'.$sec;
 6478:     } 
 6479:     my $setprivs;
 6480:     if ($env{$cckey}) {
 6481:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6482:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6483:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6484:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6485:             $setprivs = 1;
 6486:         }
 6487:     } else {
 6488:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6489:         $setprivs = 1;
 6490:     }
 6491:     return $setprivs;
 6492: }
 6493: 
 6494: sub set_adhoc_privileges {
 6495: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6496:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6497:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6498:     if ($sec ne '') {
 6499:         $area .= '/'.$sec;
 6500:     }
 6501:     my $spec = $role.'.'.$area;
 6502:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6503:                                   $env{'user.name'},1);
 6504:     my %rolehash = ();
 6505:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6506:         my $rolename = $1;
 6507:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6508:         my %domdef = &get_domain_defaults($dcdom);
 6509:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6510:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6511:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6512:             }
 6513:         }
 6514:     } else {
 6515:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6516:     }
 6517:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6518:     &appenv(\%userroles,[$role,'cm']);
 6519:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6520:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6521:         &appenv( {'request.role'        => $spec,
 6522:                   'request.role.domain' => $dcdom,
 6523:                   'request.course.sec'  => $sec,
 6524:                  }
 6525:                );
 6526:         my $tadv=0;
 6527:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6528:         &appenv({'request.role.adv'    => $tadv});
 6529:     }
 6530: }
 6531: 
 6532: # --------------------------------------------------------------- get interface
 6533: 
 6534: sub get {
 6535:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6536:    my $items='';
 6537:    foreach my $item (@$storearr) {
 6538:        $items.=&escape($item).'&';
 6539:    }
 6540:    $items=~s/\&$//;
 6541:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6542:    if (!$uname) { $uname=$env{'user.name'}; }
 6543:    my $uhome=&homeserver($uname,$udomain);
 6544: 
 6545:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6546:    my @pairs=split(/\&/,$rep);
 6547:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6548:      return @pairs;
 6549:    }
 6550:    my %returnhash=();
 6551:    my $i=0;
 6552:    foreach my $item (@$storearr) {
 6553:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6554:       $i++;
 6555:    }
 6556:    return %returnhash;
 6557: }
 6558: 
 6559: # --------------------------------------------------------------- del interface
 6560: 
 6561: sub del {
 6562:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6563:    my $items='';
 6564:    foreach my $item (@$storearr) {
 6565:        $items.=&escape($item).'&';
 6566:    }
 6567: 
 6568:    $items=~s/\&$//;
 6569:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6570:    if (!$uname) { $uname=$env{'user.name'}; }
 6571:    my $uhome=&homeserver($uname,$udomain);
 6572:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6573: }
 6574: 
 6575: # -------------------------------------------------------------- dump interface
 6576: 
 6577: sub unserialize {
 6578:     my ($rep, $escapedkeys) = @_;
 6579: 
 6580:     return {} if $rep =~ /^error/;
 6581: 
 6582:     my %returnhash=();
 6583: 	foreach my $item (split(/\&/,$rep)) {
 6584: 	    my ($key, $value) = split(/=/, $item, 2);
 6585: 	    $key = unescape($key) unless $escapedkeys;
 6586: 	    next if $key =~ /^error: 2 /;
 6587: 	    $returnhash{$key} = &thaw_unescape($value);
 6588: 	}
 6589:     #return %returnhash;
 6590:     return \%returnhash;
 6591: }        
 6592: 
 6593: # see Lond::dump_with_regexp
 6594: # if $escapedkeys hash keys won't get unescaped.
 6595: sub dump {
 6596:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6597:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6598:     if (!$uname) { $uname=$env{'user.name'}; }
 6599:     my $uhome=&homeserver($uname,$udomain);
 6600: 
 6601:     if ($regexp) {
 6602:         $regexp=&escape($regexp);
 6603:     } else {
 6604:         $regexp='.';
 6605:     }
 6606:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6607:         # user is hosted on this machine
 6608:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6609:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6610:         return %{unserialize($reply, $escapedkeys)};
 6611:     }
 6612:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6613:     my @pairs=split(/\&/,$rep);
 6614:     my %returnhash=();
 6615:     if (!($rep =~ /^error/ )) {
 6616: 	foreach my $item (@pairs) {
 6617: 	    my ($key,$value)=split(/=/,$item,2);
 6618:         $key = unescape($key) unless $escapedkeys;
 6619:         #$key = &unescape($key);
 6620: 	    next if ($key =~ /^error: 2 /);
 6621: 	    $returnhash{$key}=&thaw_unescape($value);
 6622: 	}
 6623:     }
 6624:     return %returnhash;
 6625: }
 6626: 
 6627: 
 6628: # --------------------------------------------------------- dumpstore interface
 6629: 
 6630: sub dumpstore {
 6631:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6632:    # same as dump but keys must be escaped. They may contain colon separated
 6633:    # lists of values that may themself contain colons (e.g. symbs).
 6634:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6635: }
 6636: 
 6637: # -------------------------------------------------------------- keys interface
 6638: 
 6639: sub getkeys {
 6640:    my ($namespace,$udomain,$uname)=@_;
 6641:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6642:    if (!$uname) { $uname=$env{'user.name'}; }
 6643:    my $uhome=&homeserver($uname,$udomain);
 6644:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6645:    my @keyarray=();
 6646:    foreach my $key (split(/\&/,$rep)) {
 6647:       next if ($key =~ /^error: 2 /);
 6648:       push(@keyarray,&unescape($key));
 6649:    }
 6650:    return @keyarray;
 6651: }
 6652: 
 6653: # --------------------------------------------------------------- currentdump
 6654: sub currentdump {
 6655:    my ($courseid,$sdom,$sname)=@_;
 6656:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6657:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6658:    $sname    = $env{'user.name'}         if (! defined($sname));
 6659:    my $uhome = &homeserver($sname,$sdom);
 6660:    my $rep;
 6661: 
 6662:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6663:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6664:                    $courseid)));
 6665:    } else {
 6666:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6667:    }
 6668: 
 6669:    return if ($rep =~ /^(error:|no_such_host)/);
 6670:    #
 6671:    my %returnhash=();
 6672:    #
 6673:    if ($rep eq 'unknown_cmd') {
 6674:        # an old lond will not know currentdump
 6675:        # Do a dump and make it look like a currentdump
 6676:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6677:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6678:        my %hash = @tmp;
 6679:        @tmp=();
 6680:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6681:    } else {
 6682:        my @pairs=split(/\&/,$rep);
 6683:        foreach my $pair (@pairs) {
 6684:            my ($key,$value)=split(/=/,$pair,2);
 6685:            my ($symb,$param) = split(/:/,$key);
 6686:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6687:                                                         &thaw_unescape($value);
 6688:        }
 6689:    }
 6690:    return %returnhash;
 6691: }
 6692: 
 6693: sub convert_dump_to_currentdump{
 6694:     my %hash = %{shift()};
 6695:     my %returnhash;
 6696:     # Code ripped from lond, essentially.  The only difference
 6697:     # here is the unescaping done by lonnet::dump().  Conceivably
 6698:     # we might run in to problems with parameter names =~ /^v\./
 6699:     while (my ($key,$value) = each(%hash)) {
 6700:         my ($v,$symb,$param) = split(/:/,$key);
 6701: 	$symb  = &unescape($symb);
 6702: 	$param = &unescape($param);
 6703:         next if ($v eq 'version' || $symb eq 'keys');
 6704:         next if (exists($returnhash{$symb}) &&
 6705:                  exists($returnhash{$symb}->{$param}) &&
 6706:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6707:         $returnhash{$symb}->{$param}=$value;
 6708:         $returnhash{$symb}->{'v.'.$param}=$v;
 6709:     }
 6710:     #
 6711:     # Remove all of the keys in the hashes which keep track of
 6712:     # the version of the parameter.
 6713:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6714:         # use a foreach because we are going to delete from the hash.
 6715:         foreach my $key (keys(%$param_hash)) {
 6716:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6717:         }
 6718:     }
 6719:     return \%returnhash;
 6720: }
 6721: 
 6722: # ------------------------------------------------------ critical inc interface
 6723: 
 6724: sub cinc {
 6725:     return &inc(@_,'critical');
 6726: }
 6727: 
 6728: # --------------------------------------------------------------- inc interface
 6729: 
 6730: sub inc {
 6731:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6732:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6733:     if (!$uname) { $uname=$env{'user.name'}; }
 6734:     my $uhome=&homeserver($uname,$udomain);
 6735:     my $items='';
 6736:     if (! ref($store)) {
 6737:         # got a single value, so use that instead
 6738:         $items = &escape($store).'=&';
 6739:     } elsif (ref($store) eq 'SCALAR') {
 6740:         $items = &escape($$store).'=&';        
 6741:     } elsif (ref($store) eq 'ARRAY') {
 6742:         $items = join('=&',map {&escape($_);} @{$store});
 6743:     } elsif (ref($store) eq 'HASH') {
 6744:         while (my($key,$value) = each(%{$store})) {
 6745:             $items.= &escape($key).'='.&escape($value).'&';
 6746:         }
 6747:     }
 6748:     $items=~s/\&$//;
 6749:     if ($critical) {
 6750: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6751:     } else {
 6752: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6753:     }
 6754: }
 6755: 
 6756: # --------------------------------------------------------------- put interface
 6757: 
 6758: sub put {
 6759:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6760:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6761:    if (!$uname) { $uname=$env{'user.name'}; }
 6762:    my $uhome=&homeserver($uname,$udomain);
 6763:    my $items='';
 6764:    foreach my $item (keys(%$storehash)) {
 6765:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6766:    }
 6767:    $items=~s/\&$//;
 6768:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6769: }
 6770: 
 6771: # ------------------------------------------------------------ newput interface
 6772: 
 6773: sub newput {
 6774:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6775:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6776:    if (!$uname) { $uname=$env{'user.name'}; }
 6777:    my $uhome=&homeserver($uname,$udomain);
 6778:    my $items='';
 6779:    foreach my $key (keys(%$storehash)) {
 6780:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6781:    }
 6782:    $items=~s/\&$//;
 6783:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6784: }
 6785: 
 6786: # ---------------------------------------------------------  putstore interface
 6787: 
 6788: sub putstore {
 6789:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6790:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6791:    if (!$uname) { $uname=$env{'user.name'}; }
 6792:    my $uhome=&homeserver($uname,$udomain);
 6793:    my $items='';
 6794:    foreach my $key (keys(%$storehash)) {
 6795:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6796:    }
 6797:    $items=~s/\&$//;
 6798:    my $esc_symb=&escape($symb);
 6799:    my $esc_v=&escape($version);
 6800:    my $reply =
 6801:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6802: 	      $uhome);
 6803:    if (($tolog) && ($reply eq 'ok')) {
 6804:        my $namevalue='';
 6805:        foreach my $key (keys(%{$storehash})) {
 6806:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6807:        }
 6808:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6809:                      '&host='.&escape($perlvar{'lonHostID'}).
 6810:                      '&version='.$esc_v.
 6811:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6812:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6813:    }
 6814:    if ($reply eq 'unknown_cmd') {
 6815:        # gfall back to way things use to be done
 6816:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6817: 			    $uname);
 6818:    }
 6819:    return $reply;
 6820: }
 6821: 
 6822: sub old_putstore {
 6823:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6824:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6825:     if (!$uname) { $uname=$env{'user.name'}; }
 6826:     my $uhome=&homeserver($uname,$udomain);
 6827:     my %newstorehash;
 6828:     foreach my $item (keys(%$storehash)) {
 6829: 	my $key = $version.':'.&escape($symb).':'.$item;
 6830: 	$newstorehash{$key} = $storehash->{$item};
 6831:     }
 6832:     my $items='';
 6833:     my %allitems = ();
 6834:     foreach my $item (keys(%newstorehash)) {
 6835: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6836: 	    my $key = $1.':keys:'.$2;
 6837: 	    $allitems{$key} .= $3.':';
 6838: 	}
 6839: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6840:     }
 6841:     foreach my $item (keys(%allitems)) {
 6842: 	$allitems{$item} =~ s/\:$//;
 6843: 	$items.= $item.'='.$allitems{$item}.'&';
 6844:     }
 6845:     $items=~s/\&$//;
 6846:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6847: }
 6848: 
 6849: # ------------------------------------------------------ critical put interface
 6850: 
 6851: sub cput {
 6852:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6853:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6854:    if (!$uname) { $uname=$env{'user.name'}; }
 6855:    my $uhome=&homeserver($uname,$udomain);
 6856:    my $items='';
 6857:    foreach my $item (keys(%$storehash)) {
 6858:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6859:    }
 6860:    $items=~s/\&$//;
 6861:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6862: }
 6863: 
 6864: # -------------------------------------------------------------- eget interface
 6865: 
 6866: sub eget {
 6867:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6868:    my $items='';
 6869:    foreach my $item (@$storearr) {
 6870:        $items.=&escape($item).'&';
 6871:    }
 6872:    $items=~s/\&$//;
 6873:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6874:    if (!$uname) { $uname=$env{'user.name'}; }
 6875:    my $uhome=&homeserver($uname,$udomain);
 6876:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6877:    my @pairs=split(/\&/,$rep);
 6878:    my %returnhash=();
 6879:    my $i=0;
 6880:    foreach my $item (@$storearr) {
 6881:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6882:       $i++;
 6883:    }
 6884:    return %returnhash;
 6885: }
 6886: 
 6887: # ------------------------------------------------------------ tmpput interface
 6888: sub tmpput {
 6889:     my ($storehash,$server,$context)=@_;
 6890:     my $items='';
 6891:     foreach my $item (keys(%$storehash)) {
 6892: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6893:     }
 6894:     $items=~s/\&$//;
 6895:     if (defined($context)) {
 6896:         $items .= ':'.&escape($context);
 6897:     }
 6898:     return &reply("tmpput:$items",$server);
 6899: }
 6900: 
 6901: # ------------------------------------------------------------ tmpget interface
 6902: sub tmpget {
 6903:     my ($token,$server)=@_;
 6904:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6905:     my $rep=&reply("tmpget:$token",$server);
 6906:     my %returnhash;
 6907:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6908:         return %returnhash;
 6909:     }
 6910:     foreach my $item (split(/\&/,$rep)) {
 6911: 	my ($key,$value)=split(/=/,$item);
 6912: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6913:     }
 6914:     return %returnhash;
 6915: }
 6916: 
 6917: # ------------------------------------------------------------ tmpdel interface
 6918: sub tmpdel {
 6919:     my ($token,$server)=@_;
 6920:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6921:     return &reply("tmpdel:$token",$server);
 6922: }
 6923: 
 6924: # ------------------------------------------------------------ get_timebased_id 
 6925: 
 6926: sub get_timebased_id {
 6927:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6928:         $maxtries) = @_;
 6929:     my ($newid,$error,$dellock);
 6930:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6931:         return ('','ok','invalid call to get suffix');
 6932:     }
 6933: 
 6934: # set defaults for any optional args for which values were not supplied
 6935:     if ($who eq '') {
 6936:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6937:     }
 6938:     if (!$locktries) {
 6939:         $locktries = 3;
 6940:     }
 6941:     if (!$maxtries) {
 6942:         $maxtries = 10;
 6943:     }
 6944:     
 6945:     if (($cdom eq '') || ($cnum eq '')) {
 6946:         if ($env{'request.course.id'}) {
 6947:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6948:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6949:         }
 6950:         if (($cdom eq '') || ($cnum eq '')) {
 6951:             return ('','ok','call to get suffix not in course context');
 6952:         }
 6953:     }
 6954: 
 6955: # construct locking item
 6956:     my $lockhash = {
 6957:                       $prefix."\0".'locked_'.$keyid => $who,
 6958:                    };
 6959:     my $tries = 0;
 6960: 
 6961: # attempt to get lock on nohist_$namespace file
 6962:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6963:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6964:         $tries ++;
 6965:         sleep 1;
 6966:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6967:     }
 6968: 
 6969: # attempt to get unique identifier, based on current timestamp
 6970:     if ($gotlock eq 'ok') {
 6971:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6972:         my $id = time;
 6973:         $newid = $id;
 6974:         if ($idtype eq 'addcode') {
 6975:             $newid .= &sixnum_code();
 6976:         }
 6977:         my $idtries = 0;
 6978:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6979:             if ($idtype eq 'concat') {
 6980:                 $newid = $id.$idtries;
 6981:             } elsif ($idtype eq 'addcode') {
 6982:                 $newid = $newid.&sixnum_code();
 6983:             } else {
 6984:                 $newid ++;
 6985:             }
 6986:             $idtries ++;
 6987:         }
 6988:         if (!exists($inuse{$prefix."\0".$newid})) {
 6989:             my %new_item =  (
 6990:                               $prefix."\0".$newid => $who,
 6991:                             );
 6992:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6993:                                                  $cdom,$cnum);
 6994:             if ($putresult ne 'ok') {
 6995:                 undef($newid);
 6996:                 $error = 'error saving new item: '.$putresult;
 6997:             }
 6998:         } else {
 6999:              undef($newid);
 7000:              $error = ('error: no unique suffix available for the new item ');
 7001:         }
 7002: #  remove lock
 7003:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7004:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7005:     } else {
 7006:         $error = "error: could not obtain lockfile\n";
 7007:         $dellock = 'ok';
 7008:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7009:             $dellock = 'nolock';
 7010:         }
 7011:     }
 7012:     return ($newid,$dellock,$error);
 7013: }
 7014: 
 7015: sub sixnum_code {
 7016:     my $code;
 7017:     for (0..6) {
 7018:         $code .= int( rand(9) );
 7019:     }
 7020:     return $code;
 7021: }
 7022: 
 7023: # -------------------------------------------------- portfolio access checking
 7024: 
 7025: sub portfolio_access {
 7026:     my ($requrl,$clientip) = @_;
 7027:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7028:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7029:     if ($result) {
 7030:         my %setters;
 7031:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7032:             my ($startblock,$endblock) =
 7033:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7034:             if ($startblock && $endblock) {
 7035:                 return 'B';
 7036:             }
 7037:         } else {
 7038:             my ($startblock,$endblock) =
 7039:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7040:             if ($startblock && $endblock) {
 7041:                 return 'B';
 7042:             }
 7043:         }
 7044:     }
 7045:     if ($result eq 'ok') {
 7046:        return 'F';
 7047:     } elsif ($result =~ /^[^:]+:guest_/) {
 7048:        return 'A';
 7049:     }
 7050:     return '';
 7051: }
 7052: 
 7053: sub get_portfolio_access {
 7054:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7055: 
 7056:     if (!ref($access_hash)) {
 7057: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7058: 	my %access_controls = &get_access_controls($current_perms,$group,
 7059: 						   $file_name);
 7060: 	$access_hash = $access_controls{$file_name};
 7061:     }
 7062: 
 7063:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7064:     my $now = time;
 7065:     if (ref($access_hash) eq 'HASH') {
 7066:         foreach my $key (keys(%{$access_hash})) {
 7067:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7068:             if ($start > $now) {
 7069:                 next;
 7070:             }
 7071:             if ($end && $end<$now) {
 7072:                 next;
 7073:             }
 7074:             if ($scope eq 'public') {
 7075:                 $public = $key;
 7076:                 last;
 7077:             } elsif ($scope eq 'guest') {
 7078:                 $guest = $key;
 7079:             } elsif ($scope eq 'domains') {
 7080:                 push(@domains,$key);
 7081:             } elsif ($scope eq 'users') {
 7082:                 push(@users,$key);
 7083:             } elsif ($scope eq 'course') {
 7084:                 push(@courses,$key);
 7085:             } elsif ($scope eq 'group') {
 7086:                 push(@groups,$key);
 7087:             } elsif ($scope eq 'ip') {
 7088:                 push(@ips,$key);
 7089:             }
 7090:         }
 7091:         if ($public) {
 7092:             return 'ok';
 7093:         } elsif (@ips > 0) {
 7094:             my $allowed;
 7095:             foreach my $ipkey (@ips) {
 7096:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7097:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7098:                         $allowed = 1;
 7099:                         last; 
 7100:                     }
 7101:                 }
 7102:             }
 7103:             if ($allowed) {
 7104:                 return 'ok';
 7105:             }
 7106:         }
 7107:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7108:             if ($guest) {
 7109:                 return $guest;
 7110:             }
 7111:         } else {
 7112:             if (@domains > 0) {
 7113:                 foreach my $domkey (@domains) {
 7114:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7115:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7116:                             return 'ok';
 7117:                         }
 7118:                     }
 7119:                 }
 7120:             }
 7121:             if (@users > 0) {
 7122:                 foreach my $userkey (@users) {
 7123:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7124:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7125:                             if (ref($item) eq 'HASH') {
 7126:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7127:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7128:                                     return 'ok';
 7129:                                 }
 7130:                             }
 7131:                         }
 7132:                     } 
 7133:                 }
 7134:             }
 7135:             my %roleshash;
 7136:             my @courses_and_groups = @courses;
 7137:             push(@courses_and_groups,@groups); 
 7138:             if (@courses_and_groups > 0) {
 7139:                 my (%allgroups,%allroles); 
 7140:                 my ($start,$end,$role,$sec,$group);
 7141:                 foreach my $envkey (%env) {
 7142:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7143:                         my $cid = $2.'_'.$3; 
 7144:                         if ($1 eq 'gr') {
 7145:                             $group = $4;
 7146:                             $allgroups{$cid}{$group} = $env{$envkey};
 7147:                         } else {
 7148:                             if ($4 eq '') {
 7149:                                 $sec = 'none';
 7150:                             } else {
 7151:                                 $sec = $4;
 7152:                             }
 7153:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7154:                         }
 7155:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7156:                         my $cid = $2.'_'.$3;
 7157:                         if ($4 eq '') {
 7158:                             $sec = 'none';
 7159:                         } else {
 7160:                             $sec = $4;
 7161:                         }
 7162:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7163:                     }
 7164:                 }
 7165:                 if (keys(%allroles) == 0) {
 7166:                     return;
 7167:                 }
 7168:                 foreach my $key (@courses_and_groups) {
 7169:                     my %content = %{$$access_hash{$key}};
 7170:                     my $cnum = $content{'number'};
 7171:                     my $cdom = $content{'domain'};
 7172:                     my $cid = $cdom.'_'.$cnum;
 7173:                     if (!exists($allroles{$cid})) {
 7174:                         next;
 7175:                     }    
 7176:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7177:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7178:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7179:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7180:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7181:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7182:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7183:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7184:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7185:                                         if (grep/^all$/,@sections) {
 7186:                                             return 'ok';
 7187:                                         } else {
 7188:                                             if (grep/^$sec$/,@sections) {
 7189:                                                 return 'ok';
 7190:                                             }
 7191:                                         }
 7192:                                     }
 7193:                                 }
 7194:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7195:                                     if (grep/^none$/,@groups) {
 7196:                                         return 'ok';
 7197:                                     }
 7198:                                 } else {
 7199:                                     if (grep/^all$/,@groups) {
 7200:                                         return 'ok';
 7201:                                     } 
 7202:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7203:                                         if (grep/^$group$/,@groups) {
 7204:                                             return 'ok';
 7205:                                         }
 7206:                                     }
 7207:                                 } 
 7208:                             }
 7209:                         }
 7210:                     }
 7211:                 }
 7212:             }
 7213:             if ($guest) {
 7214:                 return $guest;
 7215:             }
 7216:         }
 7217:     }
 7218:     return;
 7219: }
 7220: 
 7221: sub course_group_datechecker {
 7222:     my ($dates,$now,$status) = @_;
 7223:     my ($start,$end) = split(/\./,$dates);
 7224:     if (!$start && !$end) {
 7225:         return 'ok';
 7226:     }
 7227:     if (grep/^active$/,@{$status}) {
 7228:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7229:             return 'ok';
 7230:         }
 7231:     }
 7232:     if (grep/^previous$/,@{$status}) {
 7233:         if ($end > $now ) {
 7234:             return 'ok';
 7235:         }
 7236:     }
 7237:     if (grep/^future$/,@{$status}) {
 7238:         if ($start > $now) {
 7239:             return 'ok';
 7240:         }
 7241:     }
 7242:     return; 
 7243: }
 7244: 
 7245: sub parse_portfolio_url {
 7246:     my ($url) = @_;
 7247: 
 7248:     my ($type,$udom,$unum,$group,$file_name);
 7249:     
 7250:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7251: 	$type = 1;
 7252:         $udom = $1;
 7253:         $unum = $2;
 7254:         $file_name = $3;
 7255:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7256: 	$type = 2;
 7257:         $udom = $1;
 7258:         $unum = $2;
 7259:         $group = $3;
 7260:         $file_name = $3.'/'.$4;
 7261:     }
 7262:     if (wantarray) {
 7263: 	return ($type,$udom,$unum,$file_name,$group);
 7264:     }
 7265:     return $type;
 7266: }
 7267: 
 7268: sub is_portfolio_url {
 7269:     my ($url) = @_;
 7270:     return scalar(&parse_portfolio_url($url));
 7271: }
 7272: 
 7273: sub is_portfolio_file {
 7274:     my ($file) = @_;
 7275:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7276:         return 1;
 7277:     }
 7278:     return;
 7279: }
 7280: 
 7281: sub usertools_access {
 7282:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7283:     my ($access,%tools);
 7284:     if ($context eq '') {
 7285:         $context = 'tools';
 7286:     }
 7287:     if ($context eq 'requestcourses') {
 7288:         %tools = (
 7289:                       official   => 1,
 7290:                       unofficial => 1,
 7291:                       community  => 1,
 7292:                       textbook   => 1,
 7293:                       placement  => 1,
 7294:                       lti        => 1,
 7295:                  );
 7296:     } elsif ($context eq 'requestauthor') {
 7297:         %tools = (
 7298:                       requestauthor => 1,
 7299:                  );
 7300:     } else {
 7301:         %tools = (
 7302:                       aboutme   => 1,
 7303:                       blog      => 1,
 7304:                       webdav    => 1,
 7305:                       portfolio => 1,
 7306:                  );
 7307:     }
 7308:     return if (!defined($tools{$tool}));
 7309: 
 7310:     if (($udom eq '') || ($uname eq '')) {
 7311:         $udom = $env{'user.domain'};
 7312:         $uname = $env{'user.name'};
 7313:     }
 7314: 
 7315:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7316:         if ($action ne 'reload') {
 7317:             if ($context eq 'requestcourses') {
 7318:                 return $env{'environment.canrequest.'.$tool};
 7319:             } elsif ($context eq 'requestauthor') {
 7320:                 return $env{'environment.canrequest.author'};
 7321:             } else {
 7322:                 return $env{'environment.availabletools.'.$tool};
 7323:             }
 7324:         }
 7325:     }
 7326: 
 7327:     my ($toolstatus,$inststatus,$envkey);
 7328:     if ($context eq 'requestauthor') {
 7329:         $envkey = $context; 
 7330:     } else {
 7331:         $envkey = $context.'.'.$tool;
 7332:     }
 7333: 
 7334:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7335:          ($action ne 'reload')) {
 7336:         $toolstatus = $env{'environment.'.$envkey};
 7337:         $inststatus = $env{'environment.inststatus'};
 7338:     } else {
 7339:         if (ref($userenvref) eq 'HASH') {
 7340:             $toolstatus = $userenvref->{$envkey};
 7341:             $inststatus = $userenvref->{'inststatus'};
 7342:         } else {
 7343:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7344:             $toolstatus = $userenv{$envkey};
 7345:             $inststatus = $userenv{'inststatus'};
 7346:         }
 7347:     }
 7348: 
 7349:     if ($toolstatus ne '') {
 7350:         if ($toolstatus) {
 7351:             $access = 1;
 7352:         } else {
 7353:             $access = 0;
 7354:         }
 7355:         return $access;
 7356:     }
 7357: 
 7358:     my ($is_adv,%domdef);
 7359:     if (ref($is_advref) eq 'HASH') {
 7360:         $is_adv = $is_advref->{'is_adv'};
 7361:     } else {
 7362:         $is_adv = &is_advanced_user($udom,$uname);
 7363:     }
 7364:     if (ref($domdefref) eq 'HASH') {
 7365:         %domdef = %{$domdefref};
 7366:     } else {
 7367:         %domdef = &get_domain_defaults($udom);
 7368:     }
 7369:     if (ref($domdef{$tool}) eq 'HASH') {
 7370:         if ($is_adv) {
 7371:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7372:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7373:                     $access = 1;
 7374:                 } else {
 7375:                     $access = 0;
 7376:                 }
 7377:                 return $access;
 7378:             }
 7379:         }
 7380:         if ($inststatus ne '') {
 7381:             my ($hasaccess,$hasnoaccess);
 7382:             foreach my $affiliation (split(/:/,$inststatus)) {
 7383:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7384:                     if ($domdef{$tool}{$affiliation}) {
 7385:                         $hasaccess = 1;
 7386:                     } else {
 7387:                         $hasnoaccess = 1;
 7388:                     }
 7389:                 }
 7390:             }
 7391:             if ($hasaccess || $hasnoaccess) {
 7392:                 if ($hasaccess) {
 7393:                     $access = 1;
 7394:                 } elsif ($hasnoaccess) {
 7395:                     $access = 0; 
 7396:                 }
 7397:                 return $access;
 7398:             }
 7399:         } else {
 7400:             if ($domdef{$tool}{'default'} ne '') {
 7401:                 if ($domdef{$tool}{'default'}) {
 7402:                     $access = 1;
 7403:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7404:                     $access = 0;
 7405:                 }
 7406:                 return $access;
 7407:             }
 7408:         }
 7409:     } else {
 7410:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7411:             $access = 1;
 7412:         } else {
 7413:             $access = 0;
 7414:         }
 7415:         return $access;
 7416:     }
 7417: }
 7418: 
 7419: sub is_course_owner {
 7420:     my ($cdom,$cnum,$udom,$uname) = @_;
 7421:     if (($udom eq '') || ($uname eq '')) {
 7422:         $udom = $env{'user.domain'};
 7423:         $uname = $env{'user.name'};
 7424:     }
 7425:     unless (($udom eq '') || ($uname eq '')) {
 7426:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7427:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7428:                 return 1;
 7429:             } else {
 7430:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7431:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7432:                     return 1;
 7433:                 }
 7434:             }
 7435:         }
 7436:     }
 7437:     return;
 7438: }
 7439: 
 7440: sub is_advanced_user {
 7441:     my ($udom,$uname) = @_;
 7442:     if ($udom ne '' && $uname ne '') {
 7443:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7444:             if (wantarray) {
 7445:                 return ($env{'user.adv'},$env{'user.author'});
 7446:             } else {
 7447:                 return $env{'user.adv'};
 7448:             }
 7449:         }
 7450:     }
 7451:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7452:     my %allroles;
 7453:     my ($is_adv,$is_author);
 7454:     foreach my $role (keys(%roleshash)) {
 7455:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7456:         my $area = '/'.$tdomain.'/'.$trest;
 7457:         if ($sec ne '') {
 7458:             $area .= '/'.$sec;
 7459:         }
 7460:         if (($area ne '') && ($trole ne '')) {
 7461:             my $spec=$trole.'.'.$area;
 7462:             if ($trole =~ /^cr\//) {
 7463:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7464:             } elsif ($trole ne 'gr') {
 7465:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7466:             }
 7467:             if ($trole eq 'au') {
 7468:                 $is_author = 1;
 7469:             }
 7470:         }
 7471:     }
 7472:     foreach my $role (keys(%allroles)) {
 7473:         last if ($is_adv);
 7474:         foreach my $item (split(/:/,$allroles{$role})) {
 7475:             if ($item ne '') {
 7476:                 my ($privilege,$restrictions)=split(/&/,$item);
 7477:                 if ($privilege eq 'adv') {
 7478:                     $is_adv = 1;
 7479:                     last;
 7480:                 }
 7481:             }
 7482:         }
 7483:     }
 7484:     if (wantarray) {
 7485:         return ($is_adv,$is_author);
 7486:     }
 7487:     return $is_adv;
 7488: }
 7489: 
 7490: sub check_can_request {
 7491:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7492:     my $canreq = 0;
 7493:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7494:         $uname = $env{'user.name'};
 7495:         $udom = $env{'user.domain'};
 7496:     }
 7497:     my ($types,$typename) = &Apache::loncommon::course_types();
 7498:     my @options = ('approval','validate','autolimit');
 7499:     my $optregex = join('|',@options);
 7500:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7501:         foreach my $type (@{$types}) {
 7502:             if (&usertools_access($uname,$udom,$type,undef,
 7503:                                   'requestcourses')) {
 7504:                 $canreq ++;
 7505:                 if (ref($request_domains) eq 'HASH') {
 7506:                     push(@{$request_domains->{$type}},$udom);
 7507:                 }
 7508:                 if ($dom eq $udom) {
 7509:                     $can_request->{$type} = 1;
 7510:                 }
 7511:             }
 7512:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7513:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7514:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7515:                 if (@curr > 0) {
 7516:                     foreach my $item (@curr) {
 7517:                         if (ref($request_domains) eq 'HASH') {
 7518:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7519:                             if ($otherdom ne '') {
 7520:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7521:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7522:                                         push(@{$request_domains->{$type}},$otherdom);
 7523:                                     }
 7524:                                 } else {
 7525:                                     push(@{$request_domains->{$type}},$otherdom);
 7526:                                 }
 7527:                             }
 7528:                         }
 7529:                     }
 7530:                     unless ($dom eq $env{'user.domain'}) {
 7531:                         $canreq ++;
 7532:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7533:                             $can_request->{$type} = 1;
 7534:                         }
 7535:                     }
 7536:                 }
 7537:             }
 7538:         }
 7539:     }
 7540:     return $canreq;
 7541: }
 7542: 
 7543: # ---------------------------------------------- Custom access rule evaluation
 7544: 
 7545: sub customaccess {
 7546:     my ($priv,$uri)=@_;
 7547:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7548:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7549:     $udom = &LONCAPA::clean_domain($udom);
 7550:     $ucrs = &LONCAPA::clean_username($ucrs);
 7551:     my $access=0;
 7552:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7553: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7554: 	if ($type eq 'user') {
 7555: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7556: 		my ($tdom,$tuname)=split(m{/},$scope);
 7557: 		if ($tdom) {
 7558: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7559: 		}
 7560: 		if ($tuname) {
 7561: 		    if ($tuname ne $env{'user.name'}) { next; }
 7562: 		}
 7563: 		$access=($effect eq 'allow');
 7564: 		last;
 7565: 	    }
 7566: 	} else {
 7567: 	    if ($role) {
 7568: 		if ($role ne $urole) { next; }
 7569: 	    }
 7570: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7571: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7572: 		if ($tdom) {
 7573: 		    if ($tdom ne $udom) { next; }
 7574: 		}
 7575: 		if ($tcrs) {
 7576: 		    if ($tcrs ne $ucrs) { next; }
 7577: 		}
 7578: 		if ($tsec) {
 7579: 		    if ($tsec ne $usec) { next; }
 7580: 		}
 7581: 		$access=($effect eq 'allow');
 7582: 		last;
 7583: 	    }
 7584: 	    if ($realm eq '' && $role eq '') {
 7585: 		$access=($effect eq 'allow');
 7586: 	    }
 7587: 	}
 7588:     }
 7589:     return $access;
 7590: }
 7591: 
 7592: # ------------------------------------------------- Check for a user privilege
 7593: 
 7594: sub allowed {
 7595:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7596:     my $ver_orguri=$uri;
 7597:     $uri=&deversion($uri);
 7598:     my $orguri=$uri;
 7599:     $uri=&declutter($uri);
 7600: 
 7601:     if ($priv eq 'evb') {
 7602: # Evade communication block restrictions for specified role in a course
 7603:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7604:             return $1;
 7605:         } else {
 7606:             return;
 7607:         }
 7608:     }
 7609: 
 7610:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7611: # Free bre access to adm and meta resources
 7612:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7613: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7614: 	&& ($priv eq 'bre')) {
 7615: 	return 'F';
 7616:     }
 7617: 
 7618: # Free bre access to user's own portfolio contents
 7619:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7620:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7621: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7622:         my %setters;
 7623:         my ($startblock,$endblock) = 
 7624:             &Apache::loncommon::blockcheck(\%setters,'port');
 7625:         if ($startblock && $endblock) {
 7626:             return 'B';
 7627:         } else {
 7628:             return 'F';
 7629:         }
 7630:     }
 7631: 
 7632: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7633:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7634:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7635:         if (exists($env{'request.course.id'})) {
 7636:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7637:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7638:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7639:                 my $courseprivid=$env{'request.course.id'};
 7640:                 $courseprivid=~s/\_/\//;
 7641:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7642:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7643:                     return $1; 
 7644:                 } else {
 7645:                     if ($env{'request.course.sec'}) {
 7646:                         $courseprivid.='/'.$env{'request.course.sec'};
 7647:                     }
 7648:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7649:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7650:                         return $2;
 7651:                     }
 7652:                 }
 7653:             }
 7654:         }
 7655:     }
 7656: 
 7657: # Free bre to public access
 7658: 
 7659:     if ($priv eq 'bre') {
 7660:         my $copyright;
 7661:         unless ($uri =~ /ext\.tool/) {
 7662:             $copyright=&metadata($uri,'copyright');
 7663:         }
 7664: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7665:            return 'F'; 
 7666:         }
 7667:         if ($copyright eq 'priv') {
 7668:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7669: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7670: 		return '';
 7671:             }
 7672:         }
 7673:         if ($copyright eq 'domain') {
 7674:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7675: 	    unless (($env{'user.domain'} eq $1) ||
 7676:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7677: 		return '';
 7678:             }
 7679:         }
 7680:         if ($env{'request.role'}=~ /li\.\//) {
 7681:             # Library role, so allow browsing of resources in this domain.
 7682:             return 'F';
 7683:         }
 7684:         if ($copyright eq 'custom') {
 7685: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7686:         }
 7687:     }
 7688:     # Domain coordinator is trying to create a course
 7689:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7690:         # uri is the requested domain in this case.
 7691:         # comparison to 'request.role.domain' shows if the user has selected
 7692:         # a role of dc for the domain in question.
 7693:         return 'F' if ($uri eq $env{'request.role.domain'});
 7694:     }
 7695: 
 7696:     my $thisallowed='';
 7697:     my $statecond=0;
 7698:     my $courseprivid='';
 7699: 
 7700:     my $ownaccess;
 7701:     # Community Coordinator or Assistant Co-author browsing resource space.
 7702:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7703:         if ($uri eq '') {
 7704:             $ownaccess = 1;
 7705:         } else {
 7706:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7707:                 my $udom = $env{'user.domain'};
 7708:                 my $uname = $env{'user.name'};
 7709:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7710:                     $ownaccess = 1;
 7711:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7712:                     unless ($uri =~ m{\.\./}) {
 7713:                         $ownaccess = 1;
 7714:                     }
 7715:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7716:                     my $now = time;
 7717:                     if ($uri =~ m{^([^/]+)/?$}) {
 7718:                         my $adom = $1;
 7719:                         foreach my $key (keys(%env)) {
 7720:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7721:                                 my ($start,$end) = split('.',$env{$key});
 7722:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7723:                                     $ownaccess = 1;
 7724:                                     last;
 7725:                                 }
 7726:                             }
 7727:                         }
 7728:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7729:                         my $adom = $1;
 7730:                         my $aname = $2;
 7731:                         foreach my $role ('ca','aa') { 
 7732:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7733:                                 my ($start,$end) =
 7734:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7735:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7736:                                     $ownaccess = 1;
 7737:                                     last;
 7738:                                 }
 7739:                             }
 7740:                         }
 7741:                     }
 7742:                 }
 7743:             }
 7744:         }
 7745:     }
 7746: 
 7747: # Course
 7748: 
 7749:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7750:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7751:             $thisallowed.=$1;
 7752:         }
 7753:     }
 7754: 
 7755: # Domain
 7756: 
 7757:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7758:        =~/\Q$priv\E\&([^\:]*)/) {
 7759:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7760:             $thisallowed.=$1;
 7761:         }
 7762:     }
 7763: 
 7764: # User who is not author or co-author might still be able to edit
 7765: # resource of an author in the domain (e.g., if Domain Coordinator).
 7766:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7767:         (&allowed('mdc',$env{'request.course.id'}))) {
 7768:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7769:             $thisallowed.=$1;
 7770:         }
 7771:     }
 7772: 
 7773: # Course: uri itself is a course
 7774:     my $courseuri=$uri;
 7775:     $courseuri=~s/\_(\d)/\/$1/;
 7776:     $courseuri=~s/^([^\/])/\/$1/;
 7777: 
 7778:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7779:        =~/\Q$priv\E\&([^\:]*)/) {
 7780:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7781:             $thisallowed.=$1;
 7782:         }
 7783:     }
 7784: 
 7785: # URI is an uploaded document for this course, default permissions don't matter
 7786: # not allowing 'edit' access (editupload) to uploaded course docs
 7787:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7788: 	$thisallowed='';
 7789:         my ($match)=&is_on_map($uri);
 7790:         if ($match) {
 7791:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7792:                   =~/\Q$priv\E\&([^\:]*)/) {
 7793:                 my $value = $1;
 7794:                 if ($noblockcheck) {
 7795:                     $thisallowed.=$value;
 7796:                 } else {
 7797:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7798:                     if (@blockers > 0) {
 7799:                         $thisallowed = 'B';
 7800:                     } else {
 7801:                         $thisallowed.=$value;
 7802:                     }
 7803:                 }
 7804:             }
 7805:         } else {
 7806:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7807:             if ($refuri) {
 7808:                 if ($refuri =~ m|^/adm/|) {
 7809:                     $thisallowed='F';
 7810:                 } else {
 7811:                     $refuri=&declutter($refuri);
 7812:                     my ($match) = &is_on_map($refuri);
 7813:                     if ($match) {
 7814:                         if ($noblockcheck) {
 7815:                             $thisallowed='F';
 7816:                         } else {
 7817:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7818:                             if (@blockers > 0) {
 7819:                                 $thisallowed = 'B';
 7820:                             } else {
 7821:                                 $thisallowed='F';
 7822:                             }
 7823:                         }
 7824:                     }
 7825:                 }
 7826:             }
 7827:         }
 7828:     }
 7829: 
 7830:     if ($priv eq 'bre'
 7831: 	&& $thisallowed ne 'F' 
 7832: 	&& $thisallowed ne '2'
 7833: 	&& &is_portfolio_url($uri)) {
 7834: 	$thisallowed = &portfolio_access($uri,$clientip);
 7835:     }
 7836: 
 7837: # Full access at system, domain or course-wide level? Exit.
 7838:     if ($thisallowed=~/F/) {
 7839: 	return 'F';
 7840:     }
 7841: 
 7842: # If this is generating or modifying users, exit with special codes
 7843: 
 7844:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7845: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7846: 	    my ($audom,$auname)=split('/',$uri);
 7847: # no author name given, so this just checks on the general right to make a co-author in this domain
 7848: 	    unless ($auname) { return $thisallowed; }
 7849: # an author name is given, so we are about to actually make a co-author for a certain account
 7850: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7851: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7852: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7853: 	}
 7854: 	return $thisallowed;
 7855:     }
 7856: #
 7857: # Gathered so far: system, domain and course wide privileges
 7858: #
 7859: # Course: See if uri or referer is an individual resource that is part of 
 7860: # the course
 7861: 
 7862:     if ($env{'request.course.id'}) {
 7863: 
 7864:        $courseprivid=$env{'request.course.id'};
 7865:        if ($env{'request.course.sec'}) {
 7866:           $courseprivid.='/'.$env{'request.course.sec'};
 7867:        }
 7868:        $courseprivid=~s/\_/\//;
 7869:        my $checkreferer=1;
 7870:        my ($match,$cond)=&is_on_map($uri);
 7871:        if ($match) {
 7872:            $statecond=$cond;
 7873:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7874:                =~/\Q$priv\E\&([^\:]*)/) {
 7875:                my $value = $1;
 7876:                if ($priv eq 'bre') {
 7877:                    if ($noblockcheck) {
 7878:                        $thisallowed.=$value;
 7879:                    } else {
 7880:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7881:                        if (@blockers > 0) {
 7882:                            $thisallowed = 'B';
 7883:                        } else {
 7884:                            $thisallowed.=$value;
 7885:                        }
 7886:                    }
 7887:                } else {
 7888:                    $thisallowed.=$value;
 7889:                }
 7890:                $checkreferer=0;
 7891:            }
 7892:        }
 7893:        
 7894:        if ($checkreferer) {
 7895: 	  my $refuri=$env{'httpref.'.$orguri};
 7896:             unless ($refuri) {
 7897:                 foreach my $key (keys(%env)) {
 7898: 		    if ($key=~/^httpref\..*\*/) {
 7899: 			my $pattern=$key;
 7900:                         $pattern=~s/^httpref\.\/res\///;
 7901:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7902:                         $pattern=~s/\//\\\//g;
 7903:                         if ($orguri=~/$pattern/) {
 7904: 			    $refuri=$env{$key};
 7905:                         }
 7906:                     }
 7907:                 }
 7908:             }
 7909: 
 7910:          if ($refuri) { 
 7911: 	  $refuri=&declutter($refuri);
 7912:           my ($match,$cond)=&is_on_map($refuri);
 7913:             if ($match) {
 7914:               my $refstatecond=$cond;
 7915:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7916:                   =~/\Q$priv\E\&([^\:]*)/) {
 7917:                   my $value = $1;
 7918:                   if ($priv eq 'bre') {
 7919:                       if ($noblockcheck) {
 7920:                           $thisallowed.=$value;
 7921:                       } else {
 7922:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7923:                           if (@blockers > 0) {
 7924:                               $thisallowed = 'B';
 7925:                           } else {
 7926:                               $thisallowed.=$value;
 7927:                           }
 7928:                       }
 7929:                   } else {
 7930:                       $thisallowed.=$value;
 7931:                   }
 7932:                   $uri=$refuri;
 7933:                   $statecond=$refstatecond;
 7934:               }
 7935:           }
 7936:         }
 7937:        }
 7938:    }
 7939: 
 7940: #
 7941: # Gathered now: all privileges that could apply, and condition number
 7942: # 
 7943: #
 7944: # Full or no access?
 7945: #
 7946: 
 7947:     if ($thisallowed=~/F/) {
 7948: 	return 'F';
 7949:     }
 7950: 
 7951:     unless ($thisallowed) {
 7952:         return '';
 7953:     }
 7954: 
 7955: # Restrictions exist, deal with them
 7956: #
 7957: #   C:according to course preferences
 7958: #   R:according to resource settings
 7959: #   L:unless locked
 7960: #   X:according to user session state
 7961: #
 7962: 
 7963: # Possibly locked functionality, check all courses
 7964: # Locks might take effect only after 10 minutes cache expiration for other
 7965: # courses, and 2 minutes for current course
 7966: 
 7967:     my $envkey;
 7968:     if ($thisallowed=~/L/) {
 7969:         foreach $envkey (keys(%env)) {
 7970:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7971:                my $courseid=$2;
 7972:                my $roleid=$1.'.'.$2;
 7973:                $courseid=~s/^\///;
 7974:                my $expiretime=600;
 7975:                if ($env{'request.role'} eq $roleid) {
 7976: 		  $expiretime=120;
 7977:                }
 7978: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7979:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7980:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7981: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7982:                }
 7983:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7984:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7985: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7986:                        &log($env{'user.domain'},$env{'user.name'},
 7987:                             $env{'user.home'},
 7988:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7989:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7990:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7991: 		       return '';
 7992:                    }
 7993:                }
 7994:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7995:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7996: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7997:                        &log($env{'user.domain'},$env{'user.name'},
 7998:                             $env{'user.home'},
 7999:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8000:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8001:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8002: 		       return '';
 8003:                    }
 8004:                }
 8005: 	   }
 8006:        }
 8007:     }
 8008:    
 8009: #
 8010: # Rest of the restrictions depend on selected course
 8011: #
 8012: 
 8013:     unless ($env{'request.course.id'}) {
 8014: 	if ($thisallowed eq 'A') {
 8015: 	    return 'A';
 8016:         } elsif ($thisallowed eq 'B') {
 8017:             return 'B';
 8018: 	} else {
 8019: 	    return '1';
 8020: 	}
 8021:     }
 8022: 
 8023: #
 8024: # Now user is definitely in a course
 8025: #
 8026: 
 8027: 
 8028: # Course preferences
 8029: 
 8030:    if ($thisallowed=~/C/) {
 8031:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8032:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8033:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8034: 	   =~/\Q$rolecode\E/) {
 8035: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8036: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8037: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8038: 			$env{'request.course.id'});
 8039: 	   }
 8040:            return '';
 8041:        }
 8042: 
 8043:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8044: 	   =~/\Q$unamedom\E/) {
 8045: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8046: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8047: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8048: 			$env{'request.course.id'});
 8049: 	   }
 8050:            return '';
 8051:        }
 8052:    }
 8053: 
 8054: # Resource preferences
 8055: 
 8056:    if ($thisallowed=~/R/) {
 8057:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8058:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8059: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8060: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8061: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8062: 	   }
 8063: 	   return '';
 8064:        }
 8065:    }
 8066: 
 8067: # Restricted by state or randomout?
 8068: 
 8069:    if ($thisallowed=~/X/) {
 8070:       if ($env{'acc.randomout'}) {
 8071: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8072:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8073:             return ''; 
 8074:          }
 8075:       }
 8076:       if (&condval($statecond)) {
 8077: 	 return '2';
 8078:       } else {
 8079:          return '';
 8080:       }
 8081:    }
 8082: 
 8083:     if ($thisallowed eq 'A') {
 8084: 	return 'A';
 8085:     } elsif ($thisallowed eq 'B') {
 8086:         return 'B';
 8087:     }
 8088:    return 'F';
 8089: }
 8090: 
 8091: # ------------------------------------------- Check construction space access
 8092: 
 8093: sub constructaccess {
 8094:     my ($url,$setpriv)=@_;
 8095: 
 8096: # We do not allow editing of previous versions of files
 8097:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8098: 
 8099: # Get username and domain from URL
 8100:     my ($ownername,$ownerdomain,$ownerhome);
 8101: 
 8102:     ($ownerdomain,$ownername) =
 8103:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8104: 
 8105: # The URL does not really point to any authorspace, forget it
 8106:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8107: 
 8108: # Now we need to see if the user has access to the authorspace of
 8109: # $ownername at $ownerdomain
 8110: 
 8111:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8112: # Real author for this?
 8113:        $ownerhome = $env{'user.home'};
 8114:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8115:           return ($ownername,$ownerdomain,$ownerhome);
 8116:        }
 8117:     } else {
 8118: # Co-author for this?
 8119:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8120:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8121:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8122:             return ($ownername,$ownerdomain,$ownerhome);
 8123:         }
 8124:         if ($env{'request.course.id'}) {
 8125:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8126:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8127:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8128:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8129:                     return ($ownername,$ownerdomain,$ownerhome);
 8130:                 }
 8131:             }
 8132:         }
 8133:     }
 8134: 
 8135: # We don't have any access right now. If we are not possibly going to do anything about this,
 8136: # we might as well leave
 8137:    unless ($setpriv) { return ''; }
 8138: 
 8139: # Backdoor access?
 8140:     my $allowed=&allowed('eco',$ownerdomain);
 8141: # Nope
 8142:     unless ($allowed) { return ''; }
 8143: # Looks like we may have access, but could be locked by the owner of the construction space
 8144:     if ($allowed eq 'U') {
 8145:         my %blocked=&get('environment',['domcoord.author'],
 8146:                          $ownerdomain,$ownername);
 8147: # Is blocked by owner
 8148:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8149:     }
 8150:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8151: # Grant temporary access
 8152:         my $then=$env{'user.login.time'};
 8153:         my $update=$env{'user.update.time'};
 8154:         if (!$update) { $update = $then; }
 8155:         my $refresh=$env{'user.refresh.time'};
 8156:         if (!$refresh) { $refresh = $update; }
 8157:         my $now = time;
 8158:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8159:                            $now,'ca','constructaccess');
 8160:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8161:         return($ownername,$ownerdomain,$ownerhome);
 8162:     }
 8163: # No business here
 8164:     return '';
 8165: }
 8166: 
 8167: # ----------------------------------------------------------- Content Blocking
 8168: 
 8169: {
 8170: # Caches for faster Course Contents display where content blocking
 8171: # is in operation (i.e., interval param set) for timed quiz.
 8172: #
 8173: # User for whom data are being temporarily cached.
 8174: my $cacheduser='';
 8175: # Cached blockers for this user (a hash of blocking items). 
 8176: my %cachedblockers=();
 8177: # When the data were last cached.
 8178: my $cachedlast='';
 8179: 
 8180: sub load_all_blockers {
 8181:     my ($uname,$udom,$blocks)=@_;
 8182:     if (($uname ne '') && ($udom ne '')) { 
 8183:         if (($cacheduser eq $uname.':'.$udom) &&
 8184:             (abs($cachedlast-time)<5)) {
 8185:             return;
 8186:         }
 8187:     }
 8188:     $cachedlast=time;
 8189:     $cacheduser=$uname.':'.$udom;
 8190:     %cachedblockers = &get_commblock_resources($blocks);
 8191: }
 8192: 
 8193: sub get_comm_blocks {
 8194:     my ($cdom,$cnum) = @_;
 8195:     if ($cdom eq '' || $cnum eq '') {
 8196:         return unless ($env{'request.course.id'});
 8197:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8198:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8199:     }
 8200:     my %commblocks;
 8201:     my $hashid=$cdom.'_'.$cnum;
 8202:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8203:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8204:         %commblocks = %{$blocksref};
 8205:     } else {
 8206:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8207:         my $cachetime = 600;
 8208:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8209:     }
 8210:     return %commblocks;
 8211: }
 8212: 
 8213: sub get_commblock_resources {
 8214:     my ($blocks) = @_;
 8215:     my %blockers = ();
 8216:     return %blockers unless ($env{'request.course.id'});
 8217:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8218:     my %commblocks;
 8219:     if (ref($blocks) eq 'HASH') {
 8220:         %commblocks = %{$blocks};
 8221:     } else {
 8222:         %commblocks = &get_comm_blocks();
 8223:     }
 8224:     return %blockers unless (keys(%commblocks) > 0); 
 8225:     my $navmap = Apache::lonnavmaps::navmap->new();
 8226:     return %blockers unless (ref($navmap));
 8227:     my $now = time;
 8228:     foreach my $block (keys(%commblocks)) {
 8229:         if ($block =~ /^(\d+)____(\d+)$/) {
 8230:             my ($start,$end) = ($1,$2);
 8231:             if ($start <= $now && $end >= $now) {
 8232:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8233:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8234:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8235:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8236:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8237:                             }
 8238:                         }
 8239:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8240:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8241:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8242:                             }
 8243:                         }
 8244:                     }
 8245:                 }
 8246:             }
 8247:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8248:             my $item = $1;
 8249:             my @to_test;
 8250:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8251:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8252:                     my @interval;
 8253:                     my $type = 'map';
 8254:                     if ($item eq 'course') {
 8255:                         $type = 'course';
 8256:                         @interval=&EXT("resource.0.interval");
 8257:                     } else {
 8258:                         if ($item =~ /___\d+___/) {
 8259:                             $type = 'resource';
 8260:                             @interval=&EXT("resource.0.interval",$item);
 8261:                             if (ref($navmap)) {                        
 8262:                                 my $res = $navmap->getBySymb($item); 
 8263:                                 push(@to_test,$res);
 8264:                             }
 8265:                         } else {
 8266:                             my $mapsymb = &symbread($item,1);
 8267:                             if ($mapsymb) {
 8268:                                 if (ref($navmap)) {
 8269:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8270:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8271:                                     foreach my $res (@to_test) {
 8272:                                         my $symb = $res->symb();
 8273:                                         next if ($symb eq $mapsymb);
 8274:                                         if ($symb ne '') {
 8275:                                             @interval=&EXT("resource.0.interval",$symb);
 8276:                                             if ($interval[1] eq 'map') {
 8277:                                                 last;
 8278:                                             }
 8279:                                         }
 8280:                                     }
 8281:                                 }
 8282:                             }
 8283:                         }
 8284:                     }
 8285:                     if ($interval[0] =~ /^(\d+)/) {
 8286:                         my $timelimit = $1; 
 8287:                         my $first_access;
 8288:                         if ($type eq 'resource') {
 8289:                             $first_access=&get_first_access($interval[1],$item);
 8290:                         } elsif ($type eq 'map') {
 8291:                             $first_access=&get_first_access($interval[1],undef,$item);
 8292:                         } else {
 8293:                             $first_access=&get_first_access($interval[1]);
 8294:                         }
 8295:                         if ($first_access) {
 8296:                             my $timesup = $first_access+$timelimit;
 8297:                             if ($timesup > $now) {
 8298:                                 my $activeblock;
 8299:                                 foreach my $res (@to_test) {
 8300:                                     if ($res->answerable()) {
 8301:                                         $activeblock = 1;
 8302:                                         last;
 8303:                                     }
 8304:                                 }
 8305:                                 if ($activeblock) {
 8306:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8307:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8308:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8309:                                          }
 8310:                                     }
 8311:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8312:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8313:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8314:                                         }
 8315:                                     }
 8316:                                 }
 8317:                             }
 8318:                         }
 8319:                     }
 8320:                 }
 8321:             }
 8322:         }
 8323:     }
 8324:     return %blockers;
 8325: }
 8326: 
 8327: sub has_comm_blocking {
 8328:     my ($priv,$symb,$uri,$blocks) = @_;
 8329:     my @blockers;
 8330:     return unless ($env{'request.course.id'});
 8331:     return unless ($priv eq 'bre');
 8332:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8333:     return if ($env{'request.state'} eq 'construct');
 8334:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8335:     return unless (keys(%cachedblockers) > 0);
 8336:     my (%possibles,@symbs);
 8337:     if (!$symb) {
 8338:         $symb = &symbread($uri,1,1,1,\%possibles);
 8339:     }
 8340:     if ($symb) {
 8341:         @symbs = ($symb);
 8342:     } elsif (keys(%possibles)) { 
 8343:         @symbs = keys(%possibles);
 8344:     }
 8345:     my $noblock;
 8346:     foreach my $symb (@symbs) {
 8347:         last if ($noblock);
 8348:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8349:         foreach my $block (keys(%cachedblockers)) {
 8350:             if ($block =~ /^firstaccess____(.+)$/) {
 8351:                 my $item = $1;
 8352:                 if (($item eq $map) || ($item eq $symb)) {
 8353:                     $noblock = 1;
 8354:                     last;
 8355:                 }
 8356:             }
 8357:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8358:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8359:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8360:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8361:                             push(@blockers,$block);
 8362:                         }
 8363:                     }
 8364:                 }
 8365:             }
 8366:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8367:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8368:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8369:                         push(@blockers,$block);
 8370:                     }
 8371:                 }
 8372:             }
 8373:         }
 8374:     }
 8375:     return if ($noblock);
 8376:     return @blockers;
 8377: }
 8378: }
 8379: 
 8380: # -------------------------------- Deversion and split uri into path an filename   
 8381: 
 8382: #
 8383: #   Removes the version from a URI and
 8384: #   splits it in to its filename and path to the filename.
 8385: #   Seems like File::Basename could have done this more clearly.
 8386: #   Parameters:
 8387: #      $uri   - input URI
 8388: #   Returns:
 8389: #     Two element list consisting of 
 8390: #     $pathname  - the URI up to and excluding the trailing /
 8391: #     $filename  - The part of the URI following the last /
 8392: #  NOTE:
 8393: #    Another realization of this is simply:
 8394: #    use File::Basename;
 8395: #    ...
 8396: #    $uri = shift;
 8397: #    $filename = basename($uri);
 8398: #    $path     = dirname($uri);
 8399: #    return ($filename, $path);
 8400: #
 8401: #     The implementation below is probably faster however.
 8402: #
 8403: sub split_uri_for_cond {
 8404:     my $uri=&deversion(&declutter(shift));
 8405:     my @uriparts=split(/\//,$uri);
 8406:     my $filename=pop(@uriparts);
 8407:     my $pathname=join('/',@uriparts);
 8408:     return ($pathname,$filename);
 8409: }
 8410: # --------------------------------------------------- Is a resource on the map?
 8411: 
 8412: sub is_on_map {
 8413:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8414:     #Trying to find the conditional for the file
 8415:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8416: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8417:     if ($match) {
 8418: 	return (1,$1);
 8419:     } else {
 8420: 	return (0,0);
 8421:     }
 8422: }
 8423: 
 8424: # --------------------------------------------------------- Get symb from alias
 8425: 
 8426: sub get_symb_from_alias {
 8427:     my $symb=shift;
 8428:     my ($map,$resid,$url)=&decode_symb($symb);
 8429: # Already is a symb
 8430:     if ($url) { return $symb; }
 8431: # Must be an alias
 8432:     my $aliassymb='';
 8433:     my %bighash;
 8434:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8435:                             &GDBM_READER(),0640)) {
 8436:         my $rid=$bighash{'mapalias_'.$symb};
 8437: 	if ($rid) {
 8438: 	    my ($mapid,$resid)=split(/\./,$rid);
 8439: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8440: 				    $resid,$bighash{'src_'.$rid});
 8441: 	}
 8442:         untie %bighash;
 8443:     }
 8444:     return $aliassymb;
 8445: }
 8446: 
 8447: # ----------------------------------------------------------------- Define Role
 8448: 
 8449: sub definerole {
 8450:   if (allowed('mcr','/')) {
 8451:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8452:     foreach my $role (split(':',$sysrole)) {
 8453: 	my ($crole,$cqual)=split(/\&/,$role);
 8454:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8455:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8456: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8457:                return "refused:s:$crole&$cqual"; 
 8458:             }
 8459:         }
 8460:     }
 8461:     foreach my $role (split(':',$domrole)) {
 8462: 	my ($crole,$cqual)=split(/\&/,$role);
 8463:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8464:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8465: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8466:                return "refused:d:$crole&$cqual"; 
 8467:             }
 8468:         }
 8469:     }
 8470:     foreach my $role (split(':',$courole)) {
 8471: 	my ($crole,$cqual)=split(/\&/,$role);
 8472:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8473:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8474: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8475:                return "refused:c:$crole&$cqual"; 
 8476:             }
 8477:         }
 8478:     }
 8479:     my $uhome;
 8480:     if (($uname ne '') && ($udom ne '')) {
 8481:         $uhome = &homeserver($uname,$udom);
 8482:         return $uhome if ($uhome eq 'no_host');
 8483:     } else {
 8484:         $uname = $env{'user.name'};
 8485:         $udom = $env{'user.domain'};
 8486:         $uhome = $env{'user.home'};
 8487:     }
 8488:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8489:                 "$udom:$uname:rolesdef_$rolename=".
 8490:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8491:     return reply($command,$uhome);
 8492:   } else {
 8493:     return 'refused';
 8494:   }
 8495: }
 8496: 
 8497: # ---------------- Make a metadata query against the network of library servers
 8498: 
 8499: sub metadata_query {
 8500:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8501:     my %rhash;
 8502:     my %libserv = &all_library();
 8503:     my @server_list = (defined($server_array) ? @$server_array
 8504:                                               : keys(%libserv) );
 8505:     for my $server (@server_list) {
 8506:         my $domains = ''; 
 8507:         if (ref($domains_hash) eq 'HASH') {
 8508:             $domains = $domains_hash->{$server}; 
 8509:         }
 8510: 	unless ($custom or $customshow) {
 8511: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8512: 	    $rhash{$server}=$reply;
 8513: 	}
 8514: 	else {
 8515: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8516: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8517: 			     $server);
 8518: 	    $rhash{$server}=$reply;
 8519: 	}
 8520:     }
 8521:     return \%rhash;
 8522: }
 8523: 
 8524: # ----------------------------------------- Send log queries and wait for reply
 8525: 
 8526: sub log_query {
 8527:     my ($uname,$udom,$query,%filters)=@_;
 8528:     my $uhome=&homeserver($uname,$udom);
 8529:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8530:     my $uhost=&hostname($uhome);
 8531:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8532:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8533:                        $uhome);
 8534:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8535:     return get_query_reply($queryid);
 8536: }
 8537: 
 8538: # -------------------------- Update MySQL table for portfolio file
 8539: 
 8540: sub update_portfolio_table {
 8541:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8542:     if ($group ne '') {
 8543:         $file_name =~s /^\Q$group\E//;
 8544:     }
 8545:     my $homeserver = &homeserver($uname,$udom);
 8546:     my $queryid=
 8547:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8548:                ':'.&escape($file_name).':'.$action,$homeserver);
 8549:     my $reply = &get_query_reply($queryid);
 8550:     return $reply;
 8551: }
 8552: 
 8553: # -------------------------- Update MySQL allusers table
 8554: 
 8555: sub update_allusers_table {
 8556:     my ($uname,$udom,$names) = @_;
 8557:     my $homeserver = &homeserver($uname,$udom);
 8558:     my $queryid=
 8559:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8560:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8561:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8562:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8563:                'generation='.&escape($names->{'generation'}).'%%'.
 8564:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8565:                'id='.&escape($names->{'id'}),$homeserver);
 8566:     return;
 8567: }
 8568: 
 8569: # ------- Request retrieval of institutional classlists for course(s)
 8570: 
 8571: sub fetch_enrollment_query {
 8572:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8573:     my ($homeserver,$sleep,$loopmax);
 8574:     my $maxtries = 1;
 8575:     if ($context eq 'automated') {
 8576:         $homeserver = $perlvar{'lonHostID'};
 8577:         $sleep = 2;
 8578:         $loopmax = 100;
 8579:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8580:     } else {
 8581:         $homeserver = &homeserver($cnum,$dom);
 8582:     }
 8583:     my $host=&hostname($homeserver);
 8584:     my $cmd = '';
 8585:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8586:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8587:     }
 8588:     $cmd =~ s/%%$//;
 8589:     $cmd = &escape($cmd);
 8590:     my $query = 'fetchenrollment';
 8591:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8592:     unless ($queryid=~/^\Q$host\E\_/) { 
 8593:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8594:         return 'error: '.$queryid;
 8595:     }
 8596:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8597:     my $tries = 1;
 8598:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8599:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8600:         $tries ++;
 8601:     }
 8602:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8603:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8604:     } else {
 8605:         my @responses = split(/:/,$reply);
 8606:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8607:             foreach my $line (@responses) {
 8608:                 my ($key,$value) = split(/=/,$line,2);
 8609:                 $$replyref{$key} = $value;
 8610:             }
 8611:         } else {
 8612:             my $pathname = LONCAPA::tempdir();
 8613:             foreach my $line (@responses) {
 8614:                 my ($key,$value) = split(/=/,$line);
 8615:                 $$replyref{$key} = $value;
 8616:                 if ($value > 0) {
 8617:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8618:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8619:                         my $destname = $pathname.'/'.$filename;
 8620:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8621:                         if ($xml_classlist =~ /^error/) {
 8622:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8623:                         } else {
 8624:                             if ( open(FILE,">",$destname) ) {
 8625:                                 print FILE &unescape($xml_classlist);
 8626:                                 close(FILE);
 8627:                             } else {
 8628:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8629:                             }
 8630:                         }
 8631:                     }
 8632:                 }
 8633:             }
 8634:         }
 8635:         return 'ok';
 8636:     }
 8637:     return 'error';
 8638: }
 8639: 
 8640: sub get_query_reply {
 8641:     my ($queryid,$sleep,$loopmax) = @_;;
 8642:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8643:         $sleep = 0.2;
 8644:     }
 8645:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8646:         $loopmax = 100;
 8647:     }
 8648:     my $replyfile=LONCAPA::tempdir().$queryid;
 8649:     my $reply='';
 8650:     for (1..$loopmax) {
 8651: 	sleep($sleep);
 8652:         if (-e $replyfile.'.end') {
 8653: 	    if (open(my $fh,"<",$replyfile)) {
 8654: 		$reply = join('',<$fh>);
 8655: 		close($fh);
 8656: 	   } else { return 'error: reply_file_error'; }
 8657:            return &unescape($reply);
 8658: 	}
 8659:     }
 8660:     return 'timeout:'.$queryid;
 8661: }
 8662: 
 8663: sub courselog_query {
 8664: #
 8665: # possible filters:
 8666: # url: url or symb
 8667: # username
 8668: # domain
 8669: # action: view, submit, grade
 8670: # start: timestamp
 8671: # end: timestamp
 8672: #
 8673:     my (%filters)=@_;
 8674:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8675:     if ($filters{'url'}) {
 8676: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8677:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8678:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8679:     }
 8680:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8681:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8682:     return &log_query($cname,$cdom,'courselog',%filters);
 8683: }
 8684: 
 8685: sub userlog_query {
 8686: #
 8687: # possible filters:
 8688: # action: log check role
 8689: # start: timestamp
 8690: # end: timestamp
 8691: #
 8692:     my ($uname,$udom,%filters)=@_;
 8693:     return &log_query($uname,$udom,'userlog',%filters);
 8694: }
 8695: 
 8696: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8697: 
 8698: sub auto_run {
 8699:     my ($cnum,$cdom) = @_;
 8700:     my $response = 0;
 8701:     my $settings;
 8702:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8703:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8704:         $settings = $domconfig{'autoenroll'};
 8705:         if ($settings->{'run'} eq '1') {
 8706:             $response = 1;
 8707:         }
 8708:     } else {
 8709:         my $homeserver;
 8710:         if (&is_course($cdom,$cnum)) {
 8711:             $homeserver = &homeserver($cnum,$cdom);
 8712:         } else {
 8713:             $homeserver = &domain($cdom,'primary');
 8714:         }
 8715:         if ($homeserver ne 'no_host') {
 8716:             $response = &reply('autorun:'.$cdom,$homeserver);
 8717:         }
 8718:     }
 8719:     return $response;
 8720: }
 8721: 
 8722: sub auto_get_sections {
 8723:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8724:     my $homeserver;
 8725:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8726:         $homeserver = &homeserver($cnum,$cdom);
 8727:     }
 8728:     if (!defined($homeserver)) { 
 8729:         if ($cdom =~ /^$match_domain$/) {
 8730:             $homeserver = &domain($cdom,'primary');
 8731:         }
 8732:     }
 8733:     my @secs;
 8734:     if (defined($homeserver)) {
 8735:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8736:         unless ($response eq 'refused') {
 8737:             @secs = split(/:/,$response);
 8738:         }
 8739:     }
 8740:     return @secs;
 8741: }
 8742: 
 8743: sub auto_new_course {
 8744:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8745:     my $homeserver = &homeserver($cnum,$cdom);
 8746:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8747:     return $response;
 8748: }
 8749: 
 8750: sub auto_validate_courseID {
 8751:     my ($cnum,$cdom,$inst_course_id) = @_;
 8752:     my $homeserver = &homeserver($cnum,$cdom);
 8753:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8754:     return $response;
 8755: }
 8756: 
 8757: sub auto_validate_instcode {
 8758:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8759:     my ($homeserver,$response);
 8760:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8761:         $homeserver = &homeserver($cnum,$cdom);
 8762:     }
 8763:     if (!defined($homeserver)) {
 8764:         if ($cdom =~ /^$match_domain$/) {
 8765:             $homeserver = &domain($cdom,'primary');
 8766:         }
 8767:     }
 8768:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8769:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8770:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8771:     return ($outcome,$description,$defaultcredits);
 8772: }
 8773: 
 8774: sub auto_create_password {
 8775:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8776:     my ($homeserver,$response);
 8777:     my $create_passwd = 0;
 8778:     my $authchk = '';
 8779:     if ($udom =~ /^$match_domain$/) {
 8780:         $homeserver = &domain($udom,'primary');
 8781:     }
 8782:     if ($homeserver eq '') {
 8783:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8784:             $homeserver = &homeserver($cnum,$cdom);
 8785:         }
 8786:     }
 8787:     if ($homeserver eq '') {
 8788:         $authchk = 'nodomain';
 8789:     } else {
 8790:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8791:         if ($response eq 'refused') {
 8792:             $authchk = 'refused';
 8793:         } else {
 8794:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8795:         }
 8796:     }
 8797:     return ($authparam,$create_passwd,$authchk);
 8798: }
 8799: 
 8800: sub auto_photo_permission {
 8801:     my ($cnum,$cdom,$students) = @_;
 8802:     my $homeserver = &homeserver($cnum,$cdom);
 8803:     my ($outcome,$perm_reqd,$conditions) = 
 8804: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8805:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8806: 	return (undef,undef);
 8807:     }
 8808:     return ($outcome,$perm_reqd,$conditions);
 8809: }
 8810: 
 8811: sub auto_checkphotos {
 8812:     my ($uname,$udom,$pid) = @_;
 8813:     my $homeserver = &homeserver($uname,$udom);
 8814:     my ($result,$resulttype);
 8815:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8816: 				   &escape($uname).':'.&escape($pid),
 8817: 				   $homeserver));
 8818:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8819: 	return (undef,undef);
 8820:     }
 8821:     if ($outcome) {
 8822:         ($result,$resulttype) = split(/:/,$outcome);
 8823:     } 
 8824:     return ($result,$resulttype);
 8825: }
 8826: 
 8827: sub auto_photochoice {
 8828:     my ($cnum,$cdom) = @_;
 8829:     my $homeserver = &homeserver($cnum,$cdom);
 8830:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8831: 						       &escape($cdom),
 8832: 						       $homeserver)));
 8833:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8834: 	return (undef,undef);
 8835:     }
 8836:     return ($update,$comment);
 8837: }
 8838: 
 8839: sub auto_photoupdate {
 8840:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8841:     my $homeserver = &homeserver($cnum,$dom);
 8842:     my $host=&hostname($homeserver);
 8843:     my $cmd = '';
 8844:     my $maxtries = 1;
 8845:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8846:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8847:     }
 8848:     $cmd =~ s/%%$//;
 8849:     $cmd = &escape($cmd);
 8850:     my $query = 'institutionalphotos';
 8851:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8852:     unless ($queryid=~/^\Q$host\E\_/) {
 8853:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8854:         return 'error: '.$queryid;
 8855:     }
 8856:     my $reply = &get_query_reply($queryid);
 8857:     my $tries = 1;
 8858:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8859:         $reply = &get_query_reply($queryid);
 8860:         $tries ++;
 8861:     }
 8862:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8863:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8864:     } else {
 8865:         my @responses = split(/:/,$reply);
 8866:         my $outcome = shift(@responses); 
 8867:         foreach my $item (@responses) {
 8868:             my ($key,$value) = split(/=/,$item);
 8869:             $$photo{$key} = $value;
 8870:         }
 8871:         return $outcome;
 8872:     }
 8873:     return 'error';
 8874: }
 8875: 
 8876: sub auto_instcode_format {
 8877:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8878: 	$cat_order) = @_;
 8879:     my $courses = '';
 8880:     my @homeservers;
 8881:     if ($caller eq 'global') {
 8882: 	my %servers = &get_servers($codedom,'library');
 8883: 	foreach my $tryserver (keys(%servers)) {
 8884: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8885: 		push(@homeservers,$tryserver);
 8886: 	    }
 8887:         }
 8888:     } elsif ($caller eq 'requests') {
 8889:         if ($codedom =~ /^$match_domain$/) {
 8890:             my $chome = &domain($codedom,'primary');
 8891:             unless ($chome eq 'no_host') {
 8892:                 push(@homeservers,$chome);
 8893:             }
 8894:         }
 8895:     } else {
 8896:         push(@homeservers,&homeserver($caller,$codedom));
 8897:     }
 8898:     foreach my $code (keys(%{$instcodes})) {
 8899:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8900:     }
 8901:     chop($courses);
 8902:     my $ok_response = 0;
 8903:     my $response;
 8904:     while (@homeservers > 0 && $ok_response == 0) {
 8905:         my $server = shift(@homeservers); 
 8906:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8907:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8908:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8909: 		split(/:/,$response);
 8910:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8911:             push(@{$codetitles},&str2array($codetitles_str));
 8912:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8913:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8914:             $ok_response = 1;
 8915:         }
 8916:     }
 8917:     if ($ok_response) {
 8918:         return 'ok';
 8919:     } else {
 8920:         return $response;
 8921:     }
 8922: }
 8923: 
 8924: sub auto_instcode_defaults {
 8925:     my ($domain,$returnhash,$code_order) = @_;
 8926:     my @homeservers;
 8927: 
 8928:     my %servers = &get_servers($domain,'library');
 8929:     foreach my $tryserver (keys(%servers)) {
 8930: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8931: 	    push(@homeservers,$tryserver);
 8932: 	}
 8933:     }
 8934: 
 8935:     my $response;
 8936:     foreach my $server (@homeservers) {
 8937:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8938:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8939: 	
 8940: 	foreach my $pair (split(/\&/,$response)) {
 8941: 	    my ($name,$value)=split(/\=/,$pair);
 8942: 	    if ($name eq 'code_order') {
 8943: 		@{$code_order} = split(/\&/,&unescape($value));
 8944: 	    } else {
 8945: 		$returnhash->{&unescape($name)}=&unescape($value);
 8946: 	    }
 8947: 	}
 8948: 	return 'ok';
 8949:     }
 8950: 
 8951:     return $response;
 8952: }
 8953: 
 8954: sub auto_possible_instcodes {
 8955:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8956:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8957:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8958:         return;
 8959:     }
 8960:     my (@homeservers,$uhome);
 8961:     if (defined(&domain($domain,'primary'))) {
 8962:         $uhome=&domain($domain,'primary');
 8963:         push(@homeservers,&domain($domain,'primary'));
 8964:     } else {
 8965:         my %servers = &get_servers($domain,'library');
 8966:         foreach my $tryserver (keys(%servers)) {
 8967:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8968:                 push(@homeservers,$tryserver);
 8969:             }
 8970:         }
 8971:     }
 8972:     my $response;
 8973:     foreach my $server (@homeservers) {
 8974:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8975:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8976:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8977:             split(':',$response);
 8978:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8979:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8980:         foreach my $item (split('&',$cat_title)) {   
 8981:             my ($name,$value)=split('=',$item);
 8982:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8983:         }
 8984:         foreach my $item (split('&',$cat_order)) {
 8985:             my ($name,$value)=split('=',$item);
 8986:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8987:         }
 8988:         return 'ok';
 8989:     }
 8990:     return $response;
 8991: }
 8992: 
 8993: sub auto_courserequest_checks {
 8994:     my ($dom) = @_;
 8995:     my ($homeserver,%validations);
 8996:     if ($dom =~ /^$match_domain$/) {
 8997:         $homeserver = &domain($dom,'primary');
 8998:     }
 8999:     unless ($homeserver eq 'no_host') {
 9000:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9001:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9002:             my @items = split(/&/,$response);
 9003:             foreach my $item (@items) {
 9004:                 my ($key,$value) = split('=',$item);
 9005:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9006:             }
 9007:         }
 9008:     }
 9009:     return %validations; 
 9010: }
 9011: 
 9012: sub auto_courserequest_validation {
 9013:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9014:     my ($homeserver,$response);
 9015:     if ($dom =~ /^$match_domain$/) {
 9016:         $homeserver = &domain($dom,'primary');
 9017:     }
 9018:     unless ($homeserver eq 'no_host') {
 9019:         my $customdata;
 9020:         if (ref($custominfo) eq 'HASH') {
 9021:             $customdata = &freeze_escape($custominfo);
 9022:         }
 9023:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9024:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9025:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9026:                                     $customdata,$homeserver));
 9027:     }
 9028:     return $response;
 9029: }
 9030: 
 9031: sub auto_validate_class_sec {
 9032:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9033:     my $homeserver = &homeserver($cnum,$cdom);
 9034:     my $ownerlist;
 9035:     if (ref($owners) eq 'ARRAY') {
 9036:         $ownerlist = join(',',@{$owners});
 9037:     } else {
 9038:         $ownerlist = $owners;
 9039:     }
 9040:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9041:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9042:     return $response;
 9043: }
 9044: 
 9045: sub auto_validate_instclasses {
 9046:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9047:     my ($homeserver,%validations);
 9048:     $homeserver = &homeserver($cnum,$cdom);
 9049:     unless ($homeserver eq 'no_host') {
 9050:         my $ownerlist;
 9051:         if (ref($owners) eq 'ARRAY') {
 9052:             $ownerlist = join(',',@{$owners});
 9053:         } else {
 9054:             $ownerlist = $owners;
 9055:         }
 9056:         if (ref($classesref) eq 'HASH') {
 9057:             my $classes = &freeze_escape($classesref);
 9058:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9059:                                 ':'.$cdom.':'.$classes,$homeserver);
 9060:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9061:                 my @items = split(/&/,$response);
 9062:                 foreach my $item (@items) {
 9063:                     my ($key,$value) = split('=',$item);
 9064:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9065:                 }
 9066:             }
 9067:         }
 9068:     }
 9069:     return %validations;
 9070: }
 9071: 
 9072: sub auto_crsreq_update {
 9073:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9074:         $code,$accessstart,$accessend,$inbound) = @_;
 9075:     my ($homeserver,%crsreqresponse);
 9076:     if ($cdom =~ /^$match_domain$/) {
 9077:         $homeserver = &domain($cdom,'primary');
 9078:     }
 9079:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9080:         my $info;
 9081:         if (ref($inbound) eq 'HASH') {
 9082:             $info = &freeze_escape($inbound);
 9083:         }
 9084:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9085:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9086:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9087:                             &escape($title).':'.&escape($code).':'.
 9088:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9089:                             $homeserver);
 9090:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9091:             my @items = split(/&/,$response);
 9092:             foreach my $item (@items) {
 9093:                 my ($key,$value) = split('=',$item);
 9094:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9095:             }
 9096:         }
 9097:     }
 9098:     return \%crsreqresponse;
 9099: }
 9100: 
 9101: sub auto_export_grades {
 9102:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9103:     my ($homeserver,%exportresponse);
 9104:     if ($cdom =~ /^$match_domain$/) {
 9105:         $homeserver = &domain($cdom,'primary');
 9106:     }
 9107:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9108:         my $info;
 9109:         if (ref($inforef) eq 'HASH') {
 9110:             $info = &freeze_escape($inforef);
 9111:         }
 9112:         if (ref($gradesref) eq 'HASH') {
 9113:             my $grades = &freeze_escape($gradesref);
 9114:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9115:                                 $info.':'.$grades,$homeserver);
 9116:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9117:                 my @items = split(/&/,$response);
 9118:                 foreach my $item (@items) {
 9119:                     my ($key,$value) = split('=',$item);
 9120:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9121:                 }
 9122:             }
 9123:         }
 9124:     }
 9125:     return \%exportresponse;
 9126: }
 9127: 
 9128: sub check_instcode_cloning {
 9129:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9130:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9131:         return;
 9132:     }
 9133:     my $canclone;
 9134:     if (@{$code_order} > 0) {
 9135:         my $instcoderegexp ='^';
 9136:         my @clonecodes = split(/\&/,$cloner);
 9137:         foreach my $item (@{$code_order}) {
 9138:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9139:                 foreach my $pair (@clonecodes) {
 9140:                     my ($key,$val) = split(/\=/,$pair,2);
 9141:                     $val = &unescape($val);
 9142:                     if ($key eq $item) {
 9143:                         $instcoderegexp .= '('.$val.')';
 9144:                         last;
 9145:                     }
 9146:                 }
 9147:             } else {
 9148:                 $instcoderegexp .= $codedefaults->{$item};
 9149:             }
 9150:         }
 9151:         $instcoderegexp .= '$';
 9152:         my (@from,@to);
 9153:         eval {
 9154:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9155:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9156:         };
 9157:         if ((@from > 0) && (@to > 0)) {
 9158:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9159:             if (!@diffs) {
 9160:                 $canclone = 1;
 9161:             }
 9162:         }
 9163:     }
 9164:     return $canclone;
 9165: }
 9166: 
 9167: sub default_instcode_cloning {
 9168:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9169:     my (%codedefaults,@code_order,$canclone);
 9170:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9171:         %codedefaults = %{$codedefaultsref};
 9172:         @code_order = @{$codeorderref};
 9173:     } elsif ($clonedom) {
 9174:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9175:     }
 9176:     if (($domdefclone) && (@code_order)) {
 9177:         my @clonecodes = split(/\+/,$domdefclone);
 9178:         my $instcoderegexp ='^';
 9179:         foreach my $item (@code_order) {
 9180:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9181:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9182:             } else {
 9183:                 $instcoderegexp .= $codedefaults{$item};
 9184:             }
 9185:         }
 9186:         $instcoderegexp .= '$';
 9187:         my (@from,@to);
 9188:         eval {
 9189:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9190:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9191:         };
 9192:         if ((@from > 0) && (@to > 0)) {
 9193:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9194:             if (!@diffs) {
 9195:                 $canclone = 1;
 9196:             }
 9197:         }
 9198:     }
 9199:     return $canclone;
 9200: }
 9201: 
 9202: # ------------------------------------------------------- Course Group routines
 9203: 
 9204: sub get_coursegroups {
 9205:     my ($cdom,$cnum,$group,$namespace) = @_;
 9206:     return(&dump($namespace,$cdom,$cnum,$group));
 9207: }
 9208: 
 9209: sub modify_coursegroup {
 9210:     my ($cdom,$cnum,$groupsettings) = @_;
 9211:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9212: }
 9213: 
 9214: sub toggle_coursegroup_status {
 9215:     my ($cdom,$cnum,$group,$action) = @_;
 9216:     my ($from_namespace,$to_namespace);
 9217:     if ($action eq 'delete') {
 9218:         $from_namespace = 'coursegroups';
 9219:         $to_namespace = 'deleted_groups';
 9220:     } else {
 9221:         $from_namespace = 'deleted_groups';
 9222:         $to_namespace = 'coursegroups';
 9223:     }
 9224:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9225:     if (my $tmp = &error(%curr_group)) {
 9226:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9227:         return ('read error',$tmp);
 9228:     } else {
 9229:         my %savedsettings = %curr_group; 
 9230:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9231:         my $deloutcome;
 9232:         if ($result eq 'ok') {
 9233:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9234:         } else {
 9235:             return ('write error',$result);
 9236:         }
 9237:         if ($deloutcome eq 'ok') {
 9238:             return 'ok';
 9239:         } else {
 9240:             return ('delete error',$deloutcome);
 9241:         }
 9242:     }
 9243: }
 9244: 
 9245: sub modify_group_roles {
 9246:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9247:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9248:     my $role = 'gr/'.&escape($userprivs);
 9249:     my ($uname,$udom) = split(/:/,$user);
 9250:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9251:     if ($result eq 'ok') {
 9252:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9253:     }
 9254:     return $result;
 9255: }
 9256: 
 9257: sub modify_coursegroup_membership {
 9258:     my ($cdom,$cnum,$membership) = @_;
 9259:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9260:     return $result;
 9261: }
 9262: 
 9263: sub get_active_groups {
 9264:     my ($udom,$uname,$cdom,$cnum) = @_;
 9265:     my $now = time;
 9266:     my %groups = ();
 9267:     foreach my $key (keys(%env)) {
 9268:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9269:             my ($start,$end) = split(/\./,$env{$key});
 9270:             if (($end!=0) && ($end<$now)) { next; }
 9271:             if (($start!=0) && ($start>$now)) { next; }
 9272:             if ($1 eq $cdom && $2 eq $cnum) {
 9273:                 $groups{$3} = $env{$key} ;
 9274:             }
 9275:         }
 9276:     }
 9277:     return %groups;
 9278: }
 9279: 
 9280: sub get_group_membership {
 9281:     my ($cdom,$cnum,$group) = @_;
 9282:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9283: }
 9284: 
 9285: sub get_users_groups {
 9286:     my ($udom,$uname,$courseid) = @_;
 9287:     my @usersgroups;
 9288:     my $cachetime=1800;
 9289: 
 9290:     my $hashid="$udom:$uname:$courseid";
 9291:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9292:     if (defined($cached)) {
 9293:         @usersgroups = split(/:/,$grouplist);
 9294:     } else {  
 9295:         $grouplist = '';
 9296:         my $courseurl = &courseid_to_courseurl($courseid);
 9297:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9298:         my $access_end = $env{'course.'.$courseid.
 9299:                               '.default_enrollment_end_date'};
 9300:         my $now = time;
 9301:         foreach my $key (keys(%roleshash)) {
 9302:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9303:                 my $group = $1;
 9304:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9305:                     my $start = $2;
 9306:                     my $end = $1;
 9307:                     if ($start == -1) { next; } # deleted from group
 9308:                     if (($start!=0) && ($start>$now)) { next; }
 9309:                     if (($end!=0) && ($end<$now)) {
 9310:                         if ($access_end && $access_end < $now) {
 9311:                             if ($access_end - $end < 86400) {
 9312:                                 push(@usersgroups,$group);
 9313:                             }
 9314:                         }
 9315:                         next;
 9316:                     }
 9317:                     push(@usersgroups,$group);
 9318:                 }
 9319:             }
 9320:         }
 9321:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9322:         $grouplist = join(':',@usersgroups);
 9323:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9324:     }
 9325:     return @usersgroups;
 9326: }
 9327: 
 9328: sub devalidate_getgroups_cache {
 9329:     my ($udom,$uname,$cdom,$cnum)=@_;
 9330:     my $courseid = $cdom.'_'.$cnum;
 9331: 
 9332:     my $hashid="$udom:$uname:$courseid";
 9333:     &devalidate_cache_new('getgroups',$hashid);
 9334: }
 9335: 
 9336: # ------------------------------------------------------------------ Plain Text
 9337: 
 9338: sub plaintext {
 9339:     my ($short,$type,$cid,$forcedefault) = @_;
 9340:     if ($short =~ m{^cr/}) {
 9341: 	return (split('/',$short))[-1];
 9342:     }
 9343:     if (!defined($cid)) {
 9344:         $cid = $env{'request.course.id'};
 9345:     }
 9346:     my %rolenames = (
 9347:                       Course    => 'std',
 9348:                       Community => 'alt1',
 9349:                       Placement => 'std',
 9350:                     );
 9351:     if ($cid ne '') {
 9352:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9353:             unless ($forcedefault) {
 9354:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9355:                 &Apache::lonlocal::mt_escape(\$roletext);
 9356:                 return &Apache::lonlocal::mt($roletext);
 9357:             }
 9358:         }
 9359:     }
 9360:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9361:         (defined($rolenames{$type})) && 
 9362:         (defined($prp{$short}{$rolenames{$type}}))) {
 9363:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9364:     } elsif ($cid ne '') {
 9365:         my $crstype = $env{'course.'.$cid.'.type'};
 9366:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9367:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9368:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9369:         }
 9370:     }
 9371:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9372: }
 9373: 
 9374: # ----------------------------------------------------------------- Assign Role
 9375: 
 9376: sub assignrole {
 9377:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9378:         $context)=@_;
 9379:     my $mrole;
 9380:     if ($role =~ /^cr\//) {
 9381:         my $cwosec=$url;
 9382:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9383: 	unless (&allowed('ccr',$cwosec)) {
 9384:            my $refused = 1;
 9385:            if ($context eq 'requestcourses') {
 9386:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9387:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9388:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9389:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9390:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9391:                            if ($crsenv{'internal.courseowner'} eq
 9392:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9393:                                $refused = '';
 9394:                            }
 9395:                        }
 9396:                    }
 9397:                }
 9398:            }
 9399:            if ($refused) {
 9400:                &logthis('Refused custom assignrole: '.
 9401:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9402:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9403:                return 'refused';
 9404:            }
 9405:         }
 9406:         $mrole='cr';
 9407:     } elsif ($role =~ /^gr\//) {
 9408:         my $cwogrp=$url;
 9409:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9410:         unless (&allowed('mdg',$cwogrp)) {
 9411:             &logthis('Refused group assignrole: '.
 9412:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9413:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9414:             return 'refused';
 9415:         }
 9416:         $mrole='gr';
 9417:     } else {
 9418:         my $cwosec=$url;
 9419:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9420:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9421:             my $refused;
 9422:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9423:                 if (!(&allowed('c'.$role,$url))) {
 9424:                     $refused = 1;
 9425:                 }
 9426:             } else {
 9427:                 $refused = 1;
 9428:             }
 9429:             if ($refused) {
 9430:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9431:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9432:                     my %crsenv;
 9433:                     if ($role eq 'cc' || $role eq 'co') {
 9434:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9435:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9436:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9437:                                 if ($crsenv{'internal.courseowner'} eq 
 9438:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9439:                                     $refused = '';
 9440:                                 }
 9441:                             }
 9442:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9443:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9444:                                 if ($crsenv{'internal.courseowner'} eq 
 9445:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9446:                                     $refused = '';
 9447:                                 }
 9448:                             }
 9449:                         }
 9450:                     }
 9451:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9452:                     if ($role eq 'st') {
 9453:                         $refused = '';
 9454:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9455:                         $refused = '';
 9456:                     }
 9457:                 } elsif ($context eq 'requestcourses') {
 9458:                     my @possroles = ('st','ta','ep','in','cc','co');
 9459:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9460:                         my $wrongcc;
 9461:                         if ($cnum =~ /^$match_community$/) {
 9462:                             $wrongcc = 1 if ($role eq 'cc');
 9463:                         } else {
 9464:                             $wrongcc = 1 if ($role eq 'co');
 9465:                         }
 9466:                         unless ($wrongcc) {
 9467:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9468:                             if ($crsenv{'internal.courseowner'} eq 
 9469:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9470:                                 $refused = '';
 9471:                             }
 9472:                         }
 9473:                     }
 9474:                 } elsif ($context eq 'requestauthor') {
 9475:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9476:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9477:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9478:                             $refused = '';
 9479:                         } else {
 9480:                             my %domdefaults = &get_domain_defaults($udom);
 9481:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9482:                                 my $checkbystatus;
 9483:                                 if ($env{'user.adv'}) { 
 9484:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9485:                                     if ($disposition eq 'automatic') {
 9486:                                         $refused = '';
 9487:                                     } elsif ($disposition eq '') {
 9488:                                         $checkbystatus = 1;
 9489:                                     } 
 9490:                                 } else {
 9491:                                     $checkbystatus = 1;
 9492:                                 }
 9493:                                 if ($checkbystatus) {
 9494:                                     if ($env{'environment.inststatus'}) {
 9495:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9496:                                         foreach my $type (@inststatuses) {
 9497:                                             if (($type ne '') &&
 9498:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9499:                                                 $refused = '';
 9500:                                             }
 9501:                                         }
 9502:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9503:                                         $refused = '';
 9504:                                     }
 9505:                                 }
 9506:                             }
 9507:                         }
 9508:                     }
 9509:                 }
 9510:                 if ($refused) {
 9511:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9512:                              ' '.$role.' '.$end.' '.$start.' by '.
 9513: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9514:                     return 'refused';
 9515:                 }
 9516:             }
 9517:         } elsif ($role eq 'au') {
 9518:             if ($url ne '/'.$udom.'/') {
 9519:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9520:                          ' to assign author role for '.$uname.':'.$udom.
 9521:                          ' in domain: '.$url.' refused (wrong domain).');
 9522:                 return 'refused';
 9523:             }
 9524:         }
 9525:         $mrole=$role;
 9526:     }
 9527:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9528:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9529:     if ($end) { $command.='_'.$end; }
 9530:     if ($start) {
 9531: 	if ($end) { 
 9532:            $command.='_'.$start; 
 9533:         } else {
 9534:            $command.='_0_'.$start;
 9535:         }
 9536:     }
 9537:     my $origstart = $start;
 9538:     my $origend = $end;
 9539:     my $delflag;
 9540: # actually delete
 9541:     if ($deleteflag) {
 9542: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9543: # modify command to delete the role
 9544:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9545:                 "$udom:$uname:$url".'_'."$mrole";
 9546: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9547: # set start and finish to negative values for userrolelog
 9548:            $start=-1;
 9549:            $end=-1;
 9550:            $delflag = 1;
 9551:         }
 9552:     }
 9553: # send command
 9554:     my $answer=&reply($command,&homeserver($uname,$udom));
 9555: # log new user role if status is ok
 9556:     if ($answer eq 'ok') {
 9557: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9558:         if (($role eq 'cc') || ($role eq 'in') ||
 9559:             ($role eq 'ep') || ($role eq 'ad') ||
 9560:             ($role eq 'ta') || ($role eq 'st') ||
 9561:             ($role=~/^cr/) || ($role eq 'gr') ||
 9562:             ($role eq 'co')) {
 9563: # for course roles, perform group memberships changes triggered by role change.
 9564:             unless ($role =~ /^gr/) {
 9565:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9566:                                                  $origstart,$selfenroll,$context);
 9567:             }
 9568:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9569:                            $selfenroll,$context);
 9570:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9571:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9572:                  ($role eq 'da')) {
 9573:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9574:                            $context);
 9575:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9576:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9577:                              $context); 
 9578:         }
 9579:         if ($role eq 'cc') {
 9580:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9581:         }
 9582:     }
 9583:     return $answer;
 9584: }
 9585: 
 9586: sub autoupdate_coowners {
 9587:     my ($url,$end,$start,$uname,$udom) = @_;
 9588:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9589:     if (($cdom ne '') && ($cnum ne '')) {
 9590:         my $now = time;
 9591:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9592:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9593:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9594:             my $instcode = $coursehash{'internal.coursecode'};
 9595:             if ($instcode ne '') {
 9596:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9597:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9598:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9599:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9600:                         if ($result eq 'valid') {
 9601:                             if ($coursehash{'internal.co-owners'}) {
 9602:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9603:                                     push(@newcoowners,$coowner);
 9604:                                 }
 9605:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9606:                                     push(@newcoowners,$uname.':'.$udom);
 9607:                                 }
 9608:                                 @newcoowners = sort(@newcoowners);
 9609:                             } else {
 9610:                                 push(@newcoowners,$uname.':'.$udom);
 9611:                             }
 9612:                         } else {
 9613:                             if ($coursehash{'internal.co-owners'}) {
 9614:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9615:                                     unless ($coowner eq $uname.':'.$udom) {
 9616:                                         push(@newcoowners,$coowner);
 9617:                                     }
 9618:                                 }
 9619:                                 unless (@newcoowners > 0) {
 9620:                                     $delcoowners = 1;
 9621:                                     $coowners = '';
 9622:                                 }
 9623:                             }
 9624:                         }
 9625:                         if (@newcoowners || $delcoowners) {
 9626:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9627:                                             $delcoowners,@newcoowners);
 9628:                         }
 9629:                     }
 9630:                 }
 9631:             }
 9632:         }
 9633:     }
 9634: }
 9635: 
 9636: sub store_coowners {
 9637:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9638:     my $cid = $cdom.'_'.$cnum;
 9639:     my ($coowners,$delresult,$putresult);
 9640:     if (@newcoowners) {
 9641:         $coowners = join(',',@newcoowners);
 9642:         my %coownershash = (
 9643:                             'internal.co-owners' => $coowners,
 9644:                            );
 9645:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9646:         if ($putresult eq 'ok') {
 9647:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9648:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9649:             }
 9650:         }
 9651:     }
 9652:     if ($delcoowners) {
 9653:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9654:         if ($delresult eq 'ok') {
 9655:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9656:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9657:             }
 9658:         }
 9659:     }
 9660:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9661:         my %crsinfo =
 9662:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9663:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9664:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9665:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9666:         }
 9667:     }
 9668: }
 9669: 
 9670: # -------------------------------------------------- Modify user authentication
 9671: # Overrides without validation
 9672: 
 9673: sub modifyuserauth {
 9674:     my ($udom,$uname,$umode,$upass)=@_;
 9675:     my $uhome=&homeserver($uname,$udom);
 9676:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9677:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9678:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9679:              ' in domain '.$env{'request.role.domain'});  
 9680:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9681: 		     &escape($upass),$uhome);
 9682:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9683:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9684:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9685:     &log($udom,,$uname,$uhome,
 9686:         'Authentication changed by '.$env{'user.domain'}.', '.
 9687:                                      $env{'user.name'}.', '.$umode.
 9688:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9689:     unless ($reply eq 'ok') {
 9690:         &logthis('Authentication mode error: '.$reply);
 9691: 	return 'error: '.$reply;
 9692:     }   
 9693:     return 'ok';
 9694: }
 9695: 
 9696: # --------------------------------------------------------------- Modify a user
 9697: 
 9698: sub modifyuser {
 9699:     my ($udom,    $uname, $uid,
 9700:         $umode,   $upass, $first,
 9701:         $middle,  $last,  $gene,
 9702:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9703:     $udom= &LONCAPA::clean_domain($udom);
 9704:     $uname=&LONCAPA::clean_username($uname);
 9705:     my $showcandelete = 'none';
 9706:     if (ref($candelete) eq 'ARRAY') {
 9707:         if (@{$candelete} > 0) {
 9708:             $showcandelete = join(', ',@{$candelete});
 9709:         }
 9710:     }
 9711:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9712:              $umode.', '.$first.', '.$middle.', '.
 9713: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9714:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9715:                                      ' desiredhome not specified'). 
 9716:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9717:              ' in domain '.$env{'request.role.domain'});
 9718:     my $uhome=&homeserver($uname,$udom,'true');
 9719:     my $newuser;
 9720:     if ($uhome eq 'no_host') {
 9721:         $newuser = 1;
 9722:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9723:                 ($umode eq 'lti')) {
 9724:             return 'error: more information needed to create new user';
 9725:         }
 9726:     }
 9727: # ----------------------------------------------------------------- Create User
 9728:     if (($uhome eq 'no_host') && 
 9729: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9730:         my $unhome='';
 9731:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9732:             $unhome = $desiredhome;
 9733: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9734: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9735:         } else { # load balancing routine for determining $unhome
 9736:             my $loadm=10000000;
 9737: 	    my %servers = &get_servers($udom,'library');
 9738: 	    foreach my $tryserver (keys(%servers)) {
 9739: 		my $answer=reply('load',$tryserver);
 9740: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9741: 		    $loadm=$answer;
 9742: 		    $unhome=$tryserver;
 9743: 		}
 9744: 	    }
 9745:         }
 9746:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9747: 	    return 'error: unable to find a home server for '.$uname.
 9748:                    ' in domain '.$udom;
 9749:         }
 9750:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9751:                          &escape($upass),$unhome);
 9752: 	unless ($reply eq 'ok') {
 9753:             return 'error: '.$reply;
 9754:         }   
 9755:         $uhome=&homeserver($uname,$udom,'true');
 9756:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9757: 	    return 'error: unable verify users home machine.';
 9758:         }
 9759:     }   # End of creation of new user
 9760: # ---------------------------------------------------------------------- Add ID
 9761:     if ($uid) {
 9762:        $uid=~tr/A-Z/a-z/;
 9763:        my %uidhash=&idrget($udom,$uname);
 9764:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9765:          && (!$forceid)) {
 9766: 	  unless ($uid eq $uidhash{$uname}) {
 9767: 	      return 'error: user id "'.$uid.'" does not match '.
 9768:                   'current user id "'.$uidhash{$uname}.'".';
 9769:           }
 9770:        } else {
 9771: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9772:        }
 9773:     }
 9774: # -------------------------------------------------------------- Add names, etc
 9775:     my @tmp=&get('environment',
 9776: 		   ['firstname','middlename','lastname','generation','id',
 9777:                     'permanentemail','inststatus'],
 9778: 		   $udom,$uname);
 9779:     my (%names,%oldnames);
 9780:     if ($tmp[0] =~ m/^error:.*/) { 
 9781:         %names=(); 
 9782:     } else {
 9783:         %names = @tmp;
 9784:         %oldnames = %names;
 9785:     }
 9786: #
 9787: # If name, email and/or uid are blank (e.g., because an uploaded file
 9788: # of users did not contain them), do not overwrite existing values
 9789: # unless field is in $candelete array ref.  
 9790: #
 9791: 
 9792:     my @fields = ('firstname','middlename','lastname','generation',
 9793:                   'permanentemail','id');
 9794:     my %newvalues;
 9795:     if (ref($candelete) eq 'ARRAY') {
 9796:         foreach my $field (@fields) {
 9797:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9798:                 if ($field eq 'firstname') {
 9799:                     $names{$field} = $first;
 9800:                 } elsif ($field eq 'middlename') {
 9801:                     $names{$field} = $middle;
 9802:                 } elsif ($field eq 'lastname') {
 9803:                     $names{$field} = $last;
 9804:                 } elsif ($field eq 'generation') { 
 9805:                     $names{$field} = $gene;
 9806:                 } elsif ($field eq 'permanentemail') {
 9807:                     $names{$field} = $email;
 9808:                 } elsif ($field eq 'id') {
 9809:                     $names{$field}  = $uid;
 9810:                 }
 9811:             }
 9812:         }
 9813:     }
 9814:     if ($first)  { $names{'firstname'}  = $first; }
 9815:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9816:     if ($last)   { $names{'lastname'}   = $last; }
 9817:     if (defined($gene))   { $names{'generation'} = $gene; }
 9818:     if ($email) {
 9819:        $email=~s/[^\w\@\.\-\,]//gs;
 9820:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9821:     }
 9822:     if ($uid) { $names{'id'}  = $uid; }
 9823:     if (defined($inststatus)) {
 9824:         $names{'inststatus'} = '';
 9825:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9826:         if (ref($usertypes) eq 'HASH') {
 9827:             my @okstatuses; 
 9828:             foreach my $item (split(/:/,$inststatus)) {
 9829:                 if (defined($usertypes->{$item})) {
 9830:                     push(@okstatuses,$item);  
 9831:                 }
 9832:             }
 9833:             if (@okstatuses) {
 9834:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9835:             }
 9836:         }
 9837:     }
 9838:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9839:                  $umode.', '.$first.', '.$middle.', '.
 9840:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9841:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9842:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9843:     } else {
 9844:         $logmsg .= ' during self creation';
 9845:     }
 9846:     my $changed;
 9847:     if ($newuser) {
 9848:         $changed = 1;
 9849:     } else {
 9850:         foreach my $field (@fields) {
 9851:             if ($names{$field} ne $oldnames{$field}) {
 9852:                 $changed = 1;
 9853:                 last;
 9854:             }
 9855:         }
 9856:     }
 9857:     unless ($changed) {
 9858:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9859:         &logthis($logmsg);
 9860:         return 'ok';
 9861:     }
 9862:     my $reply = &put('environment', \%names, $udom,$uname);
 9863:     if ($reply ne 'ok') { 
 9864:         return 'error: '.$reply;
 9865:     }
 9866:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9867:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9868:     }
 9869:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9870:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9871:     $logmsg = 'Success modifying user '.$logmsg;
 9872:     &logthis($logmsg);
 9873:     return 'ok';
 9874: }
 9875: 
 9876: # -------------------------------------------------------------- Modify student
 9877: 
 9878: sub modifystudent {
 9879:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9880:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9881:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9882:     if (!$cid) {
 9883: 	unless ($cid=$env{'request.course.id'}) {
 9884: 	    return 'not_in_class';
 9885: 	}
 9886:     }
 9887: # --------------------------------------------------------------- Make the user
 9888:     my $reply=&modifyuser
 9889: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9890:          $desiredhome,$email,$inststatus);
 9891:     unless ($reply eq 'ok') { return $reply; }
 9892:     # This will cause &modify_student_enrollment to get the uid from the
 9893:     # student's environment
 9894:     $uid = undef if (!$forceid);
 9895:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9896:                                         $gene,$usec,$end,$start,$type,$locktype,
 9897:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9898:     return $reply;
 9899: }
 9900: 
 9901: sub modify_student_enrollment {
 9902:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9903:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9904:     my ($cdom,$cnum,$chome);
 9905:     if (!$cid) {
 9906: 	unless ($cid=$env{'request.course.id'}) {
 9907: 	    return 'not_in_class';
 9908: 	}
 9909: 	$cdom=$env{'course.'.$cid.'.domain'};
 9910: 	$cnum=$env{'course.'.$cid.'.num'};
 9911:     } else {
 9912: 	($cdom,$cnum)=split(/_/,$cid);
 9913:     }
 9914:     $chome=$env{'course.'.$cid.'.home'};
 9915:     if (!$chome) {
 9916: 	$chome=&homeserver($cnum,$cdom);
 9917:     }
 9918:     if (!$chome) { return 'unknown_course'; }
 9919:     # Make sure the user exists
 9920:     my $uhome=&homeserver($uname,$udom);
 9921:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9922: 	return 'error: no such user';
 9923:     }
 9924:     # Get student data if we were not given enough information
 9925:     if (!defined($first)  || $first  eq '' || 
 9926:         !defined($last)   || $last   eq '' || 
 9927:         !defined($uid)    || $uid    eq '' || 
 9928:         !defined($middle) || $middle eq '' || 
 9929:         !defined($gene)   || $gene   eq '') {
 9930:         # They did not supply us with enough data to enroll the student, so
 9931:         # we need to pick up more information.
 9932:         my %tmp = &get('environment',
 9933:                        ['firstname','middlename','lastname', 'generation','id']
 9934:                        ,$udom,$uname);
 9935: 
 9936:         #foreach my $key (keys(%tmp)) {
 9937:         #    &logthis("key $key = ".$tmp{$key});
 9938:         #}
 9939:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9940:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9941:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9942:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9943:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9944:     }
 9945:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9946:     my $user = "$uname:$udom";
 9947:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9948:     my $reply=cput('classlist',
 9949: 		   {$user => 
 9950: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9951: 		   $cdom,$cnum);
 9952:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9953:         &devalidate_getsection_cache($udom,$uname,$cid);
 9954:     } else { 
 9955: 	return 'error: '.$reply;
 9956:     }
 9957:     # Add student role to user
 9958:     my $uurl='/'.$cid;
 9959:     $uurl=~s/\_/\//g;
 9960:     if ($usec) {
 9961: 	$uurl.='/'.$usec;
 9962:     }
 9963:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9964:                              $selfenroll,$context);
 9965:     if ($result ne 'ok') {
 9966:         if ($old_entry{$user} ne '') {
 9967:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9968:         } else {
 9969:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9970:         }
 9971:     }
 9972:     return $result; 
 9973: }
 9974: 
 9975: sub format_name {
 9976:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9977:     my $name;
 9978:     if ($first ne 'lastname') {
 9979: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9980:     } else {
 9981: 	if ($lastname=~/\S/) {
 9982: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9983: 	    $name=~s/\s+,/,/;
 9984: 	} else {
 9985: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9986: 	}
 9987:     }
 9988:     $name=~s/^\s+//;
 9989:     $name=~s/\s+$//;
 9990:     $name=~s/\s+/ /g;
 9991:     return $name;
 9992: }
 9993: 
 9994: # ------------------------------------------------- Write to course preferences
 9995: 
 9996: sub writecoursepref {
 9997:     my ($courseid,%prefs)=@_;
 9998:     $courseid=~s/^\///;
 9999:     $courseid=~s/\_/\//g;
10000:     my ($cdomain,$cnum)=split(/\//,$courseid);
10001:     my $chome=homeserver($cnum,$cdomain);
10002:     if (($chome eq '') || ($chome eq 'no_host')) { 
10003: 	return 'error: no such course';
10004:     }
10005:     my $cstring='';
10006:     foreach my $pref (keys(%prefs)) {
10007: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10008:     }
10009:     $cstring=~s/\&$//;
10010:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10011: }
10012: 
10013: # ---------------------------------------------------------- Make/modify course
10014: 
10015: sub createcourse {
10016:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10017:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10018:     $url=&declutter($url);
10019:     my $cid='';
10020:     if ($context eq 'requestcourses') {
10021:         my $can_create = 0;
10022:         my ($ownername,$ownerdom) = split(':',$course_owner);
10023:         if ($udom eq $ownerdom) {
10024:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10025:                                   $context)) {
10026:                 $can_create = 1;
10027:             }
10028:         } else {
10029:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10030:                                            $category);
10031:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10032:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10033:                 if (@curr > 0) {
10034:                     my @options = qw(approval validate autolimit);
10035:                     my $optregex = join('|',@options);
10036:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10037:                         $can_create = 1;
10038:                     }
10039:                 }
10040:             }
10041:         }
10042:         if ($can_create) {
10043:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10044:                 unless (&allowed('ccc',$udom)) {
10045:                     return 'refused'; 
10046:                 }
10047:             }
10048:         } else {
10049:             return 'refused';
10050:         }
10051:     } elsif (!&allowed('ccc',$udom)) {
10052:         return 'refused';
10053:     }
10054: # --------------------------------------------------------------- Get Unique ID
10055:     my $uname;
10056:     if ($cnum =~ /^$match_courseid$/) {
10057:         my $chome=&homeserver($cnum,$udom,'true');
10058:         if (($chome eq '') || ($chome eq 'no_host')) {
10059:             $uname = $cnum;
10060:         } else {
10061:             $uname = &generate_coursenum($udom,$crstype);
10062:         }
10063:     } else {
10064:         $uname = &generate_coursenum($udom,$crstype);
10065:     }
10066:     return $uname if ($uname =~ /^error/);
10067: # -------------------------------------------------- Check supplied server name
10068:     if (!defined($course_server)) {
10069:         if (defined(&domain($udom,'primary'))) {
10070:             $course_server = &domain($udom,'primary');
10071:         } else {
10072:             $course_server = $env{'user.home'}; 
10073:         }
10074:     }
10075:     my %host_servers =
10076:         &Apache::lonnet::get_servers($udom,'library');
10077:     unless ($host_servers{$course_server}) {
10078:         return 'error: invalid home server for course: '.$course_server;
10079:     }
10080: # ------------------------------------------------------------- Make the course
10081:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10082:                       $course_server);
10083:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10084:     my $uhome=&homeserver($uname,$udom,'true');
10085:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10086: 	return 'error: no such course';
10087:     }
10088: # ----------------------------------------------------------------- Course made
10089: # log existence
10090:     my $now = time;
10091:     my $newcourse = {
10092:                     $udom.'_'.$uname => {
10093:                                      description => $description,
10094:                                      inst_code   => $inst_code,
10095:                                      owner       => $course_owner,
10096:                                      type        => $crstype,
10097:                                      creator     => $env{'user.name'}.':'.
10098:                                                     $env{'user.domain'},
10099:                                      created     => $now,
10100:                                      context     => $context,
10101:                                                 },
10102:                     };
10103:     &courseidput($udom,$newcourse,$uhome,'notime');
10104: # set toplevel url
10105:     my $topurl=$url;
10106:     unless ($nonstandard) {
10107: # ------------------------------------------ For standard courses, make top url
10108:         my $mapurl=&clutter($url);
10109:         if ($mapurl eq '/res/') { $mapurl=''; }
10110:         $env{'form.initmap'}=(<<ENDINITMAP);
10111: <map>
10112: <resource id="1" type="start"></resource>
10113: <resource id="2" src="$mapurl"></resource>
10114: <resource id="3" type="finish"></resource>
10115: <link index="1" from="1" to="2"></link>
10116: <link index="2" from="2" to="3"></link>
10117: </map>
10118: ENDINITMAP
10119:         $topurl=&declutter(
10120:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10121:                           );
10122:     }
10123: # ----------------------------------------------------------- Write preferences
10124:     &writecoursepref($udom.'_'.$uname,
10125:                      ('description'              => $description,
10126:                       'url'                      => $topurl,
10127:                       'internal.creator'         => $env{'user.name'}.':'.
10128:                                                     $env{'user.domain'},
10129:                       'internal.created'         => $now,
10130:                       'internal.creationcontext' => $context)
10131:                     );
10132:     return '/'.$udom.'/'.$uname;
10133: }
10134: 
10135: # ------------------------------------------------------------------- Create ID
10136: sub generate_coursenum {
10137:     my ($udom,$crstype) = @_;
10138:     my $domdesc = &domain($udom);
10139:     return 'error: invalid domain' if ($domdesc eq '');
10140:     my $first;
10141:     if ($crstype eq 'Community') {
10142:         $first = '0';
10143:     } else {
10144:         $first = int(1+rand(9)); 
10145:     } 
10146:     my $uname=$first.
10147:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10148:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10149:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10150: # ----------------------------------------------- Make sure that does not exist
10151:     my $uhome=&homeserver($uname,$udom,'true');
10152:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10153:         if ($crstype eq 'Community') {
10154:             $first = '0';
10155:         } else {
10156:             $first = int(1+rand(9));
10157:         }
10158:         $uname=$first.
10159:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10160:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10161:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10162:         $uhome=&homeserver($uname,$udom,'true');
10163:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10164:             return 'error: unable to generate unique course-ID';
10165:         }
10166:     }
10167:     return $uname;
10168: }
10169: 
10170: sub is_course {
10171:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10172:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10173: 
10174:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10175:     my $uhome=&homeserver($cnum,$cdom);
10176:     my $iscourse;
10177:     if (grep { $_ eq $uhome } current_machine_ids()) {
10178:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10179:     } else {
10180:         my $hashid = $cdom.':'.$cnum;
10181:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10182:         unless (defined($cached)) {
10183:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10184:                                         $cnum,undef,undef,'.');
10185:             $iscourse = 0;
10186:             if (exists($courses{$cdom.'_'.$cnum})) {
10187:                 $iscourse = 1;
10188:             }
10189:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10190:         }
10191:     }
10192:     return unless ($iscourse);
10193:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10194: }
10195: 
10196: sub store_userdata {
10197:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10198:     my $result;
10199:     if ($datakey ne '') {
10200:         if (ref($storehash) eq 'HASH') {
10201:             if ($udom eq '' || $uname eq '') {
10202:                 $udom = $env{'user.domain'};
10203:                 $uname = $env{'user.name'};
10204:             }
10205:             my $uhome=&homeserver($uname,$udom);
10206:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10207:                 $result = 'error: no_host';
10208:             } else {
10209:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10210:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10211: 
10212:                 my $namevalue='';
10213:                 foreach my $key (keys(%{$storehash})) {
10214:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10215:                 }
10216:                 $namevalue=~s/\&$//;
10217:                 unless ($namespace eq 'courserequests') {
10218:                     $datakey = &escape($datakey);
10219:                 }
10220:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10221:                                   $namevalue,$uhome);
10222:             }
10223:         } else {
10224:             $result = 'error: data to store was not a hash reference'; 
10225:         }
10226:     } else {
10227:         $result= 'error: invalid requestkey'; 
10228:     }
10229:     return $result;
10230: }
10231: 
10232: # ---------------------------------------------------------- Assign Custom Role
10233: 
10234: sub assigncustomrole {
10235:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10236:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10237:                        $end,$start,$deleteflag,$selfenroll,$context);
10238: }
10239: 
10240: # ----------------------------------------------------------------- Revoke Role
10241: 
10242: sub revokerole {
10243:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10244:     my $now=time;
10245:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10246: }
10247: 
10248: # ---------------------------------------------------------- Revoke Custom Role
10249: 
10250: sub revokecustomrole {
10251:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10252:     my $now=time;
10253:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10254:            $deleteflag,$selfenroll,$context);
10255: }
10256: 
10257: # ------------------------------------------------------------ Disk usage
10258: sub diskusage {
10259:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10260:     $directorypath =~ s/\/$//;
10261:     my $listing=&reply('du2:'.&escape($directorypath).':'
10262:                        .&escape($getpropath).':'.&escape($uname).':'
10263:                        .&escape($udom),homeserver($uname,$udom));
10264:     if ($listing eq 'unknown_cmd') {
10265:         if ($getpropath) {
10266:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10267:         }
10268:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10269:     }
10270:     return $listing;
10271: }
10272: 
10273: sub is_locked {
10274:     my ($file_name, $domain, $user, $which) = @_;
10275:     my @check;
10276:     my $is_locked;
10277:     push (@check,$file_name);
10278:     my %locked = &get('file_permissions',\@check,
10279: 		      $env{'user.domain'},$env{'user.name'});
10280:     my ($tmp)=keys(%locked);
10281:     if ($tmp=~/^error:/) { undef(%locked); }
10282:     
10283:     if (ref($locked{$file_name}) eq 'ARRAY') {
10284:         $is_locked = 'false';
10285:         foreach my $entry (@{$locked{$file_name}}) {
10286:            if (ref($entry) eq 'ARRAY') {
10287:                $is_locked = 'true';
10288:                if (ref($which) eq 'ARRAY') {
10289:                    push(@{$which},$entry);
10290:                } else {
10291:                    last;
10292:                }
10293:            }
10294:        }
10295:     } else {
10296:         $is_locked = 'false';
10297:     }
10298:     return $is_locked;
10299: }
10300: 
10301: sub declutter_portfile {
10302:     my ($file) = @_;
10303:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10304:     return $file;
10305: }
10306: 
10307: # ------------------------------------------------------------- Mark as Read Only
10308: 
10309: sub mark_as_readonly {
10310:     my ($domain,$user,$files,$what) = @_;
10311:     my %current_permissions = &dump('file_permissions',$domain,$user);
10312:     my ($tmp)=keys(%current_permissions);
10313:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10314:     foreach my $file (@{$files}) {
10315: 	$file = &declutter_portfile($file);
10316:         push(@{$current_permissions{$file}},$what);
10317:     }
10318:     &put('file_permissions',\%current_permissions,$domain,$user);
10319:     return;
10320: }
10321: 
10322: # ------------------------------------------------------------Save Selected Files
10323: 
10324: sub save_selected_files {
10325:     my ($user, $path, @files) = @_;
10326:     my $filename = $user."savedfiles";
10327:     my @other_files = &files_not_in_path($user, $path);
10328:     open (OUT,'>',LONCAPA::tempdir().$filename);
10329:     foreach my $file (@files) {
10330:         print (OUT $env{'form.currentpath'}.$file."\n");
10331:     }
10332:     foreach my $file (@other_files) {
10333:         print (OUT $file."\n");
10334:     }
10335:     close (OUT);
10336:     return 'ok';
10337: }
10338: 
10339: sub clear_selected_files {
10340:     my ($user) = @_;
10341:     my $filename = $user."savedfiles";
10342:     open (OUT,'>',LONCAPA::tempdir().$filename);
10343:     print (OUT undef);
10344:     close (OUT);
10345:     return ("ok");    
10346: }
10347: 
10348: sub files_in_path {
10349:     my ($user, $path) = @_;
10350:     my $filename = $user."savedfiles";
10351:     my %return_files;
10352:     open (IN,'<',LONCAPA::tempdir().$filename);
10353:     while (my $line_in = <IN>) {
10354:         chomp ($line_in);
10355:         my @paths_and_file = split (m!/!, $line_in);
10356:         my $file_part = pop (@paths_and_file);
10357:         my $path_part = join ('/', @paths_and_file);
10358:         $path_part.='/';
10359:         my $path_and_file = $path_part.$file_part;
10360:         if ($path_part eq $path) {
10361:             $return_files{$file_part}= 'selected';
10362:         }
10363:     }
10364:     close (IN);
10365:     return (\%return_files);
10366: }
10367: 
10368: # called in portfolio select mode, to show files selected NOT in current directory
10369: sub files_not_in_path {
10370:     my ($user, $path) = @_;
10371:     my $filename = $user."savedfiles";
10372:     my @return_files;
10373:     my $path_part;
10374:     open(IN, '<',LONCAPA::tempdir().$filename);
10375:     while (my $line = <IN>) {
10376:         #ok, I know it's clunky, but I want it to work
10377:         my @paths_and_file = split(m|/|, $line);
10378:         my $file_part = pop(@paths_and_file);
10379:         chomp($file_part);
10380:         my $path_part = join('/', @paths_and_file);
10381:         $path_part .= '/';
10382:         my $path_and_file = $path_part.$file_part;
10383:         if ($path_part ne $path) {
10384:             push(@return_files, ($path_and_file));
10385:         }
10386:     }
10387:     close(OUT);
10388:     return (@return_files);
10389: }
10390: 
10391: #------------------------------Submitted/Handedback Portfolio Files Versioning
10392:  
10393: sub portfiles_versioning {
10394:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10395:     my $portfolio_root = '/userfiles/portfolio';
10396:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10397:     foreach my $file (@{$portfiles}) {
10398:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10399:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10400:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10401:         my $getpropath = 1;
10402:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10403:                                              $stu_name,$getpropath);
10404:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10405:         my $new_answer = 
10406:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10407:         if ($new_answer ne 'problem getting file') {
10408:             push(@{$versioned_portfiles}, $directory.$new_answer);
10409:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10410:                               [$symb,$env{'request.course.id'},'graded']);
10411:         }
10412:     }
10413: }
10414: 
10415: sub get_next_version {
10416:     my ($answer_name, $answer_ext, $dir_list) = @_;
10417:     my $version;
10418:     if (ref($dir_list) eq 'ARRAY') {
10419:         foreach my $row (@{$dir_list}) {
10420:             my ($file) = split(/\&/,$row,2);
10421:             my ($file_name,$file_version,$file_ext) =
10422:                 &file_name_version_ext($file);
10423:             if (($file_name eq $answer_name) &&
10424:                 ($file_ext eq $answer_ext)) {
10425:                      # gets here if filename and extension match,
10426:                      # regardless of version
10427:                 if ($file_version ne '') {
10428:                     # a versioned file is found  so save it for later
10429:                     if ($file_version > $version) {
10430:                         $version = $file_version;
10431:                     }
10432:                 }
10433:             }
10434:         }
10435:     }
10436:     $version ++;
10437:     return($version);
10438: }
10439: 
10440: sub version_selected_portfile {
10441:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10442:     my ($answer_name,$answer_ver,$answer_ext) =
10443:         &file_name_version_ext($file_name);
10444:     my $new_answer;
10445:     $env{'form.copy'} =
10446:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10447:     if($env{'form.copy'} eq '-1') {
10448:         $new_answer = 'problem getting file';
10449:     } else {
10450:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10451:         my $copy_result = 
10452:             &finishuserfileupload($stu_name,$domain,'copy',
10453:                                   '/portfolio'.$directory.$new_answer);
10454:     }
10455:     undef($env{'form.copy'});
10456:     return ($new_answer);
10457: }
10458: 
10459: sub file_name_version_ext {
10460:     my ($file)=@_;
10461:     my @file_parts = split(/\./, $file);
10462:     my ($name,$version,$ext);
10463:     if (@file_parts > 1) {
10464:         $ext=pop(@file_parts);
10465:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10466:             $version=pop(@file_parts);
10467:         }
10468:         $name=join('.',@file_parts);
10469:     } else {
10470:         $name=join('.',@file_parts);
10471:     }
10472:     return($name,$version,$ext);
10473: }
10474: 
10475: #----------------------------------------------Get portfolio file permissions
10476: 
10477: sub get_portfile_permissions {
10478:     my ($domain,$user) = @_;
10479:     my %current_permissions = &dump('file_permissions',$domain,$user);
10480:     my ($tmp)=keys(%current_permissions);
10481:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10482:     return \%current_permissions;
10483: }
10484: 
10485: #---------------------------------------------Get portfolio file access controls
10486: 
10487: sub get_access_controls {
10488:     my ($current_permissions,$group,$file) = @_;
10489:     my %access;
10490:     my $real_file = $file;
10491:     $file =~ s/\.meta$//;
10492:     if (defined($file)) {
10493:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10494:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10495:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10496:             }
10497:         }
10498:     } else {
10499:         foreach my $key (keys(%{$current_permissions})) {
10500:             if ($key =~ /\0accesscontrol$/) {
10501:                 if (defined($group)) {
10502:                     if ($key !~ m-^\Q$group\E/-) {
10503:                         next;
10504:                     }
10505:                 }
10506:                 my ($fullpath) = split(/\0/,$key);
10507:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10508:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10509:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10510:                     }
10511:                 }
10512:             }
10513:         }
10514:     }
10515:     return %access;
10516: }
10517: 
10518: sub modify_access_controls {
10519:     my ($file_name,$changes,$domain,$user)=@_;
10520:     my ($outcome,$deloutcome);
10521:     my %store_permissions;
10522:     my %new_values;
10523:     my %new_control;
10524:     my %translation;
10525:     my @deletions = ();
10526:     my $now = time;
10527:     if (exists($$changes{'activate'})) {
10528:         if (ref($$changes{'activate'}) eq 'HASH') {
10529:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10530:             my $numnew = scalar(@newitems);
10531:             for (my $i=0; $i<$numnew; $i++) {
10532:                 my $newkey = $newitems[$i];
10533:                 my $newid = &Apache::loncommon::get_cgi_id();
10534:                 if ($newkey =~ /^\d+:/) { 
10535:                     $newkey =~ s/^(\d+)/$newid/;
10536:                     $translation{$1} = $newid;
10537:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10538:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10539:                     $translation{$1} = $newid;
10540:                 }
10541:                 $new_values{$file_name."\0".$newkey} = 
10542:                                           $$changes{'activate'}{$newitems[$i]};
10543:                 $new_control{$newkey} = $now;
10544:             }
10545:         }
10546:     }
10547:     my %todelete;
10548:     my %changed_items;
10549:     foreach my $action ('delete','update') {
10550:         if (exists($$changes{$action})) {
10551:             if (ref($$changes{$action}) eq 'HASH') {
10552:                 foreach my $key (keys(%{$$changes{$action}})) {
10553:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10554:                     if ($action eq 'delete') { 
10555:                         $todelete{$itemnum} = 1;
10556:                     } else {
10557:                         $changed_items{$itemnum} = $key;
10558:                     }
10559:                 }
10560:             }
10561:         }
10562:     }
10563:     # get lock on access controls for file.
10564:     my $lockhash = {
10565:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10566:                                                        ':'.$env{'user.domain'},
10567:                    }; 
10568:     my $tries = 0;
10569:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10570:    
10571:     while (($gotlock ne 'ok') && $tries < 10) {
10572:         $tries ++;
10573:         sleep(0.1);
10574:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10575:     }
10576:     if ($gotlock eq 'ok') {
10577:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10578:         my ($tmp)=keys(%curr_permissions);
10579:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10580:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10581:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10582:             if (ref($curr_controls) eq 'HASH') {
10583:                 foreach my $control_item (keys(%{$curr_controls})) {
10584:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10585:                     if (defined($todelete{$itemnum})) {
10586:                         push(@deletions,$file_name."\0".$control_item);
10587:                     } else {
10588:                         if (defined($changed_items{$itemnum})) {
10589:                             $new_control{$changed_items{$itemnum}} = $now;
10590:                             push(@deletions,$file_name."\0".$control_item);
10591:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10592:                         } else {
10593:                             $new_control{$control_item} = $$curr_controls{$control_item};
10594:                         }
10595:                     }
10596:                 }
10597:             }
10598:         }
10599:         my ($group);
10600:         if (&is_course($domain,$user)) {
10601:             ($group,my $file) = split(/\//,$file_name,2);
10602:         }
10603:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10604:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10605:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10606:         #  remove lock
10607:         my @del_lock = ($file_name."\0".'locked_access_records');
10608:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10609:         my $sqlresult =
10610:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10611:                                     $group);
10612:     } else {
10613:         $outcome = "error: could not obtain lockfile\n";  
10614:     }
10615:     return ($outcome,$deloutcome,\%new_values,\%translation);
10616: }
10617: 
10618: sub make_public_indefinitely {
10619:     my (@requrl) = @_;
10620:     return &automated_portfile_access('public',\@requrl);
10621: }
10622: 
10623: sub automated_portfile_access {
10624:     my ($accesstype,$addsref,$delsref,$info) = @_;
10625:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10626:         return 'invalid';
10627:     }
10628:     my %urls;
10629:     if (ref($addsref) eq 'ARRAY') {
10630:         foreach my $requrl (@{$addsref}) {
10631:             if (&is_portfolio_url($requrl)) {
10632:                 unless (exists($urls{$requrl})) {
10633:                     $urls{$requrl} = 'add';
10634:                 }
10635:             }
10636:         }
10637:     }
10638:     if (ref($delsref) eq 'ARRAY') {
10639:         foreach my $requrl (@{$delsref}) { 
10640:             if (&is_portfolio_url($requrl)) {
10641:                 unless (exists($urls{$requrl})) {
10642:                     $urls{$requrl} = 'delete'; 
10643:                 }
10644:             }
10645:         }
10646:     }
10647:     unless (keys(%urls)) {
10648:         return 'invalid';
10649:     }
10650:     my $ip;
10651:     if ($accesstype eq 'ip') {
10652:         if (ref($info) eq 'HASH') {
10653:             if ($info->{'ip'} ne '') {
10654:                 $ip = $info->{'ip'};
10655:             }
10656:         }
10657:         if ($ip eq '') {
10658:             return 'invalid';
10659:         }
10660:     }
10661:     my $errors;
10662:     my $now = time;
10663:     my %current_perms;
10664:     foreach my $requrl (sort(keys(%urls))) {
10665:         my $action;
10666:         if ($urls{$requrl} eq 'add') {
10667:             $action = 'activate';
10668:         } else {
10669:             $action = 'none';
10670:         }
10671:         my $aclnum = 0;
10672:         my (undef,$udom,$unum,$file_name,$group) =
10673:             &parse_portfolio_url($requrl);
10674:         unless (exists($current_perms{$unum.':'.$udom})) {
10675:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10676:         }
10677:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10678:                                                    $group,$file_name);
10679:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10680:             my ($num,$scope,$end,$start) = 
10681:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10682:             if ($scope eq $accesstype) {
10683:                 if (($start <= $now) && ($end == 0)) {
10684:                     if ($accesstype eq 'ip') {
10685:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10686:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10687:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10688:                                     if ($urls{$requrl} eq 'add') {
10689:                                         $action = 'none';
10690:                                         last;
10691:                                     } else {
10692:                                         $action = 'delete';
10693:                                         $aclnum = $num;
10694:                                         last;
10695:                                     }
10696:                                 }
10697:                             }
10698:                         }
10699:                     } elsif ($accesstype eq 'public') {
10700:                         if ($urls{$requrl} eq 'add') {
10701:                             $action = 'none';
10702:                             last;
10703:                         } else {
10704:                             $action = 'delete';
10705:                             $aclnum = $num;
10706:                             last;
10707:                         }
10708:                     }
10709:                 } elsif ($accesstype eq 'public') {
10710:                     $action = 'update';
10711:                     $aclnum = $num;
10712:                     last;
10713:                 }
10714:             }
10715:         }
10716:         if ($action eq 'none') {
10717:             next;
10718:         } else {
10719:             my %changes;
10720:             my $newend = 0;
10721:             my $newstart = $now;
10722:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10723:             $changes{$action}{$newkey} = {
10724:                 type => $accesstype,
10725:                 time => {
10726:                     start => $newstart,
10727:                     end   => $newend,
10728:                 },
10729:             };
10730:             if ($accesstype eq 'ip') {
10731:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10732:             }
10733:             my ($outcome,$deloutcome,$new_values,$translation) =
10734:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10735:             unless ($outcome eq 'ok') {
10736:                 $errors .= $outcome.' ';
10737:             }
10738:         }
10739:     }
10740:     if ($errors) {
10741:         $errors =~ s/\s$//;
10742:         return $errors;
10743:     } else {
10744:         return 'ok';
10745:     }
10746: }
10747: 
10748: #------------------------------------------------------Get Marked as Read Only
10749: 
10750: sub get_marked_as_readonly {
10751:     my ($domain,$user,$what,$group) = @_;
10752:     my $current_permissions = &get_portfile_permissions($domain,$user);
10753:     my @readonly_files;
10754:     my $cmp1=$what;
10755:     if (ref($what)) { $cmp1=join('',@{$what}) };
10756:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10757:         if (defined($group)) {
10758:             if ($file_name !~ m-^\Q$group\E/-) {
10759:                 next;
10760:             }
10761:         }
10762:         if (ref($value) eq "ARRAY"){
10763:             foreach my $stored_what (@{$value}) {
10764:                 my $cmp2=$stored_what;
10765:                 if (ref($stored_what) eq 'ARRAY') {
10766:                     $cmp2=join('',@{$stored_what});
10767:                 }
10768:                 if ($cmp1 eq $cmp2) {
10769:                     push(@readonly_files, $file_name);
10770:                     last;
10771:                 } elsif (!defined($what)) {
10772:                     push(@readonly_files, $file_name);
10773:                     last;
10774:                 }
10775:             }
10776:         }
10777:     }
10778:     return @readonly_files;
10779: }
10780: #-----------------------------------------------------------Get Marked as Read Only Hash
10781: 
10782: sub get_marked_as_readonly_hash {
10783:     my ($current_permissions,$group,$what) = @_;
10784:     my %readonly_files;
10785:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10786:         if (defined($group)) {
10787:             if ($file_name !~ m-^\Q$group\E/-) {
10788:                 next;
10789:             }
10790:         }
10791:         if (ref($value) eq "ARRAY"){
10792:             foreach my $stored_what (@{$value}) {
10793:                 if (ref($stored_what) eq 'ARRAY') {
10794:                     foreach my $lock_descriptor(@{$stored_what}) {
10795:                         if ($lock_descriptor eq 'graded') {
10796:                             $readonly_files{$file_name} = 'graded';
10797:                         } elsif ($lock_descriptor eq 'handback') {
10798:                             $readonly_files{$file_name} = 'handback';
10799:                         } else {
10800:                             if (!exists($readonly_files{$file_name})) {
10801:                                 $readonly_files{$file_name} = 'locked';
10802:                             }
10803:                         }
10804:                     }
10805:                 } 
10806:             }
10807:         } 
10808:     }
10809:     return %readonly_files;
10810: }
10811: # ------------------------------------------------------------ Unmark as Read Only
10812: 
10813: sub unmark_as_readonly {
10814:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10815:     # for portfolio submissions, $what contains [$symb,$crsid] 
10816:     my ($domain,$user,$what,$file_name,$group) = @_;
10817:     $file_name = &declutter_portfile($file_name);
10818:     my $symb_crs = $what;
10819:     if (ref($what)) { $symb_crs=join('',@$what); }
10820:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10821:     my ($tmp)=keys(%current_permissions);
10822:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10823:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10824:     foreach my $file (@readonly_files) {
10825: 	my $clean_file = &declutter_portfile($file);
10826: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10827: 	my $current_locks = $current_permissions{$file};
10828:         my @new_locks;
10829:         my @del_keys;
10830:         if (ref($current_locks) eq "ARRAY"){
10831:             foreach my $locker (@{$current_locks}) {
10832:                 my $compare=$locker;
10833:                 if (ref($locker) eq 'ARRAY') {
10834:                     $compare=join('',@{$locker});
10835:                     if ($compare ne $symb_crs) {
10836:                         push(@new_locks, $locker);
10837:                     }
10838:                 }
10839:             }
10840:             if (scalar(@new_locks) > 0) {
10841:                 $current_permissions{$file} = \@new_locks;
10842:             } else {
10843:                 push(@del_keys, $file);
10844:                 &del('file_permissions',\@del_keys, $domain, $user);
10845:                 delete($current_permissions{$file});
10846:             }
10847:         }
10848:     }
10849:     &put('file_permissions',\%current_permissions,$domain,$user);
10850:     return;
10851: }
10852: 
10853: # ------------------------------------------------------------ Directory lister
10854: 
10855: sub dirlist {
10856:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10857:     $uri=~s/^\///;
10858:     $uri=~s/\/$//;
10859:     my ($udom, $uname);
10860:     if ($getuserdir) {
10861:         $udom = $userdomain;
10862:         $uname = $username;
10863:     } else {
10864:         (undef,$udom,$uname)=split(/\//,$uri);
10865:         if(defined($userdomain)) {
10866:             $udom = $userdomain;
10867:         }
10868:         if(defined($username)) {
10869:             $uname = $username;
10870:         }
10871:     }
10872:     my ($dirRoot,$listing,@listing_results);
10873: 
10874:     $dirRoot = $perlvar{'lonDocRoot'};
10875:     if (defined($getpropath)) {
10876:         $dirRoot = &propath($udom,$uname);
10877:         $dirRoot =~ s/\/$//;
10878:     } elsif (defined($getuserdir)) {
10879:         my $subdir=$uname.'__';
10880:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10881:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10882:                    ."/$udom/$subdir/$uname";
10883:     } elsif (defined($alternateRoot)) {
10884:         $dirRoot = $alternateRoot;
10885:     }
10886: 
10887:     if($udom) {
10888:         if($uname) {
10889:             my $uhome = &homeserver($uname,$udom);
10890:             if ($uhome eq 'no_host') {
10891:                 return ([],'no_host');
10892:             }
10893:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10894:                               .$getuserdir.':'.&escape($dirRoot)
10895:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10896:             if ($listing eq 'unknown_cmd') {
10897:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10898:             } else {
10899:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10900:             }
10901:             if ($listing eq 'unknown_cmd') {
10902:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10903:                 @listing_results = split(/:/,$listing);
10904:             } else {
10905:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10906:             }
10907:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10908:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10909:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10910:                 return ([],$listing);
10911:             } else {
10912:                 return (\@listing_results);
10913:             }
10914:         } elsif(!$alternateRoot) {
10915:             my (%allusers,%listerror);
10916: 	    my %servers = &get_servers($udom,'library');
10917:  	    foreach my $tryserver (keys(%servers)) {
10918:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10919:                                   &escape($udom),$tryserver);
10920:                 if ($listing eq 'unknown_cmd') {
10921: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10922: 				      $udom, $tryserver);
10923:                 } else {
10924:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10925:                 }
10926: 		if ($listing eq 'unknown_cmd') {
10927: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10928: 				      $udom, $tryserver);
10929: 		    @listing_results = split(/:/,$listing);
10930: 		} else {
10931: 		    @listing_results =
10932: 			map { &unescape($_); } split(/:/,$listing);
10933: 		}
10934:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10935:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10936:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10937:                     $listerror{$tryserver} = $listing;
10938:                 } else {
10939: 		    foreach my $line (@listing_results) {
10940: 			my ($entry) = split(/&/,$line,2);
10941: 			$allusers{$entry} = 1;
10942: 		    }
10943: 		}
10944:             }
10945:             my @alluserslist=();
10946:             foreach my $user (sort(keys(%allusers))) {
10947:                 push(@alluserslist,$user.'&user');
10948:             }
10949: 
10950:             if (!%listerror) {
10951:                 # no errors
10952:                 return (\@alluserslist);
10953:             } elsif (scalar(keys(%servers)) == 1) {
10954:                 # one library server, one error 
10955:                 my ($key) = keys(%listerror);
10956:                 return (\@alluserslist, $listerror{$key});
10957:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10958:                 # con_lost indicates that we might miss data from at least one
10959:                 # library server
10960:                 return (\@alluserslist, 'con_lost');
10961:             } else {
10962:                 # multiple library servers and no con_lost -> data should be
10963:                 # complete. 
10964:                 return (\@alluserslist);
10965:             }
10966: 
10967:         } else {
10968:             return ([],'missing username');
10969:         }
10970:     } elsif(!defined($getpropath)) {
10971:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10972:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10973:         return (\@all_domains);
10974:     } else {
10975:         return ([],'missing domain');
10976:     }
10977: }
10978: 
10979: # --------------------------------------------- GetFileTimestamp
10980: # This function utilizes dirlist and returns the date stamp for
10981: # when it was last modified.  It will also return an error of -1
10982: # if an error occurs
10983: 
10984: sub GetFileTimestamp {
10985:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10986:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10987:     $studentName   = &LONCAPA::clean_username($studentName);
10988:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10989:                                     undef,$getuserdir);
10990:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10991:         return -1;
10992:     }
10993:     if (ref($fileref) eq 'ARRAY') {
10994:         my @stats = split('&',$fileref->[0]);
10995:         # @stats contains first the filename, then the stat output
10996:         return $stats[10]; # so this is 10 instead of 9.
10997:     } else {
10998:         return -1;
10999:     }
11000: }
11001: 
11002: sub stat_file {
11003:     my ($uri) = @_;
11004:     $uri = &clutter_with_no_wrapper($uri);
11005: 
11006:     my ($udom,$uname,$file);
11007:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11008: 	($udom,$uname,$file) =
11009: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11010: 	$file = 'userfiles/'.$file;
11011:     }
11012:     if ($uri =~ m-^/res/-) {
11013: 	($udom,$uname) = 
11014: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11015: 	$file = $uri;
11016:     }
11017: 
11018:     if (!$udom || !$uname || !$file) {
11019: 	# unable to handle the uri
11020: 	return ();
11021:     }
11022:     my $getpropath;
11023:     if ($file =~ /^userfiles\//) {
11024:         $getpropath = 1;
11025:     }
11026:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11027:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11028:         return ();
11029:     } else {
11030:         if (ref($listref) eq 'ARRAY') {
11031:             my @stats = split('&',$listref->[0]);
11032: 	    shift(@stats); #filename is first
11033: 	    return @stats;
11034:         }
11035:     }
11036:     return ();
11037: }
11038: 
11039: # --------------------------------------------------------- recursedirs
11040: # Recursive function to traverse either a specific user's Authoring Space
11041: # or corresponding Published Resource Space, and populate the hash ref:
11042: # $dirhashref with URLs of all directories, and if $filehashref hash
11043: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11044: # or .rights files in resource space, and .meta, .save, .log, and .bak
11045: # files in Authoring Space.
11046: #
11047: # Inputs:
11048: #
11049: # $is_home - true if current server is home server for user's space
11050: # $context - either: priv, or res respectively for Authoring or Resource Space.
11051: # $docroot - Document root (i.e., /home/httpd/html
11052: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11053: # $relpath - Current path (relative to top level).
11054: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11055: # $filehashref - reference to hash to populate with URLs of files (Optional)
11056: #
11057: # Returns: nothing
11058: #
11059: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11060: #
11061: # Currently used by interface/londocs.pm to create linked select boxes for
11062: # directory and filename to import a Course "Author" resource into a course, and
11063: # also to create linked select boxes for Authoring Space and Directory to choose
11064: # save location for creation of a new "standard" problem from the Course Editor.
11065: #
11066: 
11067: sub recursedirs {
11068:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11069:     return unless (ref($dirhashref) eq 'HASH');
11070:     my $currpath = $docroot.$toppath;
11071:     if ($relpath) {
11072:         $currpath .= "/$relpath";
11073:     }
11074:     my $savefile;
11075:     if (ref($filehashref)) {
11076:         $savefile = 1;
11077:     }
11078:     if ($is_home) {
11079:         if (opendir(my $dirh,$currpath)) {
11080:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11081:                 next if ($item eq '');
11082:                 if (-d "$currpath/$item") {
11083:                     my $newpath;
11084:                     if ($relpath) {
11085:                         $newpath = "$relpath/$item";
11086:                     } else {
11087:                         $newpath = $item;
11088:                     }
11089:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11090:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11091:                 } elsif ($savefile) {
11092:                     if ($context eq 'priv') {
11093:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11094:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11095:                         }
11096:                     } else {
11097:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11098:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11099:                         }
11100:                     }
11101:                 }
11102:             }
11103:             closedir($dirh);
11104:         }
11105:     } else {
11106:         my ($dirlistref,$listerror) =
11107:             &dirlist($toppath.$relpath);
11108:         my @dir_lines;
11109:         my $dirptr=16384;
11110:         if (ref($dirlistref) eq 'ARRAY') {
11111:             foreach my $dir_line (sort
11112:                               {
11113:                                   my ($afile)=split('&',$a,2);
11114:                                   my ($bfile)=split('&',$b,2);
11115:                                   return (lc($afile) cmp lc($bfile));
11116:                               } (@{$dirlistref})) {
11117:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11118:                     split(/\&/,$dir_line,16);
11119:                 $item =~ s/\s+$//;
11120:                 next if (($item =~ /^\.\.?$/) || ($obs));
11121:                 if ($dirptr&$testdir) {
11122:                     my $newpath;
11123:                     if ($relpath) {
11124:                         $newpath = "$relpath/$item";
11125:                     } else {
11126:                         $relpath = '/';
11127:                         $newpath = $item;
11128:                     }
11129:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11130:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11131:                 } elsif ($savefile) {
11132:                     if ($context eq 'priv') {
11133:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11134:                             $filehashref->{$relpath}{$item} = 1;
11135:                         }
11136:                     } else {
11137:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11138:                             $filehashref->{$relpath}{$item} = 1;
11139:                         }
11140:                     }
11141:                 }
11142:             }
11143:         }
11144:     }
11145:     return;
11146: }
11147: 
11148: # -------------------------------------------------------- Value of a Condition
11149: 
11150: # gets the value of a specific preevaluated condition
11151: #    stored in the string  $env{user.state.<cid>}
11152: # or looks up a condition reference in the bighash and if if hasn't
11153: # already been evaluated recurses into docondval to get the value of
11154: # the condition, then memoizing it to 
11155: #   $env{user.state.<cid>.<condition>}
11156: sub directcondval {
11157:     my $number=shift;
11158:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11159: 	&Apache::lonuserstate::evalstate();
11160:     }
11161:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11162: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11163:     } elsif ($number =~ /^_/) {
11164: 	my $sub_condition;
11165: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11166: 		&GDBM_READER(),0640)) {
11167: 	    $sub_condition=$bighash{'conditions'.$number};
11168: 	    untie(%bighash);
11169: 	}
11170: 	my $value = &docondval($sub_condition);
11171: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11172: 	return $value;
11173:     }
11174:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11175:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11176:     } else {
11177:        return 2;
11178:     }
11179: }
11180: 
11181: # get the collection of conditions for this resource
11182: sub condval {
11183:     my $condidx=shift;
11184:     my $allpathcond='';
11185:     foreach my $cond (split(/\|/,$condidx)) {
11186: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11187: 	    $allpathcond.=
11188: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11189: 	}
11190:     }
11191:     $allpathcond=~s/\|$//;
11192:     return &docondval($allpathcond);
11193: }
11194: 
11195: #evaluates an expression of conditions
11196: sub docondval {
11197:     my ($allpathcond) = @_;
11198:     my $result=0;
11199:     if ($env{'request.course.id'}
11200: 	&& defined($allpathcond)) {
11201: 	my $operand='|';
11202: 	my @stack;
11203: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11204: 	    if ($chunk eq '(') {
11205: 		push @stack,($operand,$result);
11206: 	    } elsif ($chunk eq ')') {
11207: 		my $before=pop @stack;
11208: 		if (pop @stack eq '&') {
11209: 		    $result=$result>$before?$before:$result;
11210: 		} else {
11211: 		    $result=$result>$before?$result:$before;
11212: 		}
11213: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11214: 		$operand=$chunk;
11215: 	    } else {
11216: 		my $new=directcondval($chunk);
11217: 		if ($operand eq '&') {
11218: 		    $result=$result>$new?$new:$result;
11219: 		} else {
11220: 		    $result=$result>$new?$result:$new;
11221: 		}
11222: 	    }
11223: 	}
11224:     }
11225:     return $result;
11226: }
11227: 
11228: # ---------------------------------------------------- Devalidate courseresdata
11229: 
11230: sub devalidatecourseresdata {
11231:     my ($coursenum,$coursedomain)=@_;
11232:     my $hashid=$coursenum.':'.$coursedomain;
11233:     &devalidate_cache_new('courseres',$hashid);
11234: }
11235: 
11236: 
11237: # --------------------------------------------------- Course Resourcedata Query
11238: #
11239: #  Parameters:
11240: #      $coursenum    - Number of the course.
11241: #      $coursedomain - Domain at which the course was created.
11242: #  Returns:
11243: #     A hash of the course parameters along (I think) with timestamps
11244: #     and version info.
11245: 
11246: sub get_courseresdata {
11247:     my ($coursenum,$coursedomain)=@_;
11248:     my $coursehom=&homeserver($coursenum,$coursedomain);
11249:     my $hashid=$coursenum.':'.$coursedomain;
11250:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11251:     my %dumpreply;
11252:     unless (defined($cached)) {
11253: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11254: 	$result=\%dumpreply;
11255: 	my ($tmp) = keys(%dumpreply);
11256: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11257: 	    &do_cache_new('courseres',$hashid,$result,600);
11258: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11259: 	    return $tmp;
11260: 	} elsif ($tmp =~ /^(error)/) {
11261: 	    $result=undef;
11262: 	    &do_cache_new('courseres',$hashid,$result,600);
11263: 	}
11264:     }
11265:     return $result;
11266: }
11267: 
11268: sub devalidateuserresdata {
11269:     my ($uname,$udom)=@_;
11270:     my $hashid="$udom:$uname";
11271:     &devalidate_cache_new('userres',$hashid);
11272: }
11273: 
11274: sub get_userresdata {
11275:     my ($uname,$udom)=@_;
11276:     #most student don\'t have any data set, check if there is some data
11277:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11278: 
11279:     my $hashid="$udom:$uname";
11280:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11281:     if (!defined($cached)) {
11282: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11283: 	$result=\%resourcedata;
11284: 	&do_cache_new('userres',$hashid,$result,600);
11285:     }
11286:     my ($tmp)=keys(%$result);
11287:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11288: 	return $result;
11289:     }
11290:     #error 2 occurs when the .db doesn't exist
11291:     if ($tmp!~/error: 2 /) {
11292:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11293: 	    &logthis("<font color=\"blue\">WARNING:".
11294: 		     " Trying to get resource data for ".
11295: 		     $uname." at ".$udom.": ".
11296: 		     $tmp."</font>");
11297:         }
11298:     } elsif ($tmp=~/error: 2 /) {
11299: 	#&EXT_cache_set($udom,$uname);
11300: 	&do_cache_new('userres',$hashid,undef,600);
11301: 	undef($tmp); # not really an error so don't send it back
11302:     }
11303:     return $tmp;
11304: }
11305: #----------------------------------------------- resdata - return resource data
11306: #  Purpose:
11307: #    Return resource data for either users or for a course.
11308: #  Parameters:
11309: #     $name      - Course/user name.
11310: #     $domain    - Name of the domain the user/course is registered on.
11311: #     $type      - Type of thing $name is (must be 'course' or 'user')
11312: #     $mapp      - decluttered URL of enclosing map  
11313: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11314: #     $recurseup - Ref to array of map URLs, starting with map containing
11315: #                  $mapp up through hierarchy of nested maps to top level map.  
11316: #     $courseid  - CourseID (first part of param identifier).
11317: #     $modifier  - Middle part of param identifier.
11318: #     $what      - Last part of param identifier.
11319: #     @which     - Array of names of resources desired.
11320: #  Returns:
11321: #     The value of the first reasource in @which that is found in the
11322: #     resource hash.
11323: #  Exceptional Conditions:
11324: #     If the $type passed in is not valid (not the string 'course' or 
11325: #     'user', an undefined  reference is returned.
11326: #     If none of the resources are found, an undef is returned
11327: sub resdata {
11328:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11329:         $modifier,$what,@which)=@_;
11330:     my $result;
11331:     if ($type eq 'course') {
11332: 	$result=&get_courseresdata($name,$domain);
11333:     } elsif ($type eq 'user') {
11334: 	$result=&get_userresdata($name,$domain);
11335:     }
11336:     if (!ref($result)) { return $result; }    
11337:     foreach my $item (@which) {
11338:         if ($item->[1] eq 'course') {
11339:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11340:                 unless ($$recursed) {
11341:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11342:                     $$recursed = 1;
11343:                 }
11344:                 foreach my $item (@${recurseup}) {
11345:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11346:                     last if (defined($result->{$norecursechk}));
11347:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11348:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11349:                 }
11350:             }
11351:         }
11352:         if (defined($result->{$item->[0]})) {
11353: 	    return [$result->{$item->[0]},$item->[1]];
11354: 	}
11355:     }
11356:     return undef;
11357: }
11358: 
11359: sub get_domain_lti {
11360:     my ($cdom,$context) = @_;
11361:     my ($name,%lti);
11362:     if ($context eq 'consumer') {
11363:         $name = 'ltitools';
11364:     } elsif ($context eq 'provider') {
11365:         $name = 'lti';
11366:     } else {
11367:         return %lti;
11368:     }
11369:     my ($result,$cached)=&is_cached_new($name,$cdom);
11370:     if (defined($cached)) {
11371:         if (ref($result) eq 'HASH') {
11372:             %lti = %{$result};
11373:         }
11374:     } else {
11375:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11376:         if (ref($domconfig{$name}) eq 'HASH') {
11377:             %lti = %{$domconfig{$name}};
11378:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11379:             if (ref($encdomconfig{$name}) eq 'HASH') {
11380:                 foreach my $id (keys(%lti)) {
11381:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11382:                         foreach my $item ('key','secret') {
11383:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11384:                         }
11385:                     }
11386:                 }
11387:             }
11388:         }
11389:         my $cachetime = 24*60*60;
11390:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11391:     }
11392:     return %lti;
11393: }
11394: 
11395: sub get_numsuppfiles {
11396:     my ($cnum,$cdom,$ignorecache)=@_;
11397:     my $hashid=$cnum.':'.$cdom;
11398:     my ($suppcount,$cached);
11399:     unless ($ignorecache) {
11400:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11401:     }
11402:     unless (defined($cached)) {
11403:         my $chome=&homeserver($cnum,$cdom);
11404:         unless ($chome eq 'no_host') {
11405:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11406:             my $suppmap = 'supplemental.sequence';
11407:             ($suppcount,$supptools,$errors) =
11408:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11409:                                                          $supptools,$errors);
11410:         }
11411:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11412:     }
11413:     return $suppcount;
11414: }
11415: 
11416: #
11417: # EXT resource caching routines
11418: #
11419: 
11420: {
11421: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11422: #
11423: # The course for which we cache
11424: my $cachedmapkey='';
11425: # The cached recursive maps for this course
11426: my %cachedmaps=();
11427: # When this was last done
11428: my $cachedmaptime='';
11429: 
11430: sub clear_EXT_cache_status {
11431:     &delenv('cache.EXT.');
11432: }
11433: 
11434: sub EXT_cache_status {
11435:     my ($target_domain,$target_user) = @_;
11436:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11437:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11438:         # We know already the user has no data
11439:         return 1;
11440:     } else {
11441:         return 0;
11442:     }
11443: }
11444: 
11445: sub EXT_cache_set {
11446:     my ($target_domain,$target_user) = @_;
11447:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11448:     #&appenv({$cachename => time});
11449: }
11450: 
11451: # --------------------------------------------------------- Value of a Variable
11452: sub EXT {
11453: 
11454:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11455:     unless ($varname) { return ''; }
11456:     #get real user name/domain, courseid and symb
11457:     my $courseid;
11458:     my $publicuser;
11459:     if ($symbparm) {
11460: 	$symbparm=&get_symb_from_alias($symbparm);
11461:     }
11462:     if (!($uname && $udom)) {
11463:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11464:       if (!$symbparm) {	$symbparm=$cursymb; }
11465:     } else {
11466: 	$courseid=$env{'request.course.id'};
11467:     }
11468:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11469:     my $rest;
11470:     if (defined($therest[0])) {
11471:        $rest=join('.',@therest);
11472:     } else {
11473:        $rest='';
11474:     }
11475: 
11476:     my $qualifierrest=$qualifier;
11477:     if ($rest) { $qualifierrest.='.'.$rest; }
11478:     my $spacequalifierrest=$space;
11479:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11480:     if ($realm eq 'user') {
11481: # --------------------------------------------------------------- user.resource
11482: 	if ($space eq 'resource') {
11483: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11484: 		  || defined($Apache::lonhomework::parsing_a_task))
11485: 		 &&
11486: 		 ($symbparm eq &symbread()) ) {	
11487: 		# if we are in the middle of processing the resource the
11488: 		# get the value we are planning on committing
11489:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11490:                     return $Apache::lonhomework::results{$qualifierrest};
11491:                 } else {
11492:                     return $Apache::lonhomework::history{$qualifierrest};
11493:                 }
11494: 	    } else {
11495: 		my %restored;
11496: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11497: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11498: 		} else {
11499: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11500: 		}
11501: 		return $restored{$qualifierrest};
11502: 	    }
11503: # ----------------------------------------------------------------- user.access
11504:         } elsif ($space eq 'access') {
11505: 	    # FIXME - not supporting calls for a specific user
11506:             return &allowed($qualifier,$rest);
11507: # ------------------------------------------ user.preferences, user.environment
11508:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11509: 	    if (($uname eq $env{'user.name'}) &&
11510: 		($udom eq $env{'user.domain'})) {
11511: 		return $env{join('.',('environment',$qualifierrest))};
11512: 	    } else {
11513: 		my %returnhash;
11514: 		if (!$publicuser) {
11515: 		    %returnhash=&userenvironment($udom,$uname,
11516: 						 $qualifierrest);
11517: 		}
11518: 		return $returnhash{$qualifierrest};
11519: 	    }
11520: # ----------------------------------------------------------------- user.course
11521:         } elsif ($space eq 'course') {
11522: 	    # FIXME - not supporting calls for a specific user
11523:             return $env{join('.',('request.course',$qualifier))};
11524: # ------------------------------------------------------------------- user.role
11525:         } elsif ($space eq 'role') {
11526: 	    # FIXME - not supporting calls for a specific user
11527:             my ($role,$where)=split(/\./,$env{'request.role'});
11528:             if ($qualifier eq 'value') {
11529: 		return $role;
11530:             } elsif ($qualifier eq 'extent') {
11531:                 return $where;
11532:             }
11533: # ----------------------------------------------------------------- user.domain
11534:         } elsif ($space eq 'domain') {
11535:             return $udom;
11536: # ------------------------------------------------------------------- user.name
11537:         } elsif ($space eq 'name') {
11538:             return $uname;
11539: # ---------------------------------------------------- Any other user namespace
11540:         } else {
11541: 	    my %reply;
11542: 	    if (!$publicuser) {
11543: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11544: 	    }
11545: 	    return $reply{$qualifierrest};
11546:         }
11547:     } elsif ($realm eq 'query') {
11548: # ---------------------------------------------- pull stuff out of query string
11549:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11550: 						[$spacequalifierrest]);
11551: 	return $env{'form.'.$spacequalifierrest}; 
11552:    } elsif ($realm eq 'request') {
11553: # ------------------------------------------------------------- request.browser
11554:         if ($space eq 'browser') {
11555:             return $env{'browser.'.$qualifier};
11556: # ------------------------------------------------------------ request.filename
11557:         } else {
11558:             return $env{'request.'.$spacequalifierrest};
11559:         }
11560:     } elsif ($realm eq 'course') {
11561: # ---------------------------------------------------------- course.description
11562:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11563:     } elsif ($realm eq 'resource') {
11564: 
11565: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11566: 	    if (!$symbparm) { $symbparm=&symbread(); }
11567: 	}
11568: 
11569:         if ($qualifier eq '') {
11570: 	    if ($space eq 'title') {
11571: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11572: 	        return &gettitle($symbparm);
11573: 	    }
11574: 	
11575: 	    if ($space eq 'map') {
11576: 	        my ($map) = &decode_symb($symbparm);
11577: 	        return &symbread($map);
11578: 	    }
11579:             if ($space eq 'maptitle') {
11580:                 my ($map) = &decode_symb($symbparm);
11581:                 return &gettitle($map);
11582:             }
11583: 	    if ($space eq 'filename') {
11584: 	        if ($symbparm) {
11585: 		    return &clutter((&decode_symb($symbparm))[2]);
11586: 	        }
11587: 	        return &hreflocation('',$env{'request.filename'});
11588: 	    }
11589: 
11590:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11591:                 if ($space eq 'visibleparts') {
11592:                     my $navmap = Apache::lonnavmaps::navmap->new();
11593:                     my $item;
11594:                     if (ref($navmap)) {
11595:                         my $res = $navmap->getBySymb($symbparm);
11596:                         my $parts = $res->parts();
11597:                         if (ref($parts) eq 'ARRAY') {
11598:                             $item = join(',',@{$parts});
11599:                         }
11600:                         undef($navmap);
11601:                     }
11602:                     return $item;
11603:                 }
11604:             }
11605:         }
11606: 
11607: 	my ($section, $group, @groups, @recurseup, $recursed);
11608: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11609:         if (($courseid eq '') && ($cid)) {
11610:             $courseid = $cid;
11611:         }
11612: 	if (($symbparm && $courseid) && 
11613: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11614: 
11615: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11616: 
11617: # ----------------------------------------------------- Cascading lookup scheme
11618: 	    my $symbp=$symbparm;
11619: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11620: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11621:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11622: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11623: 	    if (($env{'user.name'} eq $uname) &&
11624: 		($env{'user.domain'} eq $udom)) {
11625: 		$section=$env{'request.course.sec'};
11626:                 @groups = split(/:/,$env{'request.course.groups'});  
11627:                 @groups=&sort_course_groups($courseid,@groups); 
11628: 	    } else {
11629: 		if (! defined($usection)) {
11630: 		    $section=&getsection($udom,$uname,$courseid);
11631: 		} else {
11632: 		    $section = $usection;
11633: 		}
11634:                 @groups = &get_users_groups($udom,$uname,$courseid);
11635: 	    }
11636: 
11637: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11638: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11639:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11640: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11641: 
11642: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11643: 	    my $courselevelr=$courseid.'.'.$symbparm;
11644:             $courseleveli=$courseid.'.'.$recurseparm;
11645: 	    $courselevelm=$courseid.'.'.$mapparm;
11646: 
11647: # ----------------------------------------------------------- first, check user
11648: 
11649: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11650:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11651: 				       ([$courselevelr,'resource'],
11652: 					[$courselevelm,'map'     ],
11653:                                         [$courseleveli,'map'     ],
11654: 					[$courselevel, 'course'  ]));
11655: 	    if (defined($userreply)) { return &get_reply($userreply); }
11656: 
11657: # ------------------------------------------------ second, check some of course
11658:             my $coursereply;
11659:             if (@groups > 0) {
11660:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11661:                                        $recurseparm,$mapparm,$spacequalifierrest,
11662:                                        $mapp,\$recursed,\@recurseup);
11663:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11664:             }
11665: 
11666: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11667: 				  $env{'course.'.$courseid.'.domain'},
11668: 				  'course',$mapp,\$recursed,\@recurseup,
11669:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11670: 				  ([$seclevelr,   'resource'],
11671: 				   [$seclevelm,   'map'     ],
11672:                                    [$secleveli,   'map'     ],
11673: 				   [$seclevel,    'course'  ],
11674: 				   [$courselevelr,'resource']));
11675: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11676: 
11677: # ------------------------------------------------------ third, check map parms
11678: 	    my %parmhash=();
11679: 	    my $thisparm='';
11680: 	    if (tie(%parmhash,'GDBM_File',
11681: 		    $env{'request.course.fn'}.'_parms.db',
11682: 		    &GDBM_READER(),0640)) {
11683: 		$thisparm=$parmhash{$symbparm};
11684: 		untie(%parmhash);
11685: 	    }
11686: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11687: 	}
11688: # ------------------------------------------ fourth, look in resource metadata
11689:  
11690:         my $what = $spacequalifierrest;
11691: 	$what=~s/\./\_/;
11692: 	my $filename;
11693: 	if (!$symbparm) { $symbparm=&symbread(); }
11694: 	if ($symbparm) {
11695: 	    $filename=(&decode_symb($symbparm))[2];
11696: 	} else {
11697: 	    $filename=$env{'request.filename'};
11698: 	}
11699:         my $toolsymb;
11700:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11701:             $toolsymb = $symbparm;
11702:         }
11703: 	my $metadata=&metadata($filename,$what,$toolsymb);
11704: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11705: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11706: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11707: 
11708: # ----------------------------------------------- fifth, look in rest of course
11709: 	if ($symbparm && defined($courseid) && 
11710: 	    $courseid eq $env{'request.course.id'}) {
11711: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11712: 				     $env{'course.'.$courseid.'.domain'},
11713: 				     'course',$mapp,\$recursed,\@recurseup,
11714:                                      $courseid,'.',$spacequalifierrest,
11715: 				     ([$courselevelm,'map'   ],
11716:                                       [$courseleveli,'map'   ],
11717: 				      [$courselevel, 'course']));
11718: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11719: 	}
11720: # ------------------------------------------------------------------ Cascade up
11721: 	unless ($space eq '0') {
11722: 	    my @parts=split(/_/,$space);
11723: 	    my $id=pop(@parts);
11724: 	    my $part=join('_',@parts);
11725: 	    if ($part eq '') { $part='0'; }
11726: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11727: 				 $symbparm,$udom,$uname,$section,1);
11728: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11729: 	}
11730: 	if ($recurse) { return undef; }
11731: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11732: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11733: # ---------------------------------------------------- Any other user namespace
11734:     } elsif ($realm eq 'environment') {
11735: # ----------------------------------------------------------------- environment
11736: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11737: 	    return $env{'environment.'.$spacequalifierrest};
11738: 	} else {
11739: 	    if ($uname eq 'anonymous' && $udom eq '') {
11740: 		return '';
11741: 	    }
11742: 	    my %returnhash=&userenvironment($udom,$uname,
11743: 					    $spacequalifierrest);
11744: 	    return $returnhash{$spacequalifierrest};
11745: 	}
11746:     } elsif ($realm eq 'system') {
11747: # ----------------------------------------------------------------- system.time
11748: 	if ($space eq 'time') {
11749: 	    return time;
11750:         }
11751:     } elsif ($realm eq 'server') {
11752: # ----------------------------------------------------------------- system.time
11753: 	if ($space eq 'name') {
11754: 	    return $ENV{'SERVER_NAME'};
11755:         }
11756:     }
11757:     return '';
11758: }
11759: 
11760: sub get_reply {
11761:     my ($reply_value) = @_;
11762:     if (ref($reply_value) eq 'ARRAY') {
11763:         if (wantarray) {
11764: 	    return @$reply_value;
11765:         }
11766:         return $reply_value->[0];
11767:     } else {
11768:         return $reply_value;
11769:     }
11770: }
11771: 
11772: sub check_group_parms {
11773:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11774:         $recursed,$recurseupref) = @_;
11775:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11776:                   [$what,'course']);
11777:     my $coursereply;
11778:     foreach my $group (@{$groups}) {
11779:         my @groupitems = ();
11780:         foreach my $level (@levels) {
11781:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11782:              push(@groupitems,[$item,$level->[1]]);
11783:         }
11784:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11785:                                    $env{'course.'.$courseid.'.domain'},
11786:                                    'course',$mapp,$recursed,$recurseupref,
11787:                                    $courseid,'.['.$group.'].',$what,
11788:                                    @groupitems);
11789:         last if (defined($coursereply));
11790:     }
11791:     return $coursereply;
11792: }
11793: 
11794: sub get_map_hierarchy {
11795:     my ($mapname,$courseid) = @_;
11796:     my @recurseup = ();
11797:     if ($mapname) {
11798:         if (($cachedmapkey eq $courseid) &&
11799:             (abs($cachedmaptime-time)<5)) {
11800:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11801:                 return @{$cachedmaps{$mapname}};
11802:             }
11803:         }
11804:         my $navmap = Apache::lonnavmaps::navmap->new();
11805:         if (ref($navmap)) {
11806:             @recurseup = $navmap->recurseup_maps($mapname);
11807:             undef($navmap);
11808:             $cachedmaps{$mapname} = \@recurseup;
11809:             $cachedmaptime=time;
11810:             $cachedmapkey=$courseid;
11811:         }
11812:     }
11813:     return @recurseup;
11814: }
11815: 
11816: }
11817: 
11818: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11819:     my ($courseid,@groups) = @_;
11820:     @groups = sort(@groups);
11821:     return @groups;
11822: }
11823: 
11824: sub packages_tab_default {
11825:     my ($uri,$varname,$toolsymb)=@_;
11826:     my (undef,$part,$name)=split(/\./,$varname);
11827: 
11828:     my (@extension,@specifics,$do_default);
11829:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11830: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11831: 	if ($pack_type eq 'default') {
11832: 	    $do_default=1;
11833: 	} elsif ($pack_type eq 'extension') {
11834: 	    push(@extension,[$package,$pack_type,$pack_part]);
11835: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11836: 	    # only look at packages defaults for packages that this id is
11837: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11838: 	}
11839:     }
11840:     # first look for a package that matches the requested part id
11841:     foreach my $package (@specifics) {
11842: 	my (undef,$pack_type,$pack_part)=@{$package};
11843: 	next if ($pack_part ne $part);
11844: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11845: 	    return $packagetab{"$pack_type&$name&default"};
11846: 	}
11847:     }
11848:     # look for any possible matching non extension_ package
11849:     foreach my $package (@specifics) {
11850: 	my (undef,$pack_type,$pack_part)=@{$package};
11851: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11852: 	    return $packagetab{"$pack_type&$name&default"};
11853: 	}
11854: 	if ($pack_type eq 'part') { $pack_part='0'; }
11855: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11856: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11857: 	}
11858:     }
11859:     # look for any posible extension_ match
11860:     foreach my $package (@extension) {
11861: 	my ($package,$pack_type)=@{$package};
11862: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11863: 	    return $packagetab{"$pack_type&$name&default"};
11864: 	}
11865: 	if (defined($packagetab{$package."&$name&default"})) {
11866: 	    return $packagetab{$package."&$name&default"};
11867: 	}
11868:     }
11869:     # look for a global default setting
11870:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11871: 	return $packagetab{"default&$name&default"};
11872:     }
11873:     return undef;
11874: }
11875: 
11876: sub add_prefix_and_part {
11877:     my ($prefix,$part)=@_;
11878:     my $keyroot;
11879:     if (defined($prefix) && $prefix !~ /^__/) {
11880: 	# prefix that has a part already
11881: 	$keyroot=$prefix;
11882:     } elsif (defined($prefix)) {
11883: 	# prefix that is missing a part
11884: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11885:     } else {
11886: 	# no prefix at all
11887: 	if (defined($part)) { $keyroot='_'.$part; }
11888:     }
11889:     return $keyroot;
11890: }
11891: 
11892: # ---------------------------------------------------------------- Get metadata
11893: 
11894: my %metaentry;
11895: my %importedpartids;
11896: my %importedrespids;
11897: sub metadata {
11898:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11899:     $uri=&declutter($uri);
11900:     # if it is a non metadata possible uri return quickly
11901:     if (($uri eq '') || 
11902: 	(($uri =~ m|^/*adm/|) && 
11903: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11904:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11905: 	return undef;
11906:     }
11907:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11908: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11909: 	return undef;
11910:     }
11911:     my $filename=$uri;
11912:     $uri=~s/\.meta$//;
11913: #
11914: # Is the metadata already cached?
11915: # Look at timestamp of caching
11916: # Everything is cached by the main uri, libraries are never directly cached
11917: #
11918:     if (!defined($liburi)) {
11919: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11920: 	if (defined($cached)) { return $result->{':'.$what}; }
11921:     }
11922: 
11923: #
11924: # If the uri is for an external tool the file from
11925: # which metadata should be retrieved depends on whether
11926: # the tool had been configured to be gradable (set in the Course
11927: # Editor or Resource Editor).
11928: #
11929: # If a valid symb has been included as the third arg in the call
11930: # to &metadata() that can be used to retrieve the value of
11931: # parameter_0_gradable set for the resource, and included in the
11932: # uploaded map containing the tool. The value is retrieved via
11933: # &EXT(), if a valid symb is available.  Otherwise the value of
11934: # gradable in the exttool_$marker.db file for the tool instance
11935: # is retrieved via &get().
11936: #
11937: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11938: # hiddenresource and encrypturl (during course initialization)
11939: # the map-level parameter for resource.0.gradable included in the 
11940: # uploaded map containing the tool will not yet have been stored
11941: # in the user_course_parms.db file for the user's session, so in 
11942: # this case fall back to retrieving gradable status from the
11943: # exttool_$marker.db file.
11944: #
11945: # In order to avoid an infinite loop, &metadata() will return
11946: # before a call to &EXT(), if the uri is for an external tool
11947: # and the $what for which metadata is being requested is
11948: # parameter_0_gradable or 0_gradable.
11949: #
11950: 
11951:     if ($uri =~ /ext\.tool$/) {
11952:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11953:             return;
11954:         } else {
11955:             my ($checked,$use_passback);
11956:             if ($toolsymb ne '') {
11957:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11958:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11959:                     $checked = 1;
11960:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11961:                         $use_passback = 1;
11962:                     }
11963:                 }
11964:             }
11965:             unless ($checked) {
11966:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11967:                 $marker=~s/\D//g;
11968:                 if ($marker) {
11969:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11970:                     $use_passback = $toolsettings{'gradable'};
11971:                 }
11972:             }
11973:             if ($use_passback) {
11974:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11975:             } else {
11976:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11977:             }
11978:         }
11979:     }
11980: 
11981:     {
11982: # Imported parts would go here
11983:         my @origfiletagids=();
11984:         my $importedparts=0;
11985: 
11986: # Imported responseids would go here
11987:         my $importedresponses=0;
11988: #
11989: # Is this a recursive call for a library?
11990: #
11991: #	if (! exists($metacache{$uri})) {
11992: #	    $metacache{$uri}={};
11993: #	}
11994: 	my $cachetime = 60*60;
11995:         if ($liburi) {
11996: 	    $liburi=&declutter($liburi);
11997:             $filename=$liburi;
11998:         } else {
11999: 	    &devalidate_cache_new('meta',$uri);
12000: 	    undef(%metaentry);
12001: 	}
12002:         my %metathesekeys=();
12003:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12004: 	my $metastring;
12005: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12006: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12007: 	    $metastring = 
12008: 		&Apache::lonnet::ssi_body($which,
12009: 					  ('grade_target' => 'meta'));
12010: 	    $cachetime = 1; # only want this cached in the child not long term
12011: 	} elsif (($uri !~ m -^(editupload)/-) && 
12012:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12013: 	    my $file=&filelocation('',&clutter($filename));
12014: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12015: 	    $metastring=&getfile($file);
12016: 	}
12017:         my $parser=HTML::LCParser->new(\$metastring);
12018:         my $token;
12019:         undef %metathesekeys;
12020:         while ($token=$parser->get_token) {
12021: 	    if ($token->[0] eq 'S') {
12022: 		if (defined($token->[2]->{'package'})) {
12023: #
12024: # This is a package - get package info
12025: #
12026: 		    my $package=$token->[2]->{'package'};
12027: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12028: 		    if (defined($token->[2]->{'id'})) { 
12029: 			$keyroot.='_'.$token->[2]->{'id'}; 
12030: 		    }
12031: 		    if ($metaentry{':packages'}) {
12032: 			$metaentry{':packages'}.=','.$package.$keyroot;
12033: 		    } else {
12034: 			$metaentry{':packages'}=$package.$keyroot;
12035: 		    }
12036: 		    foreach my $pack_entry (keys(%packagetab)) {
12037: 			my $part=$keyroot;
12038: 			$part=~s/^\_//;
12039: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12040: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12041: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12042: 			    # ignore package.tab specified default values
12043:                             # here &package_tab_default() will fetch those
12044: 			    if ($subp eq 'default') { next; }
12045: 			    my $value=$packagetab{$pack_entry};
12046: 			    my $unikey;
12047: 			    if ($pack =~ /_0$/) {
12048: 				$unikey='parameter_0_'.$name;
12049: 				$part=0;
12050: 			    } else {
12051: 				$unikey='parameter'.$keyroot.'_'.$name;
12052: 			    }
12053: 			    if ($subp eq 'display') {
12054: 				$value.=' [Part: '.$part.']';
12055: 			    }
12056: 			    $metaentry{':'.$unikey.'.part'}=$part;
12057: 			    $metathesekeys{$unikey}=1;
12058: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12059: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12060: 			    }
12061: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12062: 				$metaentry{':'.$unikey}=
12063: 				    $metaentry{':'.$unikey.'.default'};
12064: 			    }
12065: 			}
12066: 		    }
12067: 		} else {
12068: #
12069: # This is not a package - some other kind of start tag
12070: #
12071: 		    my $entry=$token->[1];
12072: 		    my $unikey='';
12073: 
12074: 		    if ($entry eq 'import') {
12075: #
12076: # Importing a library here
12077: #
12078:                         my $location=$parser->get_text('/import');
12079:                         my $dir=$filename;
12080:                         $dir=~s|[^/]*$||;
12081:                         $location=&filelocation($dir,$location);
12082: 
12083:                         my $importid=$token->[2]->{'id'};
12084:                         my $importmode=$token->[2]->{'importmode'};
12085: #
12086: # Check metadata for imported file to
12087: # see if it contained response items
12088: #
12089:                         my ($origfile,@libfilekeys);
12090:                         my %currmetaentry = %metaentry;
12091:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12092:                                                            $depthcount+1));
12093:                         if (grep(/^responseorder$/,@libfilekeys)) {
12094:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12095:                                                              undef,$depthcount+1);
12096:                             if ($libresponseorder ne '') {
12097:                                 if ($#origfiletagids<0) {
12098:                                     undef(%importedrespids);
12099:                                     undef(%importedpartids);
12100:                                 }
12101:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12102:                                 if (@respids) {
12103:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12104:                                 }
12105:                                 if ($importedrespids{$importid} ne '') {
12106:                                     $importedresponses = 1;
12107: # We need to get the original file and the imported file to get the response order correct
12108: # Load and inspect original file
12109:                                     if ($#origfiletagids<0) {
12110:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12111:                                         $origfile=&getfile($origfilelocation);
12112:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12113:                                     }
12114:                                 }
12115:                             }
12116:                         }
12117: # Do not overwrite contents of %metaentry hash for resource itself with 
12118: # hash populated for imported library file
12119:                         %metaentry = %currmetaentry;
12120:                         undef(%currmetaentry);
12121:                         if ($importmode eq 'part') {
12122: # Import as part(s)
12123:                            $importedparts=1;
12124: # We need to get the original file and the imported file to get the part order correct
12125: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12126: # Load and inspect original file if we didn't do that already
12127:                            if ($#origfiletagids<0) {
12128:                                undef(%importedrespids);
12129:                                undef(%importedpartids);
12130:                                if ($origfile eq '') {
12131:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12132:                                    $origfile=&getfile($origfilelocation);
12133:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12134:                                }
12135:                            }
12136:                            my @impfilepartids;
12137: # If <partorder> tag is included in metadata for the imported file
12138: # get the parts in the imported file from that.
12139:                            if (grep(/^partorder$/,@libfilekeys)) {
12140:                                %currmetaentry = %metaentry;
12141:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12142:                                                             $depthcount+1);
12143:                                %metaentry = %currmetaentry;
12144:                                undef(%currmetaentry);
12145:                                if ($libpartorder ne '') {
12146:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12147:                                }
12148:                            } else {
12149: # If no <partorder> tag available, load and inspect imported file
12150:                                my $impfile=&getfile($location);
12151:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12152:                            }
12153:                            if ($#impfilepartids>=0) {
12154: # This problem had parts
12155:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12156:                            } else {
12157: # Importing by turning a single problem into a problem part
12158: # It gets the import-tags ID as part-ID
12159:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12160:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12161:                            }
12162:                         } else {
12163: # Import as problem or as normal import
12164:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12165:                             unless ($importmode eq 'problem') {
12166: # Normal import
12167:                                 if (defined($token->[2]->{'id'})) {
12168:                                     $unikey.='_'.$token->[2]->{'id'};
12169:                                 }
12170:                             }
12171: # Check metadata for imported file to
12172: # see if it contained parts
12173:                             if (grep(/^partorder$/,@libfilekeys)) {
12174:                                 %currmetaentry = %metaentry;
12175:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12176:                                                              $depthcount+1);
12177:                                 %metaentry = %currmetaentry;
12178:                                 undef(%currmetaentry);
12179:                                 if ($libpartorder ne '') {
12180:                                     $importedparts = 1;
12181:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12182:                                 }
12183:                             }
12184:                         }
12185: 			if ($depthcount<20) {
12186: 			    my $metadata = 
12187: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12188: 					  $depthcount+1);
12189: 			    foreach my $meta (split(',',$metadata)) {
12190: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12191: 				$metathesekeys{$meta}=1;
12192: 			    }
12193:                         }
12194: 		    } else {
12195: #
12196: # Not importing, some other kind of non-package, non-library start tag
12197: # 
12198:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12199:                         if (defined($token->[2]->{'id'})) {
12200:                             $unikey.='_'.$token->[2]->{'id'};
12201:                         }
12202: 			if (defined($token->[2]->{'name'})) { 
12203: 			    $unikey.='_'.$token->[2]->{'name'}; 
12204: 			}
12205: 			$metathesekeys{$unikey}=1;
12206: 			foreach my $param (@{$token->[3]}) {
12207: 			    $metaentry{':'.$unikey.'.'.$param} =
12208: 				$token->[2]->{$param};
12209: 			}
12210: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12211: 			my $default=$metaentry{':'.$unikey.'.default'};
12212: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12213: 		 # only ws inside the tag, and not in default, so use default
12214: 		 # as value
12215: 			    $metaentry{':'.$unikey}=$default;
12216: 			} elsif ( $internaltext =~ /\S/ ) {
12217: 		  # something interesting inside the tag
12218: 			    $metaentry{':'.$unikey}=$internaltext;
12219: 			} else {
12220: 		  # no interesting values, don't set a default
12221: 			}
12222: # end of not-a-package not-a-library import
12223: 		    }
12224: # end of not-a-package start tag
12225: 		}
12226: # the next is the end of "start tag"
12227: 	    }
12228: 	}
12229: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12230: 	$extension = lc($extension);
12231: 	if ($extension eq 'htm') { $extension='html'; }
12232: 
12233: 	foreach my $key (keys(%packagetab)) {
12234: 	    #no specific packages #how's our extension
12235: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12236: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12237: 					 \%metathesekeys);
12238: 	}
12239: 
12240: 	if (!exists($metaentry{':packages'})
12241: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12242: 	    foreach my $key (keys(%packagetab)) {
12243: 		#no specific packages well let's get default then
12244: 		if ($key!~/^default&/) { next; }
12245: 		&metadata_create_package_def($uri,$key,'default',
12246: 					     \%metathesekeys);
12247: 	    }
12248: 	}
12249: # are there custom rights to evaluate
12250: 	if ($metaentry{':copyright'} eq 'custom') {
12251: 
12252:     #
12253:     # Importing a rights file here
12254:     #
12255: 	    unless ($depthcount) {
12256: 		my $location=$metaentry{':customdistributionfile'};
12257: 		my $dir=$filename;
12258: 		$dir=~s|[^/]*$||;
12259: 		$location=&filelocation($dir,$location);
12260: 		my $rights_metadata =
12261: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12262: 			      $depthcount+1);
12263: 		foreach my $rights (split(',',$rights_metadata)) {
12264: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12265: 		    $metathesekeys{$rights}=1;
12266: 		}
12267: 	    }
12268: 	}
12269: 	# uniqifiy package listing
12270: 	my %seen;
12271: 	my @uniq_packages =
12272: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12273: 	$metaentry{':packages'} = join(',',@uniq_packages);
12274: 
12275:         if (($importedresponses) || ($importedparts)) {
12276:             if ($importedparts) {
12277: # We had imported parts and need to rebuild partorder
12278:                 $metaentry{':partorder'}='';
12279:                 $metathesekeys{'partorder'}=1;
12280:             }
12281:             if ($importedresponses) {
12282: # We had imported responses and need to rebuil responseorder
12283:                 $metaentry{':responseorder'}='';
12284:                 $metathesekeys{'responseorder'}=1;
12285:             }
12286:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12287:                 my $origid = $origfiletagids[$index+1];
12288:                 if ($origfiletagids[$index] eq 'part') {
12289: # Original part, part of the problem
12290:                     if ($importedparts) {
12291:                         $metaentry{':partorder'}.=','.$origid;
12292:                     }
12293:                 } elsif ($origfiletagids[$index] eq 'import') {
12294:                     if ($importedparts) {
12295: # We have imported parts at this position
12296:                         if ($importedpartids{$origid} ne '') {
12297:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12298:                         }
12299:                     }
12300:                     if ($importedresponses) {
12301: # We have imported responses at this position
12302:                         if ($importedrespids{$origid} ne '') {
12303:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12304:                         }
12305:                     }
12306:                 } else {
12307: # Original response item, part of the problem
12308:                     if ($importedresponses) {
12309:                         $metaentry{':responseorder'}.=','.$origid;
12310:                     }
12311:                 }
12312:             }
12313:             if ($importedparts) {
12314:                 $metaentry{':partorder'}=~s/^\,//;
12315:             }
12316:             if ($importedresponses) {
12317:                 $metaentry{':responseorder'}=~s/^\,//;
12318:             }
12319:         }
12320: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12321: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12322: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12323:         unless ($liburi) {
12324: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12325:         }
12326: # this is the end of "was not already recently cached
12327:     }
12328:     return $metaentry{':'.$what};
12329: }
12330: 
12331: sub metadata_create_package_def {
12332:     my ($uri,$key,$package,$metathesekeys)=@_;
12333:     my ($pack,$name,$subp)=split(/\&/,$key);
12334:     if ($subp eq 'default') { next; }
12335:     
12336:     if (defined($metaentry{':packages'})) {
12337: 	$metaentry{':packages'}.=','.$package;
12338:     } else {
12339: 	$metaentry{':packages'}=$package;
12340:     }
12341:     my $value=$packagetab{$key};
12342:     my $unikey;
12343:     $unikey='parameter_0_'.$name;
12344:     $metaentry{':'.$unikey.'.part'}=0;
12345:     $$metathesekeys{$unikey}=1;
12346:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12347: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12348:     }
12349:     if (defined($metaentry{':'.$unikey.'.default'})) {
12350: 	$metaentry{':'.$unikey}=
12351: 	    $metaentry{':'.$unikey.'.default'};
12352:     }
12353: }
12354: 
12355: sub metadata_generate_part0 {
12356:     my ($metadata,$metacache,$uri) = @_;
12357:     my %allnames;
12358:     foreach my $metakey (keys(%$metadata)) {
12359: 	if ($metakey=~/^parameter\_(.*)/) {
12360: 	  my $part=$$metacache{':'.$metakey.'.part'};
12361: 	  my $name=$$metacache{':'.$metakey.'.name'};
12362: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12363: 	    $allnames{$name}=$part;
12364: 	  }
12365: 	}
12366:     }
12367:     foreach my $name (keys(%allnames)) {
12368:       $$metadata{"parameter_0_$name"}=1;
12369:       my $key=":parameter_0_$name";
12370:       $$metacache{"$key.part"}='0';
12371:       $$metacache{"$key.name"}=$name;
12372:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12373: 					   $allnames{$name}.'_'.$name.
12374: 					   '.type'};
12375:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12376: 			     '.display'};
12377:       my $expr='[Part: '.$allnames{$name}.']';
12378:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12379:       $$metacache{"$key.display"}=$olddis;
12380:     }
12381: }
12382: 
12383: # ------------------------------------------------------ Devalidate title cache
12384: 
12385: sub devalidate_title_cache {
12386:     my ($url)=@_;
12387:     if (!$env{'request.course.id'}) { return; }
12388:     my $symb=&symbread($url);
12389:     if (!$symb) { return; }
12390:     my $key=$env{'request.course.id'}."\0".$symb;
12391:     &devalidate_cache_new('title',$key);
12392: }
12393: 
12394: # ------------------------------------------------- Get the title of a course
12395: 
12396: sub current_course_title {
12397:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12398: }
12399: # ------------------------------------------------- Get the title of a resource
12400: 
12401: sub gettitle {
12402:     my $urlsymb=shift;
12403:     my $symb=&symbread($urlsymb);
12404:     if ($symb) {
12405: 	my $key=$env{'request.course.id'}."\0".$symb;
12406: 	my ($result,$cached)=&is_cached_new('title',$key);
12407: 	if (defined($cached)) { 
12408: 	    return $result;
12409: 	}
12410: 	my ($map,$resid,$url)=&decode_symb($symb);
12411: 	my $title='';
12412: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12413: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12414: 	} else {
12415: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12416: 		    &GDBM_READER(),0640)) {
12417: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12418: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12419: 		untie(%bighash);
12420: 	    }
12421: 	}
12422: 	$title=~s/\&colon\;/\:/gs;
12423: 	if ($title) {
12424: # Remember both $symb and $title for dynamic metadata
12425:             $accesshash{$symb.'___crstitle'}=$title;
12426:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12427: # Cache this title and then return it
12428: 	    return &do_cache_new('title',$key,$title,600);
12429: 	}
12430: 	$urlsymb=$url;
12431:     }
12432:     my $title=&metadata($urlsymb,'title');
12433:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12434:     return $title;
12435: }
12436: 
12437: sub get_slot {
12438:     my ($which,$cnum,$cdom)=@_;
12439:     if (!$cnum || !$cdom) {
12440: 	(undef,my $courseid)=&whichuser();
12441: 	$cdom=$env{'course.'.$courseid.'.domain'};
12442: 	$cnum=$env{'course.'.$courseid.'.num'};
12443:     }
12444:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12445:     my %slotinfo;
12446:     if (exists($remembered{$key})) {
12447: 	$slotinfo{$which} = $remembered{$key};
12448:     } else {
12449: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12450: 	&Apache::lonhomework::showhash(%slotinfo);
12451: 	my ($tmp)=keys(%slotinfo);
12452: 	if ($tmp=~/^error:/) { return (); }
12453: 	$remembered{$key} = $slotinfo{$which};
12454:     }
12455:     if (ref($slotinfo{$which}) eq 'HASH') {
12456: 	return %{$slotinfo{$which}};
12457:     }
12458:     return $slotinfo{$which};
12459: }
12460: 
12461: sub get_reservable_slots {
12462:     my ($cnum,$cdom,$uname,$udom) = @_;
12463:     my $now = time;
12464:     my $reservable_info;
12465:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12466:     if (exists($remembered{$key})) {
12467:         $reservable_info = $remembered{$key};
12468:     } else {
12469:         my %resv;
12470:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12471:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12472:         $reservable_info = \%resv;
12473:         $remembered{$key} = $reservable_info;
12474:     }
12475:     return $reservable_info;
12476: }
12477: 
12478: sub get_course_slots {
12479:     my ($cnum,$cdom) = @_;
12480:     my $hashid=$cnum.':'.$cdom;
12481:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12482:     if (defined($cached)) {
12483:         if (ref($result) eq 'HASH') {
12484:             return %{$result};
12485:         }
12486:     } else {
12487:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12488:         my ($tmp) = keys(%slots);
12489:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12490:             &do_cache_new('allslots',$hashid,\%slots,600);
12491:             return %slots;
12492:         }
12493:     }
12494:     return;
12495: }
12496: 
12497: sub devalidate_slots_cache {
12498:     my ($cnum,$cdom)=@_;
12499:     my $hashid=$cnum.':'.$cdom;
12500:     &devalidate_cache_new('allslots',$hashid);
12501: }
12502: 
12503: sub get_coursechange {
12504:     my ($cdom,$cnum) = @_;
12505:     if ($cdom eq '' || $cnum eq '') {
12506:         return unless ($env{'request.course.id'});
12507:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12508:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12509:     }
12510:     my $hashid=$cdom.'_'.$cnum;
12511:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12512:     if ((defined($cached)) && ($change ne '')) {
12513:         return $change;
12514:     } else {
12515:         my %crshash;
12516:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12517:         if ($crshash{'internal.contentchange'} eq '') {
12518:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12519:             if ($change eq '') {
12520:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12521:                 $change = $crshash{'internal.created'};
12522:             }
12523:         } else {
12524:             $change = $crshash{'internal.contentchange'};
12525:         }
12526:         my $cachetime = 600;
12527:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12528:     }
12529:     return $change;
12530: }
12531: 
12532: sub devalidate_coursechange_cache {
12533:     my ($cnum,$cdom)=@_;
12534:     my $hashid=$cnum.':'.$cdom;
12535:     &devalidate_cache_new('crschange',$hashid);
12536: }
12537: 
12538: # ------------------------------------------------- Update symbolic store links
12539: 
12540: sub symblist {
12541:     my ($mapname,%newhash)=@_;
12542:     $mapname=&deversion(&declutter($mapname));
12543:     my %hash;
12544:     if (($env{'request.course.fn'}) && (%newhash)) {
12545:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12546:                       &GDBM_WRCREAT(),0640)) {
12547: 	    foreach my $url (keys(%newhash)) {
12548: 		next if ($url eq 'last_known'
12549: 			 && $env{'form.no_update_last_known'});
12550: 		$hash{declutter($url)}=&encode_symb($mapname,
12551: 						    $newhash{$url}->[1],
12552: 						    $newhash{$url}->[0]);
12553:             }
12554:             if (untie(%hash)) {
12555: 		return 'ok';
12556:             }
12557:         }
12558:     }
12559:     return 'error';
12560: }
12561: 
12562: # --------------------------------------------------------------- Verify a symb
12563: 
12564: sub symbverify {
12565:     my ($symb,$thisurl,$encstate)=@_;
12566:     my $thisfn=$thisurl;
12567:     $thisfn=&declutter($thisfn);
12568: # direct jump to resource in page or to a sequence - will construct own symbs
12569:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12570: # check URL part
12571:     my ($map,$resid,$url)=&decode_symb($symb);
12572: 
12573:     unless ($url eq $thisfn) { return 0; }
12574: 
12575:     $symb=&symbclean($symb);
12576:     $thisurl=&deversion($thisurl);
12577:     $thisfn=&deversion($thisfn);
12578: 
12579:     my %bighash;
12580:     my $okay=0;
12581: 
12582:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12583:                             &GDBM_READER(),0640)) {
12584:         my $noclutter;
12585:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12586:             $thisurl =~ s/\?.+$//;
12587:             if ($map =~ m{^uploaded/.+\.page$}) {
12588:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12589:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12590:                 $noclutter = 1;
12591:             }
12592:         }
12593:         my $ids;
12594:         if ($noclutter) {
12595:             $ids=$bighash{'ids_'.$thisurl};
12596:         } else {
12597:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12598:         }
12599:         unless ($ids) {
12600:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12601:             $ids=$bighash{$idkey};
12602:         }
12603:         if ($ids) {
12604: # ------------------------------------------------------------------- Has ID(s)
12605:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12606:                 $symb =~ s/\?.+$//;
12607:             }
12608: 	    foreach my $id (split(/\,/,$ids)) {
12609: 	       my ($mapid,$resid)=split(/\./,$id);
12610:                if (
12611:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12612:    eq $symb) {
12613:                    if (ref($encstate)) {
12614:                        $$encstate = $bighash{'encrypted_'.$id};
12615:                    }
12616: 		   if (($env{'request.role.adv'}) ||
12617: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12618:                        ($thisurl eq '/adm/navmaps')) {
12619: 		       $okay=1;
12620:                        last;
12621: 		   }
12622: 	       }
12623: 	   }
12624:         }
12625: 	untie(%bighash);
12626:     }
12627:     return $okay;
12628: }
12629: 
12630: # --------------------------------------------------------------- Clean-up symb
12631: 
12632: sub symbclean {
12633:     my $symb=shift;
12634:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12635: # remove version from map
12636:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12637: 
12638: # remove version from URL
12639:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12640: 
12641: # remove wrapper
12642: 
12643:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12644:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12645:     return $symb;
12646: }
12647: 
12648: # ---------------------------------------------- Split symb to find map and url
12649: 
12650: sub encode_symb {
12651:     my ($map,$resid,$url)=@_;
12652:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12653: }
12654: 
12655: sub decode_symb {
12656:     my $symb=shift;
12657:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12658:     my ($map,$resid,$url)=split(/___/,$symb);
12659:     return (&fixversion($map),$resid,&fixversion($url));
12660: }
12661: 
12662: sub fixversion {
12663:     my $fn=shift;
12664:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12665:     my %bighash;
12666:     my $uri=&clutter($fn);
12667:     my $key=$env{'request.course.id'}.'_'.$uri;
12668: # is this cached?
12669:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12670:     if (defined($cached)) { return $result; }
12671: # unfortunately not cached, or expired
12672:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12673: 	    &GDBM_READER(),0640)) {
12674:  	if ($bighash{'version_'.$uri}) {
12675:  	    my $version=$bighash{'version_'.$uri};
12676:  	    unless (($version eq 'mostrecent') || 
12677: 		    ($version==&getversion($uri))) {
12678:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12679:  	    }
12680:  	}
12681:  	untie %bighash;
12682:     }
12683:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12684: }
12685: 
12686: sub deversion {
12687:     my $url=shift;
12688:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12689:     return $url;
12690: }
12691: 
12692: # ------------------------------------------------------ Return symb list entry
12693: 
12694: sub symbread {
12695:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12696:     my $cache_str='request.symbread.cached.'.$thisfn;
12697:     if (defined($env{$cache_str})) {
12698:         if ($ignorecachednull) {
12699:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12700:         } else {
12701:             return $env{$cache_str};
12702:         }
12703:     }
12704: # no filename provided? try from environment
12705:     unless ($thisfn) {
12706:         if ($env{'request.symb'}) {
12707: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12708: 	}
12709: 	$thisfn=$env{'request.filename'};
12710:     }
12711:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12712: # is that filename actually a symb? Verify, clean, and return
12713:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12714: 	if (&symbverify($thisfn,$1)) {
12715: 	    return $env{$cache_str}=&symbclean($thisfn);
12716: 	}
12717:     }
12718:     $thisfn=declutter($thisfn);
12719:     my %hash;
12720:     my %bighash;
12721:     my $syval='';
12722:     if (($env{'request.course.fn'}) && ($thisfn)) {
12723:         my $targetfn = $thisfn;
12724:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12725:             $targetfn = 'adm/wrapper/'.$thisfn;
12726:         }
12727: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12728: 	    $targetfn=$1;
12729: 	}
12730:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12731:                       &GDBM_READER(),0640)) {
12732: 	    $syval=$hash{$targetfn};
12733:             untie(%hash);
12734:         }
12735: # ---------------------------------------------------------- There was an entry
12736:         if ($syval) {
12737: 	    #unless ($syval=~/\_\d+$/) {
12738: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12739: 		    #&appenv({'request.ambiguous' => $thisfn});
12740: 		    #return $env{$cache_str}='';
12741: 		#}    
12742: 		#$syval.=$1;
12743: 	    #}
12744:         } else {
12745: # ------------------------------------------------------- Was not in symb table
12746:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12747:                             &GDBM_READER(),0640)) {
12748: # ---------------------------------------------- Get ID(s) for current resource
12749:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12750:               unless ($ids) { 
12751:                  $ids=$bighash{'ids_/'.$thisfn};
12752:               }
12753:               unless ($ids) {
12754: # alias?
12755: 		  $ids=$bighash{'mapalias_'.$thisfn};
12756:               }
12757:               if ($ids) {
12758: # ------------------------------------------------------------------- Has ID(s)
12759:                  my @possibilities=split(/\,/,$ids);
12760:                  if ($#possibilities==0) {
12761: # ----------------------------------------------- There is only one possibility
12762: 		     my ($mapid,$resid)=split(/\./,$ids);
12763: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12764: 						    $resid,$thisfn);
12765:                      if (ref($possibles) eq 'HASH') {
12766:                          $possibles->{$syval} = 1;    
12767:                      }
12768:                      if ($checkforblock) {
12769:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12770:                          if (@blockers) {
12771:                              $syval = '';
12772:                              return;
12773:                          }
12774:                      }
12775:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12776: # ------------------------------------------ There is more than one possibility
12777:                      my $realpossible=0;
12778:                      foreach my $id (@possibilities) {
12779: 			 my $file=$bighash{'src_'.$id};
12780:                          my $canaccess;
12781:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12782:                              $canaccess = 1;
12783:                          } else { 
12784:                              $canaccess = &allowed('bre',$file);
12785:                          }
12786:                          if ($canaccess) {
12787:          		     my ($mapid,$resid)=split(/\./,$id);
12788:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12789:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12790: 						             $resid,$thisfn);
12791:                                  if (ref($possibles) eq 'HASH') {
12792:                                      $possibles->{$syval} = 1;
12793:                                  }
12794:                                  if ($checkforblock) {
12795:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12796:                                      unless (@blockers > 0) {
12797:                                          $syval = $poss_syval;
12798:                                          $realpossible++;
12799:                                      }
12800:                                  } else {
12801:                                      $syval = $poss_syval;
12802:                                      $realpossible++;
12803:                                  }
12804:                              }
12805: 			 }
12806:                      }
12807: 		     if ($realpossible!=1) { $syval=''; }
12808:                  } else {
12809:                      $syval='';
12810:                  }
12811: 	      }
12812:               untie(%bighash);
12813:            }
12814:         }
12815:         if ($syval) {
12816: 	    return $env{$cache_str}=$syval;
12817:         }
12818:     }
12819:     &appenv({'request.ambiguous' => $thisfn});
12820:     return $env{$cache_str}='';
12821: }
12822: 
12823: # ---------------------------------------------------------- Return random seed
12824: 
12825: sub numval {
12826:     my $txt=shift;
12827:     $txt=~tr/A-J/0-9/;
12828:     $txt=~tr/a-j/0-9/;
12829:     $txt=~tr/K-T/0-9/;
12830:     $txt=~tr/k-t/0-9/;
12831:     $txt=~tr/U-Z/0-5/;
12832:     $txt=~tr/u-z/0-5/;
12833:     $txt=~s/\D//g;
12834:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12835:     return int($txt);
12836: }
12837: 
12838: sub numval2 {
12839:     my $txt=shift;
12840:     $txt=~tr/A-J/0-9/;
12841:     $txt=~tr/a-j/0-9/;
12842:     $txt=~tr/K-T/0-9/;
12843:     $txt=~tr/k-t/0-9/;
12844:     $txt=~tr/U-Z/0-5/;
12845:     $txt=~tr/u-z/0-5/;
12846:     $txt=~s/\D//g;
12847:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12848:     my $total;
12849:     foreach my $val (@txts) { $total+=$val; }
12850:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12851:     return int($total);
12852: }
12853: 
12854: sub numval3 {
12855:     use integer;
12856:     my $txt=shift;
12857:     $txt=~tr/A-J/0-9/;
12858:     $txt=~tr/a-j/0-9/;
12859:     $txt=~tr/K-T/0-9/;
12860:     $txt=~tr/k-t/0-9/;
12861:     $txt=~tr/U-Z/0-5/;
12862:     $txt=~tr/u-z/0-5/;
12863:     $txt=~s/\D//g;
12864:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12865:     my $total;
12866:     foreach my $val (@txts) { $total+=$val; }
12867:     if ($_64bit) { $total=(($total<<32)>>32); }
12868:     return $total;
12869: }
12870: 
12871: sub digest {
12872:     my ($data)=@_;
12873:     my $digest=&Digest::MD5::md5($data);
12874:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12875:     my ($e,$f);
12876:     {
12877:         use integer;
12878:         $e=($a+$b);
12879:         $f=($c+$d);
12880:         if ($_64bit) {
12881:             $e=(($e<<32)>>32);
12882:             $f=(($f<<32)>>32);
12883:         }
12884:     }
12885:     if (wantarray) {
12886: 	return ($e,$f);
12887:     } else {
12888: 	my $g;
12889: 	{
12890: 	    use integer;
12891: 	    $g=($e+$f);
12892: 	    if ($_64bit) {
12893: 		$g=(($g<<32)>>32);
12894: 	    }
12895: 	}
12896: 	return $g;
12897:     }
12898: }
12899: 
12900: sub latest_rnd_algorithm_id {
12901:     return '64bit5';
12902: }
12903: 
12904: sub get_rand_alg {
12905:     my ($courseid)=@_;
12906:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12907:     if ($courseid) {
12908: 	return $env{"course.$courseid.rndseed"};
12909:     }
12910:     return &latest_rnd_algorithm_id();
12911: }
12912: 
12913: sub validCODE {
12914:     my ($CODE)=@_;
12915:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12916:     return 0;
12917: }
12918: 
12919: sub getCODE {
12920:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12921:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12922: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12923: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12924: 	return $Apache::lonhomework::history{'resource.CODE'};
12925:     }
12926:     return undef;
12927: }
12928: #
12929: #  Determines the random seed for a specific context:
12930: #
12931: # parameters:
12932: #   symb      - in course context the symb for the seed.
12933: #   course_id - The course id of the form domain_coursenum.
12934: #   domain    - Domain for the user.
12935: #   course    - Course for the user.
12936: #   cenv      - environment of the course.
12937: #
12938: # NOTE:
12939: #   All parameters are picked out of the environment if missing
12940: #   or not defined.
12941: #   If a symb cannot be determined the current time is used instead.
12942: #
12943: #  For a given well defined symb, courside, domain, username,
12944: #  and course environment, the seed is reproducible.
12945: #
12946: sub rndseed {
12947:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12948:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12949:     if (!defined($symb)) {
12950: 	unless ($symb=$wsymb) { return time; }
12951:     }
12952:     if (!defined $courseid) { 
12953: 	$courseid=$wcourseid; 
12954:     }
12955:     if (!defined $domain) { $domain=$wdomain; }
12956:     if (!defined $username) { $username=$wusername }
12957: 
12958:     my $which;
12959:     if (defined($cenv->{'rndseed'})) {
12960: 	$which = $cenv->{'rndseed'};
12961:     } else {
12962: 	$which =&get_rand_alg($courseid);
12963:     }
12964:     if (defined(&getCODE())) {
12965: 
12966: 	if ($which eq '64bit5') {
12967: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12968: 	} elsif ($which eq '64bit4') {
12969: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12970: 	} else {
12971: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12972: 	}
12973:     } elsif ($which eq '64bit5') {
12974: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12975:     } elsif ($which eq '64bit4') {
12976: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12977:     } elsif ($which eq '64bit3') {
12978: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12979:     } elsif ($which eq '64bit2') {
12980: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12981:     } elsif ($which eq '64bit') {
12982: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12983:     }
12984:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12985: }
12986: 
12987: sub rndseed_32bit {
12988:     my ($symb,$courseid,$domain,$username)=@_;
12989:     {
12990: 	use integer;
12991: 	my $symbchck=unpack("%32C*",$symb) << 27;
12992: 	my $symbseed=numval($symb) << 22;
12993: 	my $namechck=unpack("%32C*",$username) << 17;
12994: 	my $nameseed=numval($username) << 12;
12995: 	my $domainseed=unpack("%32C*",$domain) << 7;
12996: 	my $courseseed=unpack("%32C*",$courseid);
12997: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12998: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12999: 	#&logthis("rndseed :$num:$symb");
13000: 	if ($_64bit) { $num=(($num<<32)>>32); }
13001: 	return $num;
13002:     }
13003: }
13004: 
13005: sub rndseed_64bit {
13006:     my ($symb,$courseid,$domain,$username)=@_;
13007:     {
13008: 	use integer;
13009: 	my $symbchck=unpack("%32S*",$symb) << 21;
13010: 	my $symbseed=numval($symb) << 10;
13011: 	my $namechck=unpack("%32S*",$username);
13012: 	
13013: 	my $nameseed=numval($username) << 21;
13014: 	my $domainseed=unpack("%32S*",$domain) << 10;
13015: 	my $courseseed=unpack("%32S*",$courseid);
13016: 	
13017: 	my $num1=$symbchck+$symbseed+$namechck;
13018: 	my $num2=$nameseed+$domainseed+$courseseed;
13019: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13020: 	#&logthis("rndseed :$num:$symb");
13021: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13022: 	return "$num1,$num2";
13023:     }
13024: }
13025: 
13026: sub rndseed_64bit2 {
13027:     my ($symb,$courseid,$domain,$username)=@_;
13028:     {
13029: 	use integer;
13030: 	# strings need to be an even # of cahracters long, it it is odd the
13031:         # last characters gets thrown away
13032: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13033: 	my $symbseed=numval($symb) << 10;
13034: 	my $namechck=unpack("%32S*",$username.' ');
13035: 	
13036: 	my $nameseed=numval($username) << 21;
13037: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13038: 	my $courseseed=unpack("%32S*",$courseid.' ');
13039: 	
13040: 	my $num1=$symbchck+$symbseed+$namechck;
13041: 	my $num2=$nameseed+$domainseed+$courseseed;
13042: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13043: 	#&logthis("rndseed :$num:$symb");
13044: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13045: 	return "$num1,$num2";
13046:     }
13047: }
13048: 
13049: sub rndseed_64bit3 {
13050:     my ($symb,$courseid,$domain,$username)=@_;
13051:     {
13052: 	use integer;
13053: 	# strings need to be an even # of cahracters long, it it is odd the
13054:         # last characters gets thrown away
13055: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13056: 	my $symbseed=numval2($symb) << 10;
13057: 	my $namechck=unpack("%32S*",$username.' ');
13058: 	
13059: 	my $nameseed=numval2($username) << 21;
13060: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13061: 	my $courseseed=unpack("%32S*",$courseid.' ');
13062: 	
13063: 	my $num1=$symbchck+$symbseed+$namechck;
13064: 	my $num2=$nameseed+$domainseed+$courseseed;
13065: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13066: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13067: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13068: 	
13069: 	return "$num1:$num2";
13070:     }
13071: }
13072: 
13073: sub rndseed_64bit4 {
13074:     my ($symb,$courseid,$domain,$username)=@_;
13075:     {
13076: 	use integer;
13077: 	# strings need to be an even # of cahracters long, it it is odd the
13078:         # last characters gets thrown away
13079: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13080: 	my $symbseed=numval3($symb) << 10;
13081: 	my $namechck=unpack("%32S*",$username.' ');
13082: 	
13083: 	my $nameseed=numval3($username) << 21;
13084: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13085: 	my $courseseed=unpack("%32S*",$courseid.' ');
13086: 	
13087: 	my $num1=$symbchck+$symbseed+$namechck;
13088: 	my $num2=$nameseed+$domainseed+$courseseed;
13089: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13090: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13091: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13092: 	
13093: 	return "$num1:$num2";
13094:     }
13095: }
13096: 
13097: sub rndseed_64bit5 {
13098:     my ($symb,$courseid,$domain,$username)=@_;
13099:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13100:     return "$num1:$num2";
13101: }
13102: 
13103: sub rndseed_CODE_64bit {
13104:     my ($symb,$courseid,$domain,$username)=@_;
13105:     {
13106: 	use integer;
13107: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13108: 	my $symbseed=numval2($symb);
13109: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13110: 	my $CODEseed=numval(&getCODE());
13111: 	my $courseseed=unpack("%32S*",$courseid.' ');
13112: 	my $num1=$symbseed+$CODEchck;
13113: 	my $num2=$CODEseed+$courseseed+$symbchck;
13114: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13115: 	#&logthis("rndseed :$num1:$num2:$symb");
13116: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13117: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13118: 	return "$num1:$num2";
13119:     }
13120: }
13121: 
13122: sub rndseed_CODE_64bit4 {
13123:     my ($symb,$courseid,$domain,$username)=@_;
13124:     {
13125: 	use integer;
13126: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13127: 	my $symbseed=numval3($symb);
13128: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13129: 	my $CODEseed=numval3(&getCODE());
13130: 	my $courseseed=unpack("%32S*",$courseid.' ');
13131: 	my $num1=$symbseed+$CODEchck;
13132: 	my $num2=$CODEseed+$courseseed+$symbchck;
13133: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13134: 	#&logthis("rndseed :$num1:$num2:$symb");
13135: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13136: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13137: 	return "$num1:$num2";
13138:     }
13139: }
13140: 
13141: sub rndseed_CODE_64bit5 {
13142:     my ($symb,$courseid,$domain,$username)=@_;
13143:     my $code = &getCODE();
13144:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13145:     return "$num1:$num2";
13146: }
13147: 
13148: sub setup_random_from_rndseed {
13149:     my ($rndseed)=@_;
13150:     if ($rndseed =~/([,:])/) {
13151:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13152:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13153:             &Math::Random::random_set_seed_from_phrase($rndseed);
13154:         } else {
13155:             &Math::Random::random_set_seed($num1,$num2);
13156:         }
13157:     } else {
13158: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13159:     }
13160: }
13161: 
13162: sub latest_receipt_algorithm_id {
13163:     return 'receipt3';
13164: }
13165: 
13166: sub recunique {
13167:     my $fucourseid=shift;
13168:     my $unique;
13169:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13170: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13171: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13172:     } else {
13173: 	$unique=$perlvar{'lonReceipt'};
13174:     }
13175:     return unpack("%32C*",$unique);
13176: }
13177: 
13178: sub recprefix {
13179:     my $fucourseid=shift;
13180:     my $prefix;
13181:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13182: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13183: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13184:     } else {
13185: 	$prefix=$perlvar{'lonHostID'};
13186:     }
13187:     return unpack("%32C*",$prefix);
13188: }
13189: 
13190: sub ireceipt {
13191:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13192: 
13193:     my $return =&recprefix($fucourseid).'-';
13194: 
13195:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13196: 	$env{'request.state'} eq 'construct') {
13197: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13198: 	return $return;
13199:     }
13200: 
13201:     my $cuname=unpack("%32C*",$funame);
13202:     my $cudom=unpack("%32C*",$fudom);
13203:     my $cucourseid=unpack("%32C*",$fucourseid);
13204:     my $cusymb=unpack("%32C*",$fusymb);
13205:     my $cunique=&recunique($fucourseid);
13206:     my $cpart=unpack("%32S*",$part);
13207:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13208: 
13209: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13210: 			       
13211: 	$return.= ($cunique%$cuname+
13212: 		   $cunique%$cudom+
13213: 		   $cusymb%$cuname+
13214: 		   $cusymb%$cudom+
13215: 		   $cucourseid%$cuname+
13216: 		   $cucourseid%$cudom+
13217: 		   $cpart%$cuname+
13218: 		   $cpart%$cudom);
13219:     } else {
13220: 	$return.= ($cunique%$cuname+
13221: 		   $cunique%$cudom+
13222: 		   $cusymb%$cuname+
13223: 		   $cusymb%$cudom+
13224: 		   $cucourseid%$cuname+
13225: 		   $cucourseid%$cudom);
13226:     }
13227:     return $return;
13228: }
13229: 
13230: sub receipt {
13231:     my ($part)=@_;
13232:     my ($symb,$courseid,$domain,$name) = &whichuser();
13233:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13234: }
13235: 
13236: sub whichuser {
13237:     my ($passedsymb)=@_;
13238:     my ($symb,$courseid,$domain,$name,$publicuser);
13239:     if (defined($env{'form.grade_symb'})) {
13240: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13241: 	my $allowed=&allowed('vgr',$tmp_courseid);
13242: 	if (!$allowed &&
13243: 	    exists($env{'request.course.sec'}) &&
13244: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13245: 	    $allowed=&allowed('vgr',$tmp_courseid.
13246: 			      '/'.$env{'request.course.sec'});
13247: 	}
13248: 	if ($allowed) {
13249: 	    ($symb)=&get_env_multiple('form.grade_symb');
13250: 	    $courseid=$tmp_courseid;
13251: 	    ($domain)=&get_env_multiple('form.grade_domain');
13252: 	    ($name)=&get_env_multiple('form.grade_username');
13253: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13254: 	}
13255:     }
13256:     if (!$passedsymb) {
13257: 	$symb=&symbread();
13258:     } else {
13259: 	$symb=$passedsymb;
13260:     }
13261:     $courseid=$env{'request.course.id'};
13262:     $domain=$env{'user.domain'};
13263:     $name=$env{'user.name'};
13264:     if ($name eq 'public' && $domain eq 'public') {
13265: 	if (!defined($env{'form.username'})) {
13266: 	    $env{'form.username'}.=time.rand(10000000);
13267: 	}
13268: 	$name.=$env{'form.username'};
13269:     }
13270:     return ($symb,$courseid,$domain,$name,$publicuser);
13271: 
13272: }
13273: 
13274: # ------------------------------------------------------------ Serves up a file
13275: # returns either the contents of the file or 
13276: # -1 if the file doesn't exist
13277: #
13278: # if the target is a file that was uploaded via DOCS, 
13279: # a check will be made to see if a current copy exists on the local server,
13280: # if it does this will be served, otherwise a copy will be retrieved from
13281: # the home server for the course and stored in /home/httpd/html/userfiles on
13282: # the local server.   
13283: 
13284: sub getfile {
13285:     my ($file) = @_;
13286:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13287:     &repcopy($file);
13288:     return &readfile($file);
13289: }
13290: 
13291: sub repcopy_userfile {
13292:     my ($file)=@_;
13293:     my $londocroot = $perlvar{'lonDocRoot'};
13294:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13295:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13296:     my ($cdom,$cnum,$filename) = 
13297: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13298:     my $uri="/uploaded/$cdom/$cnum/$filename";
13299:     if (-e "$file") {
13300: # we already have a local copy, check it out
13301: 	my @fileinfo = stat($file);
13302: 	my $rtncode;
13303: 	my $info;
13304: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13305: 	if ($lwpresp ne 'ok') {
13306: # there is no such file anymore, even though we had a local copy
13307: 	    if ($rtncode eq '404') {
13308: 		unlink($file);
13309: 	    }
13310: 	    return -1;
13311: 	}
13312: 	if ($info < $fileinfo[9]) {
13313: # nice, the file we have is up-to-date, just say okay
13314: 	    return 'ok';
13315: 	} else {
13316: # the file is outdated, get rid of it
13317: 	    unlink($file);
13318: 	}
13319:     }
13320: # one way or the other, at this point, we don't have the file
13321: # construct the correct path for the file
13322:     my @parts = ($cdom,$cnum); 
13323:     if ($filename =~ m|^(.+)/[^/]+$|) {
13324: 	push @parts, split(/\//,$1);
13325:     }
13326:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13327:     foreach my $part (@parts) {
13328: 	$path .= '/'.$part;
13329: 	if (!-e $path) {
13330: 	    mkdir($path,0770);
13331: 	}
13332:     }
13333: # now the path exists for sure
13334: # get a user agent
13335:     my $transferfile=$file.'.in.transfer';
13336: # FIXME: this should flock
13337:     if (-e $transferfile) { return 'ok'; }
13338:     my $request;
13339:     $uri=~s/^\///;
13340:     my $homeserver = &homeserver($cnum,$cdom);
13341:     my $protocol = $protocol{$homeserver};
13342:     $protocol = 'http' if ($protocol ne 'https');
13343:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13344:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13345: # did it work?
13346:     if ($response->is_error()) {
13347: 	unlink($transferfile);
13348: 	&logthis("Userfile repcopy failed for $uri");
13349: 	return -1;
13350:     }
13351: # worked, rename the transfer file
13352:     rename($transferfile,$file);
13353:     return 'ok';
13354: }
13355: 
13356: sub tokenwrapper {
13357:     my $uri=shift;
13358:     $uri=~s|^https?\://([^/]+)||;
13359:     $uri=~s|^/||;
13360:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13361:     my $token=$1;
13362:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13363:     if ($udom && $uname && $file) {
13364: 	$file=~s|(\?\.*)*$||;
13365:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13366:         my $homeserver = &homeserver($uname,$udom);
13367:         my $protocol = $protocol{$homeserver};
13368:         $protocol = 'http' if ($protocol ne 'https');
13369:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13370:                (($uri=~/\?/)?'&':'?').'token='.$token.
13371:                                '&tokenissued='.$perlvar{'lonHostID'};
13372:     } else {
13373:         return '/adm/notfound.html';
13374:     }
13375: }
13376: 
13377: # call with reqtype HEAD: get last modification time
13378: # call with reqtype GET: get the file contents
13379: # Do not call this with reqtype GET for large files! It loads everything into memory
13380: #
13381: sub getuploaded {
13382:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13383:     $uri=~s/^\///;
13384:     my $homeserver = &homeserver($cnum,$cdom);
13385:     my $protocol = $protocol{$homeserver};
13386:     $protocol = 'http' if ($protocol ne 'https');
13387:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13388:     my $request=new HTTP::Request($reqtype,$uri);
13389:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13390:     $$rtncode = $response->code;
13391:     if (! $response->is_success()) {
13392: 	return 'failed';
13393:     }      
13394:     if ($reqtype eq 'HEAD') {
13395: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13396:     } elsif ($reqtype eq 'GET') {
13397: 	$$info = $response->content;
13398:     }
13399:     return 'ok';
13400: }
13401: 
13402: sub readfile {
13403:     my $file = shift;
13404:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13405:     my $fh;
13406:     open($fh,"<",$file);
13407:     my $a='';
13408:     while (my $line = <$fh>) { $a .= $line; }
13409:     return $a;
13410: }
13411: 
13412: sub filelocation {
13413:     my ($dir,$file) = @_;
13414:     my $location;
13415:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13416: 
13417:     if ($file =~ m-^/adm/-) {
13418: 	$file=~s-^/adm/wrapper/-/-;
13419: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13420:     }
13421: 
13422:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13423:         $location = $file;
13424:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13425:         my ($udom,$uname,$filename)=
13426:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13427:         my $home=&homeserver($uname,$udom);
13428:         my $is_me=0;
13429:         my @ids=&current_machine_ids();
13430:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13431:         if ($is_me) {
13432:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13433:         } else {
13434:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13435:   	      $udom.'/'.$uname.'/'.$filename;
13436:         }
13437:     } elsif ($file =~ m-^/adm/-) {
13438: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13439:     } else {
13440:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13441:         $file=~s:^/(res|priv)/:/:;
13442:         my $space=$1;
13443:         if ( !( $file =~ m:^/:) ) {
13444:             $location = $dir. '/'.$file;
13445:         } else {
13446:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13447:         }
13448:     }
13449:     $location=~s://+:/:g; # remove duplicate /
13450:     while ($location=~m{/\.\./}) {
13451: 	if ($location =~ m{/[^/]+/\.\./}) {
13452: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13453: 	} else {
13454: 	    $location=~ s{/\.\./}{/}g;
13455: 	}
13456:     } #remove dir/..
13457:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13458:     return $location;
13459: }
13460: 
13461: sub hreflocation {
13462:     my ($dir,$file)=@_;
13463:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13464: 	$file=filelocation($dir,$file);
13465:     } elsif ($file=~m-^/adm/-) {
13466: 	$file=~s-^/adm/wrapper/-/-;
13467: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13468:     }
13469:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13470: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13471:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13472: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13473: 	        {/uploaded/$1/$2/}x;
13474:     }
13475:     if ($file=~ m{^/userfiles/}) {
13476: 	$file =~ s{^/userfiles/}{/uploaded/};
13477:     }
13478:     return $file;
13479: }
13480: 
13481: 
13482: 
13483: 
13484: 
13485: sub current_machine_domains {
13486:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13487: }
13488: 
13489: sub machine_domains {
13490:     my ($hostname) = @_;
13491:     my @domains;
13492:     my %hostname = &all_hostnames();
13493:     while( my($id, $name) = each(%hostname)) {
13494: #	&logthis("-$id-$name-$hostname-");
13495: 	if ($hostname eq $name) {
13496: 	    push(@domains,&host_domain($id));
13497: 	}
13498:     }
13499:     return @domains;
13500: }
13501: 
13502: sub current_machine_ids {
13503:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13504: }
13505: 
13506: sub machine_ids {
13507:     my ($hostname) = @_;
13508:     $hostname ||= &hostname($perlvar{'lonHostID'});
13509:     my @ids;
13510:     my %name_to_host = &all_names();
13511:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13512: 	return @{ $name_to_host{$hostname} };
13513:     }
13514:     return;
13515: }
13516: 
13517: sub additional_machine_domains {
13518:     my @domains;
13519:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13520:     while( my $line = <$fh>) {
13521:         $line =~ s/\s//g;
13522:         push(@domains,$line);
13523:     }
13524:     return @domains;
13525: }
13526: 
13527: sub default_login_domain {
13528:     my $domain = $perlvar{'lonDefDomain'};
13529:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13530:     foreach my $posdom (&current_machine_domains(),
13531:                         &additional_machine_domains()) {
13532:         if (lc($posdom) eq lc($testdomain)) {
13533:             $domain=$posdom;
13534:             last;
13535:         }
13536:     }
13537:     return $domain;
13538: }
13539: 
13540: # ------------------------------------------------------------- Declutters URLs
13541: 
13542: sub declutter {
13543:     my $thisfn=shift;
13544:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13545:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13546:         $thisfn=~s{^/home/httpd/html}{};
13547:     }
13548:     $thisfn=~s/^\///;
13549:     $thisfn=~s|^adm/wrapper/||;
13550:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13551:     $thisfn=~s/^res\///;
13552:     $thisfn=~s/^priv\///;
13553:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13554:         $thisfn=~s/\?.+$//;
13555:     }
13556:     return $thisfn;
13557: }
13558: 
13559: # ------------------------------------------------------------- Clutter up URLs
13560: 
13561: sub clutter {
13562:     my $thisfn='/'.&declutter(shift);
13563:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13564: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13565:        $thisfn='/res'.$thisfn; 
13566:     }
13567:     if ($thisfn !~m|^/adm|) {
13568: 	if ($thisfn =~ m|^/ext/|) {
13569: 	    $thisfn='/adm/wrapper'.$thisfn;
13570: 	} else {
13571: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13572: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13573: 	    if ($embstyle eq 'ssi'
13574: 		|| ($embstyle eq 'hdn')
13575: 		|| ($embstyle eq 'rat')
13576: 		|| ($embstyle eq 'prv')
13577: 		|| ($embstyle eq 'ign')) {
13578: 		#do nothing with these
13579: 	    } elsif (($embstyle eq 'img') 
13580: 		|| ($embstyle eq 'emb')
13581: 		|| ($embstyle eq 'wrp')) {
13582: 		$thisfn='/adm/wrapper'.$thisfn;
13583: 	    } elsif ($embstyle eq 'unk'
13584: 		     && $thisfn!~/\.(sequence|page)$/) {
13585: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13586: 	    } else {
13587: #		&logthis("Got a blank emb style");
13588: 	    }
13589: 	}
13590:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13591:         $thisfn='/adm/wrapper'.$thisfn;
13592:     }
13593:     return $thisfn;
13594: }
13595: 
13596: sub clutter_with_no_wrapper {
13597:     my $uri = &clutter(shift);
13598:     if ($uri =~ m-^/adm/-) {
13599: 	$uri =~ s-^/adm/wrapper/-/-;
13600: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13601:     }
13602:     return $uri;
13603: }
13604: 
13605: sub freeze_escape {
13606:     my ($value)=@_;
13607:     if (ref($value)) {
13608: 	$value=&nfreeze($value);
13609: 	return '__FROZEN__'.&escape($value);
13610:     }
13611:     return &escape($value);
13612: }
13613: 
13614: 
13615: sub thaw_unescape {
13616:     my ($value)=@_;
13617:     if ($value =~ /^__FROZEN__/) {
13618: 	substr($value,0,10,undef);
13619: 	$value=&unescape($value);
13620: 	return &thaw($value);
13621:     }
13622:     return &unescape($value);
13623: }
13624: 
13625: sub correct_line_ends {
13626:     my ($result)=@_;
13627:     $$result =~s/\r\n/\n/mg;
13628:     $$result =~s/\r/\n/mg;
13629: }
13630: # ================================================================ Main Program
13631: 
13632: sub goodbye {
13633:    &logthis("Starting Shut down");
13634: #not converted to using infrastruture and probably shouldn't be
13635:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13636: #converted
13637: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13638:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13639: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13640: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13641: #1.1 only
13642: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13643: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13644: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13645: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13646:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13647:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13648:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13649:    &flushcourselogs();
13650:    &logthis("Shutting down");
13651: }
13652: 
13653: sub get_dns {
13654:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13655:     if (!$ignore_cache) {
13656: 	my ($content,$cached)=
13657: 	    &Apache::lonnet::is_cached_new('dns',$url);
13658: 	if ($cached) {
13659: 	    &$func($content,$hashref);
13660: 	    return;
13661: 	}
13662:     }
13663: 
13664:     my %alldns;
13665:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13666:         foreach my $dns (<$config>) {
13667: 	    next if ($dns !~ /^\^(\S*)/x);
13668:             my $line = $1;
13669:             my ($host,$protocol) = split(/:/,$line);
13670:             if ($protocol ne 'https') {
13671:                 $protocol = 'http';
13672:             }
13673: 	    $alldns{$host} = $protocol;
13674:         }
13675:         close($config);
13676:     }
13677:     while (%alldns) {
13678: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13679: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13680:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13681:         delete($alldns{$dns});
13682: 	next if ($response->is_error());
13683:         if ($url eq '/adm/dns/loncapaCRL') {
13684:             return &$func($response);
13685:         } else {
13686: 	    my @content = split("\n",$response->content);
13687: 	    unless ($nocache) {
13688: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13689: 	    }
13690: 	    &$func(\@content,$hashref);
13691:             return;
13692:         }
13693:     }
13694:     my $which = (split('/',$url,4))[3];
13695:     if ($which eq 'loncapaCRL') {
13696:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13697:         if (-e $diskfile) {
13698:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13699:         } else {
13700:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13701:         }
13702:     } else {
13703:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13704:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13705:             my @content = <$config>;
13706:             close($config);
13707:             &$func(\@content,$hashref);
13708:         }
13709:     }
13710:     return;
13711: }
13712: 
13713: # ------------------------------------------------------Get DNS checksums file
13714: sub parse_dns_checksums_tab {
13715:     my ($lines,$hashref) = @_;
13716:     my $lonhost = $perlvar{'lonHostID'};
13717:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13718:     my $loncaparev = &get_server_loncaparev($machine_dom);
13719:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13720:     my $webconfdir = '/etc/httpd/conf';
13721:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13722:         $webconfdir = '/etc/apache2';
13723:     } elsif ($distro =~ /^sles(\d+)$/) {
13724:         if ($1 >= 10) {
13725:             $webconfdir = '/etc/apache2';
13726:         }
13727:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13728:         if ($1 >= 10.0) {
13729:             $webconfdir = '/etc/apache2';
13730:         }
13731:     }
13732:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13733:     my (%chksum,%revnum);
13734:     if (ref($lines) eq 'ARRAY') {
13735:         chomp(@{$lines});
13736:         my $version = shift(@{$lines});
13737:         if ($version eq $release) {  
13738:             foreach my $line (@{$lines}) {
13739:                 my ($file,$version,$shasum) = split(/,/,$line);
13740:                 if ($file =~ m{^/etc/httpd/conf}) {
13741:                     if ($webconfdir eq '/etc/apache2') {
13742:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13743:                     }
13744:                 }
13745:                 $chksum{$file} = $shasum;
13746:                 $revnum{$file} = $version;
13747:             }
13748:             if (ref($hashref) eq 'HASH') {
13749:                 %{$hashref} = (
13750:                                 sums     => \%chksum,
13751:                                 versions => \%revnum,
13752:                               );
13753:             }
13754:         }
13755:     }
13756:     return;
13757: }
13758: 
13759: sub fetch_dns_checksums {
13760:     my %checksums;
13761:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13762:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13763:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13764:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13765:              \%checksums);
13766:     return \%checksums;
13767: }
13768: 
13769: sub fetch_crl_pemfile {
13770:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
13771: }
13772: 
13773: sub save_crl_pem {
13774:     my ($response) = @_;
13775:     my ($msg,$hadchanges);
13776:     if (ref($response)) {
13777:         my $now = time;
13778:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
13779:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
13780:         if (open(my $fh,'>',"$tmpcrl")) {
13781:             print $fh $response->content;
13782:             close($fh);
13783:             if (-e $lonca) {
13784:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
13785:                     my $check = <PIPE>;
13786:                     close(PIPE);
13787:                     chomp($check);
13788:                     if ($check eq 'verify OK') {
13789:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13790:                         my $backup;
13791:                         if (-e $dest) {
13792:                             if (&File::Copy::move($dest,"$dest.bak")) {
13793:                                 $backup = 'ok';
13794:                             }
13795:                         }
13796:                         if (&File::Copy::move($tmpcrl,$dest)) {
13797:                             $msg = 'ok';
13798:                             if ($backup) {
13799:                                 my (%oldnums,%newnums);
13800:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
13801:                                     while (<PIPE>) {
13802:                                         $oldnums{(split(/:/))[1]} = 1;
13803:                                     }
13804:                                     close(PIPE);
13805:                                 }
13806:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
13807:                                     while(<PIPE>) {
13808:                                         $newnums{(split(/:/))[1]} = 1;
13809:                                     }
13810:                                     close(PIPE);
13811:                                 }
13812:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
13813:                                     unless (exists($oldnums{$key})) {
13814:                                         $hadchanges = 1;
13815:                                         last;
13816:                                     }
13817:                                 }
13818:                                 unless ($hadchanges) {
13819:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
13820:                                         unless (exists($newnums{$key})) {
13821:                                             $hadchanges = 1;
13822:                                             last;
13823:                                         }
13824:                                     }
13825:                                 }
13826:                             }
13827:                         }
13828:                     } else {
13829:                         unlink($tmpcrl);
13830:                     }
13831:                 } else {
13832:                     unlink($tmpcrl);
13833:                 }
13834:             } else {
13835:                 unlink($tmpcrl);
13836:             }
13837:         }
13838:     }
13839:     return ($msg,$hadchanges);
13840: }
13841: 
13842: # ------------------------------------------------------------ Read domain file
13843: {
13844:     my $loaded;
13845:     my %domain;
13846: 
13847:     sub parse_domain_tab {
13848: 	my ($lines) = @_;
13849: 	foreach my $line (@$lines) {
13850: 	    next if ($line =~ /^(\#|\s*$ )/x);
13851: 
13852: 	    chomp($line);
13853: 	    my ($name,@elements) = split(/:/,$line,9);
13854: 	    my %this_domain;
13855: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13856: 			       'lang_def', 'city', 'longi', 'lati',
13857: 			       'primary') {
13858: 		$this_domain{$field} = shift(@elements);
13859: 	    }
13860: 	    $domain{$name} = \%this_domain;
13861: 	}
13862:     }
13863: 
13864:     sub reset_domain_info {
13865: 	undef($loaded);
13866: 	undef(%domain);
13867:     }
13868: 
13869:     sub load_domain_tab {
13870: 	my ($ignore_cache,$nocache) = @_;
13871: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13872: 	my $fh;
13873: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13874: 	    my @lines = <$fh>;
13875: 	    &parse_domain_tab(\@lines);
13876: 	}
13877: 	close($fh);
13878: 	$loaded = 1;
13879:     }
13880: 
13881:     sub domain {
13882: 	&load_domain_tab() if (!$loaded);
13883: 
13884: 	my ($name,$what) = @_;
13885: 	return if ( !exists($domain{$name}) );
13886: 
13887: 	if (!$what) {
13888: 	    return $domain{$name}{'description'};
13889: 	}
13890: 	return $domain{$name}{$what};
13891:     }
13892: 
13893:     sub domain_info {
13894:         &load_domain_tab() if (!$loaded);
13895:         return %domain;
13896:     }
13897: 
13898: }
13899: 
13900: 
13901: # ------------------------------------------------------------- Read hosts file
13902: {
13903:     my %hostname;
13904:     my %hostdom;
13905:     my %libserv;
13906:     my $loaded;
13907:     my %name_to_host;
13908:     my %internetdom;
13909:     my %LC_dns_serv;
13910: 
13911:     sub parse_hosts_tab {
13912: 	my ($file) = @_;
13913: 	foreach my $configline (@$file) {
13914: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13915:             chomp($configline);
13916: 	    if ($configline =~ /^\^/) {
13917:                 if ($configline =~ /^\^([\w.\-]+)/) {
13918:                     $LC_dns_serv{$1} = 1;
13919:                 }
13920:                 next;
13921:             }
13922: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13923: 	    $name=~s/\s//g;
13924: 	    if ($id && $domain && $role && $name) {
13925:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13926:                     my $curr = $hostname{$id};
13927:                     my $skip;
13928:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13929:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13930:                             $skip = 1;
13931:                         } else {
13932:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13933:                         }
13934:                     }
13935:                     unless ($skip) {
13936:                         push(@{$name_to_host{$name}},$id);
13937:                     }
13938:                 } else {
13939:                     push(@{$name_to_host{$name}},$id);
13940:                 }
13941: 		$hostname{$id}=$name;
13942: 		$hostdom{$id}=$domain;
13943: 		if ($role eq 'library') { $libserv{$id}=$name; }
13944:                 if (defined($protocol)) {
13945:                     if ($protocol eq 'https') {
13946:                         $protocol{$id} = $protocol;
13947:                     } else {
13948:                         $protocol{$id} = 'http'; 
13949:                     }
13950:                 } else {
13951:                     $protocol{$id} = 'http';
13952:                 }
13953:                 if (defined($intdom)) {
13954:                     $internetdom{$id} = $intdom;
13955:                 }
13956: 	    }
13957: 	}
13958:     }
13959:     
13960:     sub reset_hosts_info {
13961: 	&purge_remembered();
13962: 	&reset_domain_info();
13963: 	&reset_hosts_ip_info();
13964:         undef(%internetdom);
13965: 	undef(%name_to_host);
13966: 	undef(%hostname);
13967: 	undef(%hostdom);
13968: 	undef(%libserv);
13969: 	undef($loaded);
13970:     }
13971: 
13972:     sub load_hosts_tab {
13973: 	my ($ignore_cache,$nocache) = @_;
13974: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13975: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13976: 	my @config = <$config>;
13977: 	&parse_hosts_tab(\@config);
13978: 	close($config);
13979: 	$loaded=1;
13980:     }
13981: 
13982:     sub hostname {
13983: 	&load_hosts_tab() if (!$loaded);
13984: 
13985: 	my ($lonid) = @_;
13986: 	return $hostname{$lonid};
13987:     }
13988: 
13989:     sub all_hostnames {
13990: 	&load_hosts_tab() if (!$loaded);
13991: 
13992: 	return %hostname;
13993:     }
13994: 
13995:     sub all_names {
13996:         my ($ignore_cache,$nocache) = @_;
13997: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13998: 
13999: 	return %name_to_host;
14000:     }
14001: 
14002:     sub all_host_domain {
14003:         &load_hosts_tab() if (!$loaded);
14004:         return %hostdom;
14005:     }
14006: 
14007:     sub all_host_intdom {
14008:         &load_hosts_tab() if (!$loaded);
14009:         return %internetdom;
14010:     }
14011: 
14012:     sub is_library {
14013: 	&load_hosts_tab() if (!$loaded);
14014: 
14015: 	return exists($libserv{$_[0]});
14016:     }
14017: 
14018:     sub all_library {
14019: 	&load_hosts_tab() if (!$loaded);
14020: 
14021: 	return %libserv;
14022:     }
14023: 
14024:     sub unique_library {
14025: 	#2x reverse removes all hostnames that appear more than once
14026:         my %unique = reverse &all_library();
14027:         return reverse %unique;
14028:     }
14029: 
14030:     sub get_servers {
14031: 	&load_hosts_tab() if (!$loaded);
14032: 
14033: 	my ($domain,$type) = @_;
14034: 	my %possible_hosts = ($type eq 'library') ? %libserv
14035: 	                                          : %hostname;
14036: 	my %result;
14037: 	if (ref($domain) eq 'ARRAY') {
14038: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14039: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14040: 		    $result{$host} = $hostname;
14041: 		}
14042: 	    }
14043: 	} else {
14044: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14045: 		if ($hostdom{$host} eq $domain) {
14046: 		    $result{$host} = $hostname;
14047: 		}
14048: 	    }
14049: 	}
14050: 	return %result;
14051:     }
14052: 
14053:     sub get_unique_servers {
14054:         my %unique = reverse &get_servers(@_);
14055: 	return reverse %unique;
14056:     }
14057: 
14058:     sub host_domain {
14059: 	&load_hosts_tab() if (!$loaded);
14060: 
14061: 	my ($lonid) = @_;
14062: 	return $hostdom{$lonid};
14063:     }
14064: 
14065:     sub all_domains {
14066: 	&load_hosts_tab() if (!$loaded);
14067: 
14068: 	my %seen;
14069: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14070: 	return @uniq;
14071:     }
14072: 
14073:     sub internet_dom {
14074:         &load_hosts_tab() if (!$loaded);
14075: 
14076:         my ($lonid) = @_;
14077:         return $internetdom{$lonid};
14078:     }
14079: 
14080:     sub is_LC_dns {
14081:         &load_hosts_tab() if (!$loaded);
14082: 
14083:         my ($hostname) = @_;
14084:         return exists($LC_dns_serv{$hostname});
14085:     }
14086: 
14087: }
14088: 
14089: { 
14090:     my %iphost;
14091:     my %name_to_ip;
14092:     my %lonid_to_ip;
14093: 
14094:     sub get_hosts_from_ip {
14095: 	my ($ip) = @_;
14096: 	my %iphosts = &get_iphost();
14097: 	if (ref($iphosts{$ip})) {
14098: 	    return @{$iphosts{$ip}};
14099: 	}
14100: 	return;
14101:     }
14102:     
14103:     sub reset_hosts_ip_info {
14104: 	undef(%iphost);
14105: 	undef(%name_to_ip);
14106: 	undef(%lonid_to_ip);
14107:     }
14108: 
14109:     sub get_host_ip {
14110: 	my ($lonid) = @_;
14111: 	if (exists($lonid_to_ip{$lonid})) {
14112: 	    return $lonid_to_ip{$lonid};
14113: 	}
14114: 	my $name=&hostname($lonid);
14115:    	my $ip = gethostbyname($name);
14116: 	return if (!$ip || length($ip) ne 4);
14117: 	$ip=inet_ntoa($ip);
14118: 	$name_to_ip{$name}   = $ip;
14119: 	$lonid_to_ip{$lonid} = $ip;
14120: 	return $ip;
14121:     }
14122:     
14123:     sub get_iphost {
14124: 	my ($ignore_cache,$nocache) = @_;
14125: 
14126: 	if (!$ignore_cache) {
14127: 	    if (%iphost) {
14128: 		return %iphost;
14129: 	    }
14130: 	    my ($ip_info,$cached)=
14131: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14132: 	    if ($cached) {
14133: 		%iphost      = %{$ip_info->[0]};
14134: 		%name_to_ip  = %{$ip_info->[1]};
14135: 		%lonid_to_ip = %{$ip_info->[2]};
14136: 		return %iphost;
14137: 	    }
14138: 	}
14139: 
14140: 	# get yesterday's info for fallback
14141: 	my %old_name_to_ip;
14142: 	my ($ip_info,$cached)=
14143: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14144: 	if ($cached) {
14145: 	    %old_name_to_ip = %{$ip_info->[1]};
14146: 	}
14147: 
14148: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14149: 	foreach my $name (keys(%name_to_host)) {
14150: 	    my $ip;
14151: 	    if (!exists($name_to_ip{$name})) {
14152: 		$ip = gethostbyname($name);
14153: 		if (!$ip || length($ip) ne 4) {
14154: 		    if (defined($old_name_to_ip{$name})) {
14155: 			$ip = $old_name_to_ip{$name};
14156: 			&logthis("Can't find $name defaulting to old $ip");
14157: 		    } else {
14158: 			&logthis("Name $name no IP found");
14159: 			next;
14160: 		    }
14161: 		} else {
14162: 		    $ip=inet_ntoa($ip);
14163: 		}
14164: 		$name_to_ip{$name} = $ip;
14165: 	    } else {
14166: 		$ip = $name_to_ip{$name};
14167: 	    }
14168: 	    foreach my $id (@{ $name_to_host{$name} }) {
14169: 		$lonid_to_ip{$id} = $ip;
14170: 	    }
14171: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14172: 	}
14173:         unless ($nocache) {
14174: 	    &do_cache_new('iphost','iphost',
14175: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14176: 		          48*60*60);
14177:         }
14178: 
14179: 	return %iphost;
14180:     }
14181: 
14182:     #
14183:     #  Given a DNS returns the loncapa host name for that DNS 
14184:     # 
14185:     sub host_from_dns {
14186:         my ($dns) = @_;
14187:         my @hosts;
14188:         my $ip;
14189: 
14190:         if (exists($name_to_ip{$dns})) {
14191:             $ip = $name_to_ip{$dns};
14192:         }
14193:         if (!$ip) {
14194:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14195:             if (length($ip) == 4) { 
14196: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14197:             }
14198:         }
14199:         if ($ip) {
14200: 	    @hosts = get_hosts_from_ip($ip);
14201: 	    return $hosts[0];
14202:         }
14203:         return undef;
14204:     }
14205: 
14206:     sub get_internet_names {
14207:         my ($lonid) = @_;
14208:         return if ($lonid eq '');
14209:         my ($idnref,$cached)=
14210:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14211:         if ($cached) {
14212:             return $idnref;
14213:         }
14214:         my $ip = &get_host_ip($lonid);
14215:         my @hosts = &get_hosts_from_ip($ip);
14216:         my %iphost = &get_iphost();
14217:         my (@idns,%seen);
14218:         foreach my $id (@hosts) {
14219:             my $dom = &host_domain($id);
14220:             my $prim_id = &domain($dom,'primary');
14221:             my $prim_ip = &get_host_ip($prim_id);
14222:             next if ($seen{$prim_ip});
14223:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14224:                 foreach my $id (@{$iphost{$prim_ip}}) {
14225:                     my $intdom = &internet_dom($id);
14226:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14227:                         push(@idns,$intdom);
14228:                     }
14229:                 }
14230:             }
14231:             $seen{$prim_ip} = 1;
14232:         }
14233:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14234:     }
14235: 
14236: }
14237: 
14238: sub all_loncaparevs {
14239:     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);
14240: }
14241: 
14242: # ---------------------------------------------------------- Read loncaparev table
14243: {
14244:     sub load_loncaparevs { 
14245:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14246:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14247:                 while (my $configline=<$config>) {
14248:                     chomp($configline);
14249:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14250:                     $loncaparevs{$hostid}=$loncaparev;
14251:                 }
14252:                 close($config);
14253:             }
14254:         }
14255:     }
14256: }
14257: 
14258: # ---------------------------------------------------------- Read serverhostID table
14259: {
14260:     sub load_serverhomeIDs {
14261:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14262:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14263:                 while (my $configline=<$config>) {
14264:                     chomp($configline);
14265:                     my ($name,$id)=split(/:/,$configline);
14266:                     $serverhomeIDs{$name}=$id;
14267:                 }
14268:                 close($config);
14269:             }
14270:         }
14271:     }
14272: }
14273: 
14274: 
14275: BEGIN {
14276: 
14277: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14278:     unless ($readit) {
14279: {
14280:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14281:     %perlvar = (%perlvar,%{$configvars});
14282: }
14283: 
14284: 
14285: # ------------------------------------------------------ Read spare server file
14286: {
14287:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14288: 
14289:     while (my $configline=<$config>) {
14290:        chomp($configline);
14291:        if ($configline) {
14292: 	   my ($host,$type) = split(':',$configline,2);
14293: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14294: 	   push(@{ $spareid{$type} }, $host);
14295:        }
14296:     }
14297:     close($config);
14298: }
14299: # ------------------------------------------------------------ Read permissions
14300: {
14301:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14302: 
14303:     while (my $configline=<$config>) {
14304: 	chomp($configline);
14305: 	if ($configline) {
14306: 	    my ($role,$perm)=split(/ /,$configline);
14307: 	    if ($perm ne '') { $pr{$role}=$perm; }
14308: 	}
14309:     }
14310:     close($config);
14311: }
14312: 
14313: # -------------------------------------------- Read plain texts for permissions
14314: {
14315:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14316: 
14317:     while (my $configline=<$config>) {
14318: 	chomp($configline);
14319: 	if ($configline) {
14320: 	    my ($short,@plain)=split(/:/,$configline);
14321:             %{$prp{$short}} = ();
14322: 	    if (@plain > 0) {
14323:                 $prp{$short}{'std'} = $plain[0];
14324:                 for (my $i=1; $i<@plain; $i++) {
14325:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14326:                 }
14327:             }
14328: 	}
14329:     }
14330:     close($config);
14331: }
14332: 
14333: # ---------------------------------------------------------- Read package table
14334: {
14335:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14336: 
14337:     while (my $configline=<$config>) {
14338: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14339: 	chomp($configline);
14340: 	my ($short,$plain)=split(/:/,$configline);
14341: 	my ($pack,$name)=split(/\&/,$short);
14342: 	if ($plain ne '') {
14343: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14344: 	    $packagetab{$short}=$plain; 
14345: 	}
14346:     }
14347:     close($config);
14348: }
14349: 
14350: # ---------------------------------------------------------- Read loncaparev table
14351: 
14352: &load_loncaparevs();
14353: 
14354: # ---------------------------------------------------------- Read serverhostID table
14355: 
14356: &load_serverhomeIDs();
14357: 
14358: # ---------------------------------------------------------- Read releaseslist XML
14359: {
14360:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14361:     if (-e $file) {
14362:         my $parser = HTML::LCParser->new($file);
14363:         while (my $token = $parser->get_token()) {
14364:             if ($token->[0] eq 'S') {
14365:                 my $item = $token->[1];
14366:                 my $name = $token->[2]{'name'};
14367:                 my $value = $token->[2]{'value'};
14368:                 my $valuematch = $token->[2]{'valuematch'};
14369:                 my $namematch = $token->[2]{'namematch'};
14370:                 if ($item eq 'parameter') {
14371:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14372:                         my $release = $parser->get_text();
14373:                         $release =~ s/(^\s*|\s*$ )//gx;
14374:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14375:                     }
14376:                 } elsif ($item ne '' && $name ne '') {
14377:                     my $release = $parser->get_text();
14378:                     $release =~ s/(^\s*|\s*$ )//gx;
14379:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14380:                 }
14381:             }
14382:         }
14383:     }
14384: }
14385: 
14386: # ---------------------------------------------------------- Read managers table
14387: {
14388:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14389:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14390:             while (my $configline=<$config>) {
14391:                 chomp($configline);
14392:                 next if ($configline =~ /^\#/);
14393:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14394:                     $managerstab{$configline} = 1;
14395:                 }
14396:             }
14397:             close($config);
14398:         }
14399:     }
14400: }
14401: 
14402: # ------------- set up temporary directory
14403: {
14404:     $tmpdir = LONCAPA::tempdir();
14405: 
14406: }
14407: 
14408: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14409: 				'compress_threshold'=> 20_000,
14410:  			        });
14411: 
14412: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14413: $dumpcount=0;
14414: $locknum=0;
14415: 
14416: &logtouch();
14417: &logthis('<font color="yellow">INFO: Read configuration</font>');
14418: $readit=1;
14419:     {
14420: 	use integer;
14421: 	my $test=(2**32)+1;
14422: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14423: 	&logthis(" Detected 64bit platform ($_64bit)");
14424:     }
14425: }
14426: }
14427: 
14428: 1;
14429: __END__
14430: 
14431: =pod
14432: 
14433: =head1 NAME
14434: 
14435: Apache::lonnet - Subroutines to ask questions about things in the network.
14436: 
14437: =head1 SYNOPSIS
14438: 
14439: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14440: 
14441:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14442: 
14443: Common parameters:
14444: 
14445: =over 4
14446: 
14447: =item *
14448: 
14449: $uname : an internal username (if $cname expecting a course Id specifically)
14450: 
14451: =item *
14452: 
14453: $udom : a domain (if $cdom expecting a course's domain specifically)
14454: 
14455: =item *
14456: 
14457: $symb : a resource instance identifier
14458: 
14459: =item *
14460: 
14461: $namespace : the name of a .db file that contains the data needed or
14462: being set.
14463: 
14464: =back
14465: 
14466: =head1 OVERVIEW
14467: 
14468: lonnet provides subroutines which interact with the
14469: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14470: about classes, users, and resources.
14471: 
14472: For many of these objects you can also use this to store data about
14473: them or modify them in various ways.
14474: 
14475: =head2 Symbs
14476: 
14477: To identify a specific instance of a resource, LON-CAPA uses symbols
14478: or "symbs"X<symb>. These identifiers are built from the URL of the
14479: map, the resource number of the resource in the map, and the URL of
14480: the resource itself. The latter is somewhat redundant, but might help
14481: if maps change.
14482: 
14483: An example is
14484: 
14485:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14486: 
14487: The respective map entry is
14488: 
14489:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14490:   title="Problem 2">
14491:  </resource>
14492: 
14493: Symbs are used by the random number generator, as well as to store and
14494: restore data specific to a certain instance of for example a problem.
14495: 
14496: =head2 Storing And Retrieving Data
14497: 
14498: X<store()>X<cstore()>X<restore()>Three of the most important functions
14499: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14500: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14501: is is the non-critical message twin of cstore. These functions are for
14502: handlers to store a perl hash to a user's permanent data space in an
14503: easy manner, and to retrieve it again on another call. It is expected
14504: that a handler would use this once at the beginning to retrieve data,
14505: and then again once at the end to send only the new data back.
14506: 
14507: The data is stored in the user's data directory on the user's
14508: homeserver under the ID of the course.
14509: 
14510: The hash that is returned by restore will have all of the previous
14511: value for all of the elements of the hash.
14512: 
14513: Example:
14514: 
14515:  #creating a hash
14516:  my %hash;
14517:  $hash{'foo'}='bar';
14518: 
14519:  #storing it
14520:  &Apache::lonnet::cstore(\%hash);
14521: 
14522:  #changing a value
14523:  $hash{'foo'}='notbar';
14524: 
14525:  #adding a new value
14526:  $hash{'bar'}='foo';
14527:  &Apache::lonnet::cstore(\%hash);
14528: 
14529:  #retrieving the hash
14530:  my %history=&Apache::lonnet::restore();
14531: 
14532:  #print the hash
14533:  foreach my $key (sort(keys(%history))) {
14534:    print("\%history{$key} = $history{$key}");
14535:  }
14536: 
14537: Will print out:
14538: 
14539:  %history{1:foo} = bar
14540:  %history{1:keys} = foo:timestamp
14541:  %history{1:timestamp} = 990455579
14542:  %history{2:bar} = foo
14543:  %history{2:foo} = notbar
14544:  %history{2:keys} = foo:bar:timestamp
14545:  %history{2:timestamp} = 990455580
14546:  %history{bar} = foo
14547:  %history{foo} = notbar
14548:  %history{timestamp} = 990455580
14549:  %history{version} = 2
14550: 
14551: Note that the special hash entries C<keys>, C<version> and
14552: C<timestamp> were added to the hash. C<version> will be equal to the
14553: total number of versions of the data that have been stored. The
14554: C<timestamp> attribute will be the UNIX time the hash was
14555: stored. C<keys> is available in every historical section to list which
14556: keys were added or changed at a specific historical revision of a
14557: hash.
14558: 
14559: B<Warning>: do not store the hash that restore returns directly. This
14560: will cause a mess since it will restore the historical keys as if the
14561: were new keys. I.E. 1:foo will become 1:1:foo etc.
14562: 
14563: Calling convention:
14564: 
14565:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14566:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14567: 
14568: For more detailed information, see lonnet specific documentation.
14569: 
14570: =head1 RETURN MESSAGES
14571: 
14572: =over 4
14573: 
14574: =item * B<con_lost>: unable to contact remote host
14575: 
14576: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14577: when the connection is brought back up
14578: 
14579: =item * B<con_failed>: unable to contact remote host and unable to save message
14580: for later delivery
14581: 
14582: =item * B<error:>: an error a occurred, a description of the error follows the :
14583: 
14584: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14585: that was requested
14586: 
14587: =back
14588: 
14589: =head1 PUBLIC SUBROUTINES
14590: 
14591: =head2 Session Environment Functions
14592: 
14593: =over 4
14594: 
14595: =item * 
14596: X<appenv()>
14597: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14598: the user envirnoment file, and will be restored for each access this
14599: user makes during this session, also modifies the %env for the current
14600: process. Optional rolesarrayref - if defined contains a reference to an array
14601: of roles which are exempt from the restriction on modifying user.role entries 
14602: in the user's environment.db and in %env.    
14603: 
14604: =item *
14605: X<delenv()>
14606: B<delenv($delthis,$regexp)>: removes all items from the session
14607: environment file that begin with $delthis. If the 
14608: optional second arg - $regexp - is true, $delthis is treated as a 
14609: regular expression, otherwise \Q$delthis\E is used. 
14610: The values are also deleted from the current processes %env.
14611: 
14612: =item * get_env_multiple($name) 
14613: 
14614: gets $name from the %env hash, it seemlessly handles the cases where multiple
14615: values may be defined and end up as an array ref.
14616: 
14617: returns an array of values
14618: 
14619: =back
14620: 
14621: =head2 User Information
14622: 
14623: =over 4
14624: 
14625: =item *
14626: X<queryauthenticate()>
14627: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14628: authentication scheme
14629: 
14630: =item *
14631: X<authenticate()>
14632: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14633: authenticate user from domain's lib servers (first use the current
14634: one). C<$upass> should be the users password.
14635: $checkdefauth is optional (value is 1 if a check should be made to
14636:    authenticate user using default authentication method, and allow
14637:    account creation if username does not have account in the domain).
14638: $clientcancheckhost is optional (value is 1 if checking whether the
14639:    server can host will occur on the client side in lonauth.pm).   
14640: 
14641: =item *
14642: X<homeserver()>
14643: B<homeserver($uname,$udom)>: find the server which has
14644: the user's directory and files (there must be only one), this caches
14645: the answer, and also caches if there is a borken connection.
14646: 
14647: =item *
14648: X<idget()>
14649: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14650: a list of student/employee IDs or clicker IDs
14651: (student/employee IDs are a unique resource in a domain, there must be 
14652: only 1 ID per username, and only 1 username per ID in a specific domain).
14653: clickerIDs are not necessarily unique, as students might share clickers.
14654: (returns hash: id=>name,id=>name)
14655: 
14656: =item *
14657: X<idrget()>
14658: B<idrget($udom,@unames)>: find the IDs behind a list of
14659: usernames (returns hash: name=>id,name=>id)
14660: 
14661: =item *
14662: X<idput()>
14663: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14664: names and associated student/employee IDs or clicker IDs.
14665: 
14666: =item *
14667: X<iddel()>
14668: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14669: student/employee ID or clicker ID username look-ups from domain.
14670: The homeserver ($uhome) and namespace ($namespace) are optional.
14671: If no $uhome is provided, it will be determined usig &homeserver()
14672: for each user.  If no $namespace is provided, the default is ids.
14673: 
14674: =item *
14675: X<updateclickers()>
14676: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14677: clicker ID-to-username look-ups in clickers.db on library server.
14678: Permitted actions are add or del (i.e., add or delete). The 
14679: clickers.db contains clickerID as keys (escaped), and each corresponding
14680: value is an escaped comma-separated list of usernames (for whom the
14681: library server is the homeserver), who registered that particular ID.
14682: If $critical is true, the update will be sent via &critical, otherwise
14683: &reply() will be used.
14684: 
14685: =item *
14686: X<rolesinit()>
14687: B<rolesinit($udom,$username)>: get user privileges.
14688: returns user role, first access and timer interval hashes
14689: 
14690: =item *
14691: X<privileged()>
14692: B<privileged($username,$domain)>: returns a true if user has a
14693: privileged and active role (i.e. su or dc), false otherwise.
14694: 
14695: =item *
14696: X<getsection()>
14697: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14698: course $cname, return section name/number or '' for "not in course"
14699: and '-1' for "no section"
14700: 
14701: =item *
14702: X<userenvironment()>
14703: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14704: passed in @what from the requested user's environment, returns a hash
14705: 
14706: =item * 
14707: X<userlog_query()>
14708: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14709: activity.log file. %filters defines filters applied when parsing the
14710: log file. These can be start or end timestamps, or the type of action
14711: - log to look for Login or Logout events, check for Checkin or
14712: Checkout, role for role selection. The response is in the form
14713: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14714: escaped strings of the action recorded in the activity.log file.
14715: 
14716: =back
14717: 
14718: =head2 User Roles
14719: 
14720: =over 4
14721: 
14722: =item *
14723: 
14724: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14725: returns codes for allowed actions.
14726: 
14727: The first argument is required, all others are optional.
14728: 
14729: $priv is the privilege being checked.
14730: $uri contains additional information about what is being checked for access (e.g.,
14731: URL, course ID etc.). 
14732: $symb is the unique resource instance identifier in a course; if needed,
14733: but not provided, it will be retrieved via a call to &symbread(). 
14734: $role is the role for which a priv is being checked (only used if priv is evb). 
14735: $clientip is the user's IP address (only used when checking for access to portfolio 
14736: files).
14737: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14738: prevents recursive calls to &allowed.
14739: 
14740:  F: full access
14741:  U,I,K: authentication modes (cxx only)
14742:  '': forbidden
14743:  1: user needs to choose course
14744:  2: browse allowed
14745:  A: passphrase authentication needed
14746:  B: access temporarily blocked because of a blocking event in a course.
14747: 
14748: =item *
14749: 
14750: constructaccess($url,$setpriv) : check for access to construction space URL
14751: 
14752: See if the owner domain and name in the URL match those in the
14753: expected environment.  If so, return three element list
14754: ($ownername,$ownerdomain,$ownerhome).
14755: 
14756: Otherwise return the null string.
14757: 
14758: If second argument 'setpriv' is true, it assigns the privileges,
14759: and returns the same three element list, unless the owner has
14760: blocked "ad hoc" Domain Coordinator access to the Author Space,
14761: in which case the null string is returned.
14762: 
14763: =item *
14764: 
14765: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14766: define a custom role rolename set privileges in format of lonTabs/roles.tab
14767: for system, domain, and course level. $uname and $udom are optional (current
14768: user's username and domain will be used when either of $uname or $udom are absent.
14769: 
14770: =item *
14771: 
14772: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14773: (rolesplain.tab); plain text explanation of a user role term.
14774: $type is Course (default) or Community.
14775: If $forcedefault evaluates to true, text returned will be default 
14776: text for $type. Otherwise, if this is a course, the text returned 
14777: will be a custom name for the role (if defined in the course's 
14778: environment).  If no custom name is defined the default is returned.
14779:    
14780: =item *
14781: 
14782: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14783: All arguments are optional. Returns a hash of a roles, either for
14784: co-author/assistant author roles for a user's Construction Space
14785: (default), or if $context is 'userroles', roles for the user himself,
14786: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14787: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14788: For each key, value is set to colon-separated start and end times for
14789: the role.  If no username and domain are specified, will default to
14790: current user/domain. Types, roles, and roledoms are references to arrays
14791: of role statuses (active, future or previous), roles 
14792: (e.g., cc,in, st etc.) and domains of the roles which can be used
14793: to restrict the list of roles reported. If no array ref is 
14794: provided for types, will default to return only active roles.
14795: 
14796: =item *
14797: 
14798: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14799: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14800: 
14801: Additional optional arguments are: $type (if role checking is to be restricted 
14802: to certain user status types -- previous (expired roles), active (currently
14803: available roles) or future (roles available in the future), and
14804: $hideprivileged -- if true will not report course roles for users who
14805: have active Domain Coordinator role in course's domain or in additional
14806: domains (specified in 'Domains to check for privileged users' in course
14807: environment -- set via:  Course Settings -> Classlists and staff listing).
14808: 
14809: =item *
14810: 
14811: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14812: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14813: $possdomains and $possroles are optional array refs -- to domains to check and
14814: roles to check.  If $possdomains is not specified, a dump will be done of the
14815: users' roles.db to check for a dc or su role in any domain. This can be
14816: time consuming if &privileged is called repeatedly (e.g., when displaying a
14817: classlist), so in such cases, supplying a $possdomains array is preferred, as
14818: this then allows &privileged_by_domain() to be used, which caches the identity
14819: of privileged users, eliminating the need for repeated calls to &dump().
14820: 
14821: =item *
14822: 
14823: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14824: where the outer hash keys are domains specified in the $possdomains array ref,
14825: next inner hash keys are privileged roles specified in the $roles array ref,
14826: and the innermost hash contains key = value pairs for username:domain = end:start
14827: for active or future "privileged" users with that role in that domain. To avoid
14828: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14829: innerhash are cached using priv_$role and $dom as the identifiers.
14830: 
14831: =back
14832: 
14833: =head2 User Modification
14834: 
14835: =over 4
14836: 
14837: =item *
14838: 
14839: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14840: user for the level given by URL.  Optional start and end dates (leave empty
14841: string or zero for "no date")
14842: 
14843: =item *
14844: 
14845: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14846: change a users, password, possible return values are: ok,
14847: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14848: refused
14849: 
14850: =item *
14851: 
14852: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14853: 
14854: =item *
14855: 
14856: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14857:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14858: 
14859: will update user information (firstname,middlename,lastname,generation,
14860: permanentemail), and if forceid is true, student/employee ID also.
14861: A user's institutional affiliation(s) can also be updated.
14862: User information fields will not be overwritten with empty entries 
14863: unless the field is included in the $candelete array reference.
14864: This array is included when a single user is modified via "Manage Users",
14865: or when Autoupdate.pl is run by cron in a domain.
14866: 
14867: =item *
14868: 
14869: modifystudent
14870: 
14871: modify a student's enrollment and identification information.
14872: The course id is resolved based on the current user's environment.  
14873: This means the invoking user must be a course coordinator or otherwise
14874: associated with a course.
14875: 
14876: This call is essentially a wrapper for lonnet::modifyuser and
14877: lonnet::modify_student_enrollment
14878: 
14879: Inputs: 
14880: 
14881: =over 4
14882: 
14883: =item B<$udom> Student's loncapa domain
14884: 
14885: =item B<$uname> Student's loncapa login name
14886: 
14887: =item B<$uid> Student/Employee ID
14888: 
14889: =item B<$umode> Student's authentication mode
14890: 
14891: =item B<$upass> Student's password
14892: 
14893: =item B<$first> Student's first name
14894: 
14895: =item B<$middle> Student's middle name
14896: 
14897: =item B<$last> Student's last name
14898: 
14899: =item B<$gene> Student's generation
14900: 
14901: =item B<$usec> Student's section in course
14902: 
14903: =item B<$end> Unix time of the roles expiration
14904: 
14905: =item B<$start> Unix time of the roles start date
14906: 
14907: =item B<$forceid> If defined, allow $uid to be changed
14908: 
14909: =item B<$desiredhome> server to use as home server for student
14910: 
14911: =item B<$email> Student's permanent e-mail address
14912: 
14913: =item B<$type> Type of enrollment (auto or manual)
14914: 
14915: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14916: 
14917: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14918: 
14919: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14920: 
14921: =item B<$context> role change context (shown in User Management Logs display in a course)
14922: 
14923: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14924: 
14925: =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.
14926: 
14927: =back
14928: 
14929: =item *
14930: 
14931: modify_student_enrollment
14932: 
14933: Change a student's enrollment status in a class.  The environment variable
14934: 'role.request.course' must be defined for this function to proceed.
14935: 
14936: Inputs:
14937: 
14938: =over 4
14939: 
14940: =item $udom, student's domain
14941: 
14942: =item $uname, student's name
14943: 
14944: =item $uid, student's user id
14945: 
14946: =item $first, student's first name
14947: 
14948: =item $middle
14949: 
14950: =item $last
14951: 
14952: =item $gene
14953: 
14954: =item $usec
14955: 
14956: =item $end
14957: 
14958: =item $start
14959: 
14960: =item $type
14961: 
14962: =item $locktype
14963: 
14964: =item $cid
14965: 
14966: =item $selfenroll
14967: 
14968: =item $context
14969: 
14970: =item $credits, number of credits student will earn from this class
14971: 
14972: =item $instsec, institutional course section code for student
14973: 
14974: =back
14975: 
14976: 
14977: =item *
14978: 
14979: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14980: custom role; give a custom role to a user for the level given by URL.  Specify
14981: name and domain of role author, and role name
14982: 
14983: =item *
14984: 
14985: revokerole($udom,$uname,$url,$role) : revoke a role for url
14986: 
14987: =item *
14988: 
14989: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14990: 
14991: =back
14992: 
14993: =head2 Course Infomation
14994: 
14995: =over 4
14996: 
14997: =item *
14998: 
14999: coursedescription($courseid,$options) : returns a hash of information about the
15000: specified course id, including all environment settings for the
15001: course, the description of the course will be in the hash under the
15002: key 'description'
15003: 
15004: $options is an optional parameter that if supplied is a hash reference that controls
15005: what how this function works.  It has the following key/values:
15006: 
15007: =over 4
15008: 
15009: =item freshen_cache
15010: 
15011: If defined, and the environment cache for the course is valid, it is 
15012: returned in the returned hash.
15013: 
15014: =item one_time
15015: 
15016: If defined, the last cache time is set to _now_
15017: 
15018: =item user
15019: 
15020: If defined, the supplied username is used instead of the current user.
15021: 
15022: 
15023: =back
15024: 
15025: =item *
15026: 
15027: resdata($name,$domain,$type,@which) : request for current parameter
15028: setting for a specific $type, where $type is either 'course' or 'user',
15029: @what should be a list of parameters to ask about. This routine caches
15030: answers for 10 minutes.
15031: 
15032: =item *
15033: 
15034: get_courseresdata($courseid, $domain) : dump the entire course resource
15035: data base, returning a hash that is keyed by the resource name and has
15036: values that are the resource value.  I believe that the timestamps and
15037: versions are also returned.
15038: 
15039: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15040: supplemental content area. This routine caches the number of files for 
15041: 10 minutes.
15042: 
15043: =back
15044: 
15045: =head2 Course Modification
15046: 
15047: =over 4
15048: 
15049: =item *
15050: 
15051: writecoursepref($courseid,%prefs) : write preferences (environment
15052: database) for a course
15053: 
15054: =item *
15055: 
15056: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15057: 
15058: =item *
15059: 
15060: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15061: 
15062: =item *
15063: 
15064: is_course($courseid), is_course($cdom, $cnum)
15065: 
15066: Accepts either a combined $courseid (in the form of domain_courseid) or the
15067: two component version $cdom, $cnum. It checks if the specified course exists.
15068: 
15069: Returns:
15070:     undef if the course doesn't exist, otherwise
15071:     in scalar context the combined courseid.
15072:     in list context the two components of the course identifier, domain and 
15073:     courseid.    
15074: 
15075: =back
15076: 
15077: =head2 Resource Subroutines
15078: 
15079: =over 4
15080: 
15081: =item *
15082: 
15083: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15084: 
15085: =item *
15086: 
15087: repcopy($filename) : subscribes to the requested file, and attempts to
15088: replicate from the owning library server, Might return
15089: 'unavailable', 'not_found', 'forbidden', 'ok', or
15090: 'bad_request', also attempts to grab the metadata for the
15091: resource. Expects the local filesystem pathname
15092: (/home/httpd/html/res/....)
15093: 
15094: =back
15095: 
15096: =head2 Resource Information
15097: 
15098: =over 4
15099: 
15100: =item *
15101: 
15102: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15103: and returns the value of a variety of different possible values,
15104: $varname should be a request string, and the other parameters can be
15105: used to specify who and what one is asking about. Ordinarily, $cid 
15106: does not need to be specified, as it is retrived from 
15107: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15108: within lonuserstate::loadmap() when initializing a course, before
15109: $env{'request.course.id'} has been set, so it needs to be provided
15110: in that one case.
15111: 
15112: Possible values for $varname are environment.lastname (or other item
15113: from the envirnment hash), user.name (or someother aspect about the
15114: user), resource.0.maxtries (or some other part and parameter of a
15115: resource)
15116: 
15117: =item *
15118: 
15119: directcondval($number) : get current value of a condition; reads from a state
15120: string
15121: 
15122: =item *
15123: 
15124: condval($condidx) : value of condition index based on state
15125: 
15126: =item *
15127: 
15128: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15129: resource's metadata, $what should be either a specific key, or either
15130: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15131: packages that this resource currently uses, the last 3 arguments are 
15132: only used internally for recursive metadata.
15133: 
15134: the toolsymb is only used where the uri is for an external tool (for which
15135: the uri as well as the symb are guaranteed to be unique).
15136: 
15137: this function automatically caches all requests except any made recursively
15138: to retrieve a list of metadata keys for an imported library file ($liburi is 
15139: defined).
15140: 
15141: =item *
15142: 
15143: metadata_query($query,$custom,$customshow) : make a metadata query against the
15144: network of library servers; returns file handle of where SQL and regex results
15145: will be stored for query
15146: 
15147: =item *
15148: 
15149: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15150: return symbolic list entry (all arguments optional). 
15151: 
15152: Args: filename is the filename (including path) for the file for which a symb 
15153: is required; donotrecurse, if true will prevent calls to allowed() being made 
15154: to check access status if more than one resource was found in the bighash 
15155: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15156: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15157: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15158: cause possible symbs to be checked to determine if they are subject to content
15159: blocking, if so they will not be included as possible symbs; possibles is a
15160: ref to a hash, which, as a side effect, will be populated with all possible 
15161: symbs (content blocking not tested).
15162:  
15163: returns the data handle
15164: 
15165: =item *
15166: 
15167: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15168: and is a possible symb for the URL in $thisfn, and if is an encrypted
15169: resource that the user accessed using /enc/ returns a 1 on success, 0
15170: on failure, user must be in a course, as it assumes the existence of
15171: the course initial hash, and uses $env('request.course.id'}.  The third
15172: arg is an optional reference to a scalar.  If this arg is passed in the 
15173: call to symbverify, it will be set to 1 if the symb has been set to be 
15174: encrypted; otherwise it will be null.  
15175: 
15176: =item *
15177: 
15178: symbclean($symb) : removes versions numbers from a symb, returns the
15179: cleaned symb
15180: 
15181: =item *
15182: 
15183: is_on_map($uri) : checks if the $uri is somewhere on the current
15184: course map, user must be in a course for it to work.
15185: 
15186: =item *
15187: 
15188: numval($salt) : return random seed value (addend for rndseed)
15189: 
15190: =item *
15191: 
15192: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15193: a random seed, all arguments are optional, if they aren't sent it uses the
15194: environment to derive them. Note: if symb isn't sent and it can't get one
15195: from &symbread it will use the current time as its return value
15196: 
15197: =item *
15198: 
15199: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15200: unfakeable, receipt
15201: 
15202: =item *
15203: 
15204: receipt() : API to ireceipt working off of env values; given out to users
15205: 
15206: =item *
15207: 
15208: countacc($url) : count the number of accesses to a given URL
15209: 
15210: =item *
15211: 
15212: 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
15213: 
15214: =item *
15215: 
15216: 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)
15217: 
15218: =item *
15219: 
15220: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15221: 
15222: =item *
15223: 
15224: devalidate($symb) : devalidate temporary spreadsheet calculations,
15225: forcing spreadsheet to reevaluate the resource scores next time.
15226: 
15227: =item * 
15228: 
15229: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15230: when viewing in course context.
15231: 
15232:  input: six args -- filename (decluttered), course number, course domain,
15233:                     url, symb (if registered) and group (if this is a 
15234:                     group item -- e.g., bulletin board, group page etc.).
15235: 
15236:  output: array of five scalars --
15237:          $cfile -- url for file editing if editable on current server
15238:          $home -- homeserver of resource (i.e., for author if published,
15239:                                           or course if uploaded.).
15240:          $switchserver --  1 if server switch will be needed.
15241:          $forceedit -- 1 if icon/link should be to go to edit mode 
15242:          $forceview -- 1 if icon/link should be to go to view mode
15243: 
15244: =item *
15245: 
15246: is_course_upload($file,$cnum,$cdom)
15247: 
15248: Used in course context to determine if current file was uploaded to 
15249: the course (i.e., would be found in /userfiles/docs on the course's 
15250: homeserver.
15251: 
15252:   input: 3 args -- filename (decluttered), course number and course domain.
15253:   output: boolean -- 1 if file was uploaded.
15254: 
15255: =back
15256: 
15257: =head2 Storing/Retreiving Data
15258: 
15259: =over 4
15260: 
15261: =item *
15262: 
15263: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15264: permanently for this url; hashref needs to be given and should be a \%hashname;
15265: the remaining args aren't required and if they aren't passed or are '' they will
15266: be derived from the env (with the exception of $laststore, which is an 
15267: optional arg used when a user's submission is stored in grading).
15268: $laststore is $version=$timestamp, where $version is the most recent version
15269: number retrieved for the corresponding $symb in the $namespace db file, and
15270: $timestamp is the timestamp for that transaction (UNIX time).
15271: $laststore is currently only passed when cstore() is called by 
15272: structuretags::finalize_storage().
15273: 
15274: =item *
15275: 
15276: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15277: but uses critical subroutine
15278: 
15279: =item *
15280: 
15281: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15282: all args are optional
15283: 
15284: =item *
15285: 
15286: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15287: dumps the complete (or key matching regexp) namespace into a hash
15288: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15289: normally &store()ed into
15290: 
15291: $range should be either an integer '100' (give me the first 100
15292:                                            matching records)
15293:               or be  two integers sperated by a - with no spaces
15294:                  '30-50' (give me the 30th through the 50th matching
15295:                           records)
15296: 
15297: 
15298: =item *
15299: 
15300: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15301: replaces a &store() version of data with a replacement set of data
15302: for a particular resource in a namespace passed in the $storehash hash 
15303: reference. If $tolog is true, the transaction is logged in the courselog
15304: with an action=PUTSTORE.
15305: 
15306: =item *
15307: 
15308: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15309: works very similar to store/cstore, but all data is stored in a
15310: temporary location and can be reset using tmpreset, $storehash should
15311: be a hash reference, returns nothing on success
15312: 
15313: =item *
15314: 
15315: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15316: similar to restore, but all data is stored in a temporary location and
15317: can be reset using tmpreset. Returns a hash of values on success,
15318: error string otherwise.
15319: 
15320: =item *
15321: 
15322: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15323: deltes all keys for $symb form the temporary storage hash.
15324: 
15325: =item *
15326: 
15327: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15328: reference filled in from namesp ($udom and $uname are optional)
15329: 
15330: =item *
15331: 
15332: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15333: namesp ($udom and $uname are optional)
15334: 
15335: =item *
15336: 
15337: dump($namespace,$udom,$uname,$regexp,$range) : 
15338: dumps the complete (or key matching regexp) namespace into a hash
15339: ($udom, $uname, $regexp, $range are optional)
15340: 
15341: $range should be either an integer '100' (give me the first 100
15342:                                            matching records)
15343:               or be  two integers sperated by a - with no spaces
15344:                  '30-50' (give me the 30th through the 50th matching
15345:                           records)
15346: =item *
15347: 
15348: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15349: $store can be a scalar, an array reference, or if the amount to be 
15350: incremented is > 1, a hash reference.
15351: 
15352: ($udom and $uname are optional)
15353: 
15354: =item *
15355: 
15356: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15357: ($udom and $uname are optional)
15358: 
15359: =item *
15360: 
15361: cput($namespace,$storehash,$udom,$uname) : critical put
15362: ($udom and $uname are optional)
15363: 
15364: =item *
15365: 
15366: newput($namespace,$storehash,$udom,$uname) :
15367: 
15368: Attempts to store the items in the $storehash, but only if they don't
15369: currently exist, if this succeeds you can be certain that you have 
15370: successfully created a new key value pair in the $namespace db.
15371: 
15372: 
15373: Args:
15374:  $namespace: name of database to store values to
15375:  $storehash: hashref to store to the db
15376:  $udom: (optional) domain of user containing the db
15377:  $uname: (optional) name of user caontaining the db
15378: 
15379: Returns:
15380:  'ok' -> succeeded in storing all keys of $storehash
15381:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15382:                         least <key> already existed in the db (other
15383:                         requested keys may also already exist)
15384:  'error: <msg>' -> unable to tie the DB or other error occurred
15385:  'con_lost' -> unable to contact request server
15386:  'refused' -> action was not allowed by remote machine
15387: 
15388: 
15389: =item *
15390: 
15391: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15392: reference filled in from namesp (encrypts the return communication)
15393: ($udom and $uname are optional)
15394: 
15395: =item *
15396: 
15397: log($udom,$name,$home,$message) : write to permanent log for user; use
15398: critical subroutine
15399: 
15400: =item *
15401: 
15402: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15403: array reference filled in from namespace found in domain level on either
15404: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15405: 
15406: =item *
15407: 
15408: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15409: domain level either on specified domain server ($uhome) or primary domain 
15410: server ($udom and $uhome are optional)
15411: 
15412: =item * 
15413: 
15414: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15415: for: authentication, language, quotas, timezone, date locale, and portal URL in
15416: the target domain.
15417: 
15418: May also include additional key => value pairs for the following groups:
15419: 
15420: =over
15421: 
15422: =item
15423: disk quotas (MB allocated by default to portfolios and authoring spaces).
15424: 
15425: =over
15426: 
15427: =item defaultquota, authorquota
15428: 
15429: =back
15430: 
15431: =item
15432: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15433: portfolio for users).
15434: 
15435: =over
15436: 
15437: =item
15438: aboutme, blog, webdav, portfolio
15439: 
15440: =back
15441: 
15442: =item
15443: requestcourses: ability to request courses, and how requests are processed.
15444: 
15445: =over
15446: 
15447: =item
15448: official, unofficial, community, textbook, placement
15449: 
15450: =back
15451: 
15452: =item
15453: inststatus: types of institutional affiliation, and order in which they are displayed.
15454: 
15455: =over
15456: 
15457: =item
15458: inststatustypes, inststatusorder, inststatusguest
15459: 
15460: =back
15461: 
15462: =item
15463: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15464: for course's uploaded content.
15465: 
15466: =over
15467: 
15468: =item
15469: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15470: communityquota, textbookquota, placementquota
15471: 
15472: =back
15473: 
15474: =item
15475: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15476: on your servers.
15477: 
15478: =over
15479: 
15480: =item 
15481: remotesessions, hostedsessions
15482: 
15483: =back
15484: 
15485: =back
15486: 
15487: In cases where a domain coordinator has never used the "Set Domain Configuration"
15488: utility to create a configuration.db file on a domain's primary library server 
15489: only the following domain defaults: auth_def, auth_arg_def, lang_def
15490: -- corresponding values are authentication type (internal, krb4, krb5,
15491: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15492: will be available. Values are retrieved from cache (if current), unless the
15493: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15494: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15495: 
15496: Typical usage:
15497: 
15498: %domdefaults = &get_domain_defaults($target_domain);
15499: 
15500: =back
15501: 
15502: =head2 Network Status Functions
15503: 
15504: =over 4
15505: 
15506: =item *
15507: 
15508: dirlist() : return directory list based on URI (first arg).
15509: 
15510: Inputs: 1 required, 5 optional.
15511: 
15512: =over
15513: 
15514: =item 
15515: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15516: 
15517: =item
15518: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15519: 
15520: =item
15521: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15522: 
15523: =item
15524: $getpropath - boolean: 1 if prepend path using &propath(). 
15525: 
15526: =item
15527: $getuserdir - boolean: 1 if prepend path for "userfiles".
15528: 
15529: =item 
15530: $alternateRoot - path to prepend in place of path from $uri.
15531: 
15532: =back
15533: 
15534: Returns: Array of up to two items.
15535: 
15536: =over
15537: 
15538: a reference to an array of files/subdirectories
15539: 
15540: =over
15541: 
15542: Each element in the array of files/subdirectories is a & separated list of
15543: item name and the result of running stat on the item.  If dirlist was requested
15544: for a file instead of a directory, the item name will be ''. For a directory 
15545: listing, if the item is a metadata file, the element will end &N&M 
15546: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15547: default copyright set (1).  
15548: 
15549: =back
15550: 
15551: a scalar containing error condition (if encountered).
15552: 
15553: =over
15554: 
15555: =item 
15556: no_host (no homeserver identified for $username:$domain).
15557: 
15558: =item 
15559: no_such_host (server contacted for listing not identified as valid host).
15560: 
15561: =item 
15562: con_lost (connection to remote server failed).
15563: 
15564: =item 
15565: refused (invalid $username:$domain received on lond side).
15566: 
15567: =item 
15568: no_such_dir (directory at specified path on lond side does not exist). 
15569: 
15570: =item 
15571: empty (directory at specified path on lond side is empty).
15572: 
15573: =over
15574: 
15575: This is currently not encountered because the &ls3, &ls2, 
15576: &ls (_handler) routines on the lond side do not filter out
15577: . and .. from a directory listing. 
15578: 
15579: =back
15580: 
15581: =back
15582: 
15583: =back
15584: 
15585: =item *
15586: 
15587: spareserver() : find server with least workload from spare.tab
15588: 
15589: 
15590: =item *
15591: 
15592: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15593: if there is no corresponding loncapa host.
15594: 
15595: =back
15596: 
15597: 
15598: =head2 Apache Request
15599: 
15600: =over 4
15601: 
15602: =item *
15603: 
15604: ssi($url,%hash) : server side include, does a complete request cycle on url to
15605: localhost, posts hash
15606: 
15607: =back
15608: 
15609: =head2 Data to String to Data
15610: 
15611: =over 4
15612: 
15613: =item *
15614: 
15615: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15616: and '&' separators, supports elements that are arrayrefs and hashrefs
15617: 
15618: =item *
15619: 
15620: hashref2str($hashref) : convert a hashref into a string complete with
15621: escaping and '=' and '&' separators, supports elements that are
15622: arrayrefs and hashrefs
15623: 
15624: =item *
15625: 
15626: arrayref2str($arrayref) : convert an arrayref into a string complete
15627: with escaping and '&' separators, supports elements that are arrayrefs
15628: and hashrefs
15629: 
15630: =item *
15631: 
15632: str2hash($string) : convert string to hash using unescaping and
15633: splitting on '=' and '&', supports elements that are arrayrefs and
15634: hashrefs
15635: 
15636: =item *
15637: 
15638: str2array($string) : convert string to hash using unescaping and
15639: splitting on '&', supports elements that are arrayrefs and hashrefs
15640: 
15641: =back
15642: 
15643: =head2 Logging Routines
15644: 
15645: 
15646: These routines allow one to make log messages in the lonnet.log and
15647: lonnet.perm logfiles.
15648: 
15649: =over 4
15650: 
15651: =item *
15652: 
15653: logtouch() : make sure the logfile, lonnet.log, exists
15654: 
15655: =item *
15656: 
15657: logthis() : append message to the normal lonnet.log file, it gets
15658: preiodically rolled over and deleted.
15659: 
15660: =item *
15661: 
15662: logperm() : append a permanent message to lonnet.perm.log, this log
15663: file never gets deleted by any automated portion of the system, only
15664: messages of critical importance should go in here.
15665: 
15666: 
15667: =back
15668: 
15669: =head2 General File Helper Routines
15670: 
15671: =over 4
15672: 
15673: =item *
15674: 
15675: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15676: (a) files in /uploaded
15677:   (i) If a local copy of the file exists - 
15678:       compares modification date of local copy with last-modified date for 
15679:       definitive version stored on home server for course. If local copy is 
15680:       stale, requests a new version from the home server and stores it. 
15681:       If the original has been removed from the home server, then local copy 
15682:       is unlinked.
15683:   (ii) If local copy does not exist -
15684:       requests the file from the home server and stores it. 
15685:   
15686:   If $caller is 'uploadrep':  
15687:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15688:     for request for files originally uploaded via DOCS. 
15689:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15690:   
15691:   Otherwise:
15692:      This indicates a call from the content generation phase of the request.
15693:      -  returns the entire contents of the file or -1.
15694:      
15695: (b) files in /res
15696:    - returns the entire contents of a file or -1; 
15697:    it properly subscribes to and replicates the file if neccessary.
15698: 
15699: 
15700: =item *
15701: 
15702: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15703:                   reference
15704: 
15705: returns either a stat() list of data about the file or an empty list
15706: if the file doesn't exist or couldn't find out about it (connection
15707: problems or user unknown)
15708: 
15709: =item *
15710: 
15711: filelocation($dir,$file) : returns file system location of a file
15712: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15713: directory that relative $file lookups are to looked in ($dir of /a/dir
15714: and a file of ../bob will become /a/bob)
15715: 
15716: =item *
15717: 
15718: hreflocation($dir,$file) : returns file system location or a URL; same as
15719: filelocation except for hrefs
15720: 
15721: =item *
15722: 
15723: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15724: also removes beginning /home/httpd/html unless /priv/ follows it.
15725: 
15726: =back
15727: 
15728: =head2 Usererfile file routines (/uploaded*)
15729: 
15730: =over 4
15731: 
15732: =item *
15733: 
15734: userfileupload(): main rotine for putting a file in a user or course's
15735:                   filespace, arguments are,
15736: 
15737:  formname - required - this is the name of the element in $env where the
15738:            filename, and the contents of the file to create/modifed exist
15739:            the filename is in $env{'form.'.$formname.'.filename'} and the
15740:            contents of the file is located in $env{'form.'.$formname}
15741:  context - if coursedoc, store the file in the course of the active role
15742:              of the current user; 
15743:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15744:            if 'canceloverwrite': delete file in tmp/overwrites directory
15745:  subdir - required - subdirectory to put the file in under ../userfiles/
15746:          if undefined, it will be placed in "unknown"
15747: 
15748:  (This routine calls clean_filename() to remove any dangerous
15749:  characters from the filename, and then calls finuserfileupload() to
15750:  complete the transaction)
15751: 
15752:  returns either the url of the uploaded file (/uploaded/....) if successful
15753:  and /adm/notfound.html if unsuccessful
15754: 
15755: =item *
15756: 
15757: clean_filename(): routine for cleaing a filename up for storage in
15758:                  userfile space, argument is:
15759: 
15760:  filename - proposed filename
15761: 
15762: returns: the new clean filename
15763: 
15764: =item *
15765: 
15766: finishuserfileupload(): routine that creates and sends the file to
15767: userspace, probably shouldn't be called directly
15768: 
15769:   docuname: username or courseid of destination for the file
15770:   docudom: domain of user/course of destination for the file
15771:   formname: same as for userfileupload()
15772:   fname: filename (including subdirectories) for the file
15773:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15774:   allfiles: reference to hash used to store objects found by parser
15775:   codebase: reference to hash used for codebases of java objects found by parser
15776:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15777:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15778:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15779:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15780:   context: if 'overwrite', will move the uploaded file from its temporary location to
15781:             userfiles to facilitate overwriting a previously uploaded file with same name.
15782:   mimetype: reference to scalar to accommodate mime type determined
15783:             from File::MMagic if $parser = parse.
15784: 
15785:  returns either the url of the uploaded file (/uploaded/....) if successful
15786:  and /adm/notfound.html if unsuccessful (or an error message if context 
15787:  was 'overwrite').
15788:  
15789: 
15790: =item *
15791: 
15792: renameuserfile(): renames an existing userfile to a new name
15793: 
15794:   Args:
15795:    docuname: username or courseid of destination for the file
15796:    docudom: domain of user/course of destination for the file
15797:    old: current file name (including any subdirs under userfiles)
15798:    new: desired file name (including any subdirs under userfiles)
15799: 
15800: =item *
15801: 
15802: mkdiruserfile(): creates a directory is a userfiles dir
15803: 
15804:   Args:
15805:    docuname: username or courseid of destination for the file
15806:    docudom: domain of user/course of destination for the file
15807:    dir: dir to create (including any subdirs under userfiles)
15808: 
15809: =item *
15810: 
15811: removeuserfile(): removes a file that exists in userfiles
15812: 
15813:   Args:
15814:    docuname: username or courseid of destination for the file
15815:    docudom: domain of user/course of destination for the file
15816:    fname: filname to delete (including any subdirs under userfiles)
15817: 
15818: =item *
15819: 
15820: removeuploadedurl(): convience function for removeuserfile()
15821: 
15822:   Args:
15823:    url:  a full /uploaded/... url to delete
15824: 
15825: =item * 
15826: 
15827: get_portfile_permissions():
15828:   Args:
15829:     domain: domain of user or course contain the portfolio files
15830:     user: name of user or num of course contain the portfolio files
15831:   Returns:
15832:     hashref of a dump of the proper file_permissions.db
15833:    
15834: 
15835: =item * 
15836: 
15837: get_access_controls():
15838: 
15839: Args:
15840:   current_permissions: the hash ref returned from get_portfile_permissions()
15841:   group: (optional) the group you want the files associated with
15842:   file: (optional) the file you want access info on
15843: 
15844: Returns:
15845:     a hash (keys are file names) of hashes containing
15846:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15847:         values are XML containing access control settings (see below) 
15848: 
15849: Internal notes:
15850: 
15851:  access controls are stored in file_permissions.db as key=value pairs.
15852:     key -> path to file/file_name\0uniqueID:scope_end_start
15853:         where scope -> public,guest,course,group,domains or users.
15854:               end -> UNIX time for end of access (0 -> no end date)
15855:               start -> UNIX time for start of access
15856: 
15857:     value -> XML description of access control
15858:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15859:             <start></start>
15860:             <end></end>
15861: 
15862:             <password></password>  for scope type = guest
15863: 
15864:             <domain></domain>     for scope type = course or group
15865:             <number></number>
15866:             <roles id="">
15867:              <role></role>
15868:              <access></access>
15869:              <section></section>
15870:              <group></group>
15871:             </roles>
15872: 
15873:             <dom></dom>         for scope type = domains
15874: 
15875:             <users>             for scope type = users
15876:              <user>
15877:               <uname></uname>
15878:               <udom></udom>
15879:              </user>
15880:             </users>
15881:            </scope> 
15882:               
15883:  Access data is also aggregated for each file in an additional key=value pair:
15884:  key -> path to file/file_name\0accesscontrol 
15885:  value -> reference to hash
15886:           hash contains key = value pairs
15887:           where key = uniqueID:scope_end_start
15888:                 value = UNIX time record was last updated
15889: 
15890:           Used to improve speed of look-ups of access controls for each file.  
15891:  
15892:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15893: 
15894: =item *
15895: 
15896: modify_access_controls():
15897: 
15898: Modifies access controls for a portfolio file
15899: Args
15900: 1. file name
15901: 2. reference to hash of required changes,
15902: 3. domain
15903: 4. username
15904:   where domain,username are the domain of the portfolio owner 
15905:   (either a user or a course) 
15906: 
15907: Returns:
15908: 1. result of additions or updates ('ok' or 'error', with error message). 
15909: 2. result of deletions ('ok' or 'error', with error message).
15910: 3. reference to hash of any new or updated access controls.
15911: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15912:    key = integer (inbound ID)
15913:    value = uniqueID
15914: 
15915: =item *
15916: 
15917: get_timebased_id():
15918: 
15919: Attempts to get a unique timestamp-based suffix for use with items added to a 
15920: course via the Course Editor (e.g., folders, composite pages, 
15921: group bulletin boards).
15922: 
15923: Args: (first three required; six others optional)
15924: 
15925: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15926:    docssequence, or name of group
15927: 
15928: 2. keyid (alphanumeric): name of temporary locking key in hash,
15929:    e.g., num, boardids
15930: 
15931: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15932:    file will be named nohist_namespace.db
15933: 
15934: 4. cdom: domain of course; default is current course domain from %env
15935: 
15936: 5. cnum: course number; default is current course number from %env
15937: 
15938: 6. idtype: set to concat if an additional digit is to be appended to the 
15939:    unix timestamp to form the suffix, if the plain timestamp is already
15940:    in use.  Default is to not do this, but simply increment the unix 
15941:    timestamp by 1 until a unique key is obtained.
15942: 
15943: 7. who: holder of locking key; defaults to user:domain for user.
15944: 
15945: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15946:    retrying); default is 3.
15947: 
15948: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15949: 
15950: Returns:
15951: 
15952: 1. suffix obtained (numeric)
15953: 
15954: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15955: 
15956: 3. error: contains (localized) error message if an error occurred.
15957: 
15958: 
15959: =back
15960: 
15961: =head2 HTTP Helper Routines
15962: 
15963: =over 4
15964: 
15965: =item *
15966: 
15967: escape() : unpack non-word characters into CGI-compatible hex codes
15968: 
15969: =item *
15970: 
15971: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15972: 
15973: =back
15974: 
15975: =head1 PRIVATE SUBROUTINES
15976: 
15977: =head2 Underlying communication routines (Shouldn't call)
15978: 
15979: =over 4
15980: 
15981: =item *
15982: 
15983: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15984: 
15985: =item *
15986: 
15987: reply() : uses subreply to send a message to remote machine, logs all failures
15988: 
15989: =item *
15990: 
15991: critical() : passes a critical message to another server; if cannot
15992: get through then place message in connection buffer directory and
15993: returns con_delayed, if incapable of saving message, returns
15994: con_failed
15995: 
15996: =item *
15997: 
15998: reconlonc() : tries to reconnect lonc client processes.
15999: 
16000: =back
16001: 
16002: =head2 Resource Access Logging
16003: 
16004: =over 4
16005: 
16006: =item *
16007: 
16008: flushcourselogs() : flush (save) buffer logs and access logs
16009: 
16010: =item *
16011: 
16012: courselog($what) : save message for course in hash
16013: 
16014: =item *
16015: 
16016: courseacclog($what) : save message for course using &courselog().  Perform
16017: special processing for specific resource types (problems, exams, quizzes, etc).
16018: 
16019: =item *
16020: 
16021: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16022: as a PerlChildExitHandler
16023: 
16024: =back
16025: 
16026: =head2 Other
16027: 
16028: =over 4
16029: 
16030: =item *
16031: 
16032: symblist($mapname,%newhash) : update symbolic storage links
16033: 
16034: =back
16035: 
16036: =cut
16037: 

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