File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1393: download - view: text, annotated - select for diffs
Wed Dec 5 21:36:18 2018 UTC (5 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Remove duplicate line
- Remove trailing whitespace

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1393 2018/12/05 21:36:18 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$hostname,$context) = @_;
  234:     return if ($lonhost eq '');
  235:     if ($hostname eq '') {
  236:         $hostname = &hostname($lonhost);
  237:     }
  238:     return if ($hostname eq '');
  239:     my ($rep,$uselocal);
  240:     if ($context eq 'install') {
  241:         $uselocal = 1;
  242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  243:         $uselocal = 1;
  244:     }
  245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  247:         if ($distro eq '') {
  248:             $uselocal = 0;
  249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  250:             if ($1 < 6) {
  251:                 $uselocal = 0;
  252:             }
  253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  254:             if ($1 < 12) {
  255:                 $uselocal = 0;
  256:             }
  257:         }
  258:     }
  259:     if ($uselocal) {
  260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  261:     } else {
  262:         $rep=&reply('servercerts',$lonhost);
  263:     }
  264:     my ($result,%returnhash);
  265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  266:         ($rep eq 'unknown_cmd')) {
  267:         $result = $rep;
  268:     } else {
  269:         $result = 'ok';
  270:         my @pairs=split(/\&/,$rep);
  271:         foreach my $item (@pairs) {
  272:             my ($key,$value)=split(/=/,$item,2);
  273:             my $what = &unescape($key);
  274:             $returnhash{$what}=&thaw_unescape($value);
  275:         }
  276:     }
  277:     return ($result,\%returnhash);
  278: }
  279: 
  280: sub get_server_loncaparev {
  281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  282:     if (defined($lonhost)) {
  283:         if (!defined(&hostname($lonhost))) {
  284:             undef($lonhost);
  285:         }
  286:     }
  287:     if (!defined($lonhost)) {
  288:         if (defined(&domain($dom,'primary'))) {
  289:             $lonhost=&domain($dom,'primary');
  290:             if ($lonhost eq 'no_host') {
  291:                 undef($lonhost);
  292:             }
  293:         }
  294:     }
  295:     if (defined($lonhost)) {
  296:         my $cachetime = 12*3600;
  297:         if (!$ignore_cache) {
  298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  299:             if (defined($cached)) {
  300:                 return $loncaparev;
  301:             }
  302:         }
  303:         my ($answer,$loncaparev);
  304:         my @ids=&current_machine_ids();
  305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  306:             $answer = $perlvar{'lonVersion'};
  307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  308:                 $loncaparev = $1;
  309:             }
  310:         } else {
  311:             $answer = &reply('serverloncaparev',$lonhost);
  312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  313:                 if ($caller eq 'loncron') {
  314:                     my $protocol = $protocol{$lonhost};
  315:                     $protocol = 'http' if ($protocol ne 'https');
  316:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  317:                     my $request=new HTTP::Request('GET',$url);
  318:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  319:                     unless ($response->is_error()) {
  320:                         my $content = $response->content;
  321:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  322:                             $loncaparev = $1;
  323:                         }
  324:                     }
  325:                 } else {
  326:                     $loncaparev = $loncaparevs{$lonhost};
  327:                 }
  328:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  329:                 $loncaparev = $1;
  330:             }
  331:         }
  332:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  333:     }
  334: }
  335: 
  336: sub get_server_homeID {
  337:     my ($hostname,$ignore_cache,$caller) = @_;
  338:     unless ($ignore_cache) {
  339:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  340:         if (defined($cached)) {
  341:             return $serverhomeID;
  342:         }
  343:     }
  344:     my $cachetime = 12*3600;
  345:     my $serverhomeID;
  346:     if ($caller eq 'loncron') { 
  347:         my @machine_ids = &machine_ids($hostname);
  348:         foreach my $id (@machine_ids) {
  349:             my $response = &reply('serverhomeID',$id);
  350:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  351:                 $serverhomeID = $response;
  352:                 last;
  353:             }
  354:         }
  355:         if ($serverhomeID eq '') {
  356:             $serverhomeID = $machine_ids[-1];
  357:         }
  358:     } else {
  359:         $serverhomeID = $serverhomeIDs{$hostname};
  360:     }
  361:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  362: }
  363: 
  364: sub get_remote_globals {
  365:     my ($lonhost,$whathash,$ignore_cache) = @_;
  366:     my ($result,%returnhash,%whatneeded);
  367:     if (ref($whathash) eq 'HASH') {
  368:         foreach my $what (sort(keys(%{$whathash}))) {
  369:             my $hashid = $lonhost.'-'.$what;
  370:             my ($response,$cached);
  371:             unless ($ignore_cache) {
  372:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  373:             }
  374:             if (defined($cached)) {
  375:                 $returnhash{$what} = $response;
  376:             } else {
  377:                 $whatneeded{$what} = 1;
  378:             }
  379:         }
  380:         if (keys(%whatneeded) == 0) {
  381:             $result = 'ok';
  382:         } else {
  383:             my $requested = &freeze_escape(\%whatneeded);
  384:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  385:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  386:                 ($rep eq 'unknown_cmd')) {
  387:                 $result = $rep;
  388:             } else {
  389:                 $result = 'ok';
  390:                 my @pairs=split(/\&/,$rep);
  391:                 foreach my $item (@pairs) {
  392:                     my ($key,$value)=split(/=/,$item,2);
  393:                     my $what = &unescape($key);
  394:                     my $hashid = $lonhost.'-'.$what;
  395:                     $returnhash{$what}=&thaw_unescape($value);
  396:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  397:                 }
  398:             }
  399:         }
  400:     }
  401:     return ($result,\%returnhash);
  402: }
  403: 
  404: sub remote_devalidate_cache {
  405:     my ($lonhost,$cachekeys) = @_;
  406:     my $items;
  407:     return unless (ref($cachekeys) eq 'ARRAY');
  408:     my $cachestr = join('&',@{$cachekeys});
  409:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  410:     return $response;
  411: }
  412: 
  413: # -------------------------------------------------- Non-critical communication
  414: sub subreply {
  415:     my ($cmd,$server)=@_;
  416:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  417:     #
  418:     #  With loncnew process trimming, there's a timing hole between lonc server
  419:     #  process exit and the master server picking up the listen on the AF_UNIX
  420:     #  socket.  In that time interval, a lock file will exist:
  421: 
  422:     my $lockfile=$peerfile.".lock";
  423:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  424: 	sleep(0.1);
  425:     }
  426:     # At this point, either a loncnew parent is listening or an old lonc
  427:     # or loncnew child is listening so we can connect or everything's dead.
  428:     #
  429:     #   We'll give the connection a few tries before abandoning it.  If
  430:     #   connection is not possible, we'll con_lost back to the client.
  431:     #   
  432:     my $client;
  433:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  434: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  435: 				      Type    => SOCK_STREAM,
  436: 				      Timeout => 10);
  437: 	if ($client) {
  438: 	    last;		# Connected!
  439: 	} else {
  440: 	    &create_connection(&hostname($server),$server);
  441: 	}
  442:         sleep(0.1);	# Try again later if failed connection.
  443:     }
  444:     my $answer;
  445:     if ($client) {
  446: 	print $client "sethost:$server:$cmd\n";
  447: 	$answer=<$client>;
  448: 	if (!$answer) { $answer="con_lost"; }
  449: 	chomp($answer);
  450:     } else {
  451: 	$answer = 'con_lost';	# Failed connection.
  452:     }
  453:     return $answer;
  454: }
  455: 
  456: sub reply {
  457:     my ($cmd,$server)=@_;
  458:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  459:     my $answer=subreply($cmd,$server);
  460:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  461:        &logthis("<font color=\"blue\">WARNING:".
  462:                 " $cmd to $server returned $answer</font>");
  463:     }
  464:     return $answer;
  465: }
  466: 
  467: # ----------------------------------------------------------- Send USR1 to lonc
  468: 
  469: sub reconlonc {
  470:     my ($lonid) = @_;
  471:     if ($lonid) {
  472:         my $hostname = &hostname($lonid);
  473: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  474: 	if ($hostname && -e $peerfile) {
  475: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  476: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  477: 					     Type    => SOCK_STREAM,
  478: 					     Timeout => 10);
  479: 	    if ($client) {
  480: 		print $client ("reset_retries\n");
  481: 		my $answer=<$client>;
  482: 		#reset just this one.
  483: 	    }
  484: 	}
  485: 	return;
  486:     }
  487: 
  488:     &logthis("Trying to reconnect lonc");
  489:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  490:     if (open(my $fh,"<",$loncfile)) {
  491: 	my $loncpid=<$fh>;
  492:         chomp($loncpid);
  493:         if (kill 0 => $loncpid) {
  494: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  495:             kill USR1 => $loncpid;
  496:             sleep 1;
  497:         } else {
  498: 	    &logthis(
  499:                "<font color=\"blue\">WARNING:".
  500:                " lonc at pid $loncpid not responding, giving up</font>");
  501:         }
  502:     } else {
  503: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  504:     }
  505: }
  506: 
  507: # ------------------------------------------------------ Critical communication
  508: 
  509: sub critical {
  510:     my ($cmd,$server)=@_;
  511:     unless (&hostname($server)) {
  512:         &logthis("<font color=\"blue\">WARNING:".
  513:                " Critical message to unknown server ($server)</font>");
  514:         return 'no_such_host';
  515:     }
  516:     my $answer=reply($cmd,$server);
  517:     if ($answer eq 'con_lost') {
  518: 	&reconlonc($server);
  519: 	my $answer=reply($cmd,$server);
  520:         if ($answer eq 'con_lost') {
  521:             my $now=time;
  522:             my $middlename=$cmd;
  523:             $middlename=substr($middlename,0,16);
  524:             $middlename=~s/\W//g;
  525:             my $dfilename=
  526:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  527:             $dumpcount++;
  528:             {
  529: 		my $dfh;
  530: 		if (open($dfh,">",$dfilename)) {
  531: 		    print $dfh "$cmd\n"; 
  532: 		    close($dfh);
  533: 		}
  534:             }
  535:             sleep 1;
  536:             my $wcmd='';
  537:             {
  538: 		my $dfh;
  539: 		if (open($dfh,"<",$dfilename)) {
  540: 		    $wcmd=<$dfh>; 
  541: 		    close($dfh);
  542: 		}
  543:             }
  544:             chomp($wcmd);
  545:             if ($wcmd eq $cmd) {
  546: 		&logthis("<font color=\"blue\">WARNING: ".
  547:                          "Connection buffer $dfilename: $cmd</font>");
  548:                 &logperm("D:$server:$cmd");
  549: 	        return 'con_delayed';
  550:             } else {
  551:                 &logthis("<font color=\"red\">CRITICAL:"
  552:                         ." Critical connection failed: $server $cmd</font>");
  553:                 &logperm("F:$server:$cmd");
  554:                 return 'con_failed';
  555:             }
  556:         }
  557:     }
  558:     return $answer;
  559: }
  560: 
  561: # ------------------------------------------- check if return value is an error
  562: 
  563: sub error {
  564:     my ($result) = @_;
  565:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  566: 	if ($2 == 2) { return undef; }
  567: 	return $1;
  568:     }
  569:     return undef;
  570: }
  571: 
  572: sub convert_and_load_session_env {
  573:     my ($lonidsdir,$handle)=@_;
  574:     my @profile;
  575:     {
  576: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  577: 	if (!$opened) {
  578: 	    return 0;
  579: 	}
  580: 	flock($idf,LOCK_SH);
  581: 	@profile=<$idf>;
  582: 	close($idf);
  583:     }
  584:     my %temp_env;
  585:     foreach my $line (@profile) {
  586: 	if ($line !~ m/=/) {
  587: 	    return 0;
  588: 	}
  589: 	chomp($line);
  590: 	my ($envname,$envvalue)=split(/=/,$line,2);
  591: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  592:     }
  593:     unlink("$lonidsdir/$handle.id");
  594:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  595: 	    0640)) {
  596: 	%disk_env = %temp_env;
  597: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  598: 	untie(%disk_env);
  599:     }
  600:     return 1;
  601: }
  602: 
  603: # ------------------------------------------- Transfer profile into environment
  604: my $env_loaded;
  605: sub transfer_profile_to_env {
  606:     my ($lonidsdir,$handle,$force_transfer) = @_;
  607:     if (!$force_transfer && $env_loaded) { return; } 
  608: 
  609:     if (!defined($lonidsdir)) {
  610: 	$lonidsdir = $perlvar{'lonIDsDir'};
  611:     }
  612:     if (!defined($handle)) {
  613:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  614:     }
  615: 
  616:     my $convert;
  617:     {
  618:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  619: 	if (!$opened) {
  620: 	    return;
  621: 	}
  622: 	flock($idf,LOCK_SH);
  623: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  624: 		&GDBM_READER(),0640)) {
  625: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  626: 	    untie(%disk_env);
  627: 	} else {
  628: 	    $convert = 1;
  629: 	}
  630:     }
  631:     if ($convert) {
  632: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  633: 	    &logthis("Failed to load session, or convert session.");
  634: 	}
  635:     }
  636: 
  637:     my %remove;
  638:     while ( my $envname = each(%env) ) {
  639:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  640:             if ($time < time-300) {
  641:                 $remove{$key}++;
  642:             }
  643:         }
  644:     }
  645: 
  646:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  647:     $env_loaded=1;
  648:     foreach my $expired_key (keys(%remove)) {
  649:         &delenv($expired_key);
  650:     }
  651: }
  652: 
  653: # ---------------------------------------------------- Check for valid session 
  654: sub check_for_valid_session {
  655:     my ($r,$name,$userhashref,$domref) = @_;
  656:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  657:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  658:     if ($name eq 'lonDAV') {
  659:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  660:     } else {
  661:         $lonidsdir=$r->dir_config('lonIDsDir');
  662:         if ($name eq '') {
  663:             $name = 'lonID';
  664:         }
  665:     }
  666:     if ($name eq 'lonID') {
  667:         $secure = 'lonSID';
  668:         $linkname = 'lonLinkID';
  669:         $pubname = 'lonPubID';
  670:         if (exists($cookies{$secure})) {
  671:             $lonid=$cookies{$secure};
  672:         } elsif (exists($cookies{$name})) {
  673:             $lonid=$cookies{$name};
  674:         } elsif (exists($cookies{$linkname})) {
  675:             $lonid=$cookies{$linkname};
  676:         } elsif (exists($cookies{$pubname})) {
  677:             $lonid=$cookies{$pubname};
  678:         }
  679:     } else {
  680:         $lonid=$cookies{$name};
  681:     }
  682:     return undef if (!$lonid);
  683: 
  684:     my $handle=&LONCAPA::clean_handle($lonid->value);
  685:     if (-l "$lonidsdir/$handle.id") {
  686:         my $link = readlink("$lonidsdir/$handle.id");
  687:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  688:             $handle = $1;
  689:         }
  690:     }
  691:     if (!-e "$lonidsdir/$handle.id") {
  692:         if ((ref($domref)) && ($name eq 'lonID') && 
  693:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  694:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  695:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  696:                 $$domref = $possudom;
  697:             }
  698:         }
  699:         return undef;
  700:     }
  701: 
  702:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  703:     return undef if (!$opened);
  704: 
  705:     flock($idf,LOCK_SH);
  706:     my %disk_env;
  707:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  708: 	    &GDBM_READER(),0640)) {
  709: 	return undef;	
  710:     }
  711: 
  712:     if (!defined($disk_env{'user.name'})
  713: 	|| !defined($disk_env{'user.domain'})) {
  714: 	return undef;
  715:     }
  716: 
  717:     if (ref($userhashref) eq 'HASH') {
  718:         $userhashref->{'name'} = $disk_env{'user.name'};
  719:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  720:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  721:         if ($userhashref->{'lti'}) {
  722:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  723:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  724:         }
  725:     }
  726: 
  727:     return $handle;
  728: }
  729: 
  730: sub timed_flock {
  731:     my ($file,$lock_type) = @_;
  732:     my $failed=0;
  733:     eval {
  734: 	local $SIG{__DIE__}='DEFAULT';
  735: 	local $SIG{ALRM}=sub {
  736: 	    $failed=1;
  737: 	    die("failed lock");
  738: 	};
  739: 	alarm(13);
  740: 	flock($file,$lock_type);
  741: 	alarm(0);
  742:     };
  743:     if ($failed) {
  744: 	return undef;
  745:     } else {
  746: 	return 1;
  747:     }
  748: }
  749: 
  750: sub get_sessionfile_vars {
  751:     my ($handle,$lonidsdir,$storearr) = @_;
  752:     my %returnhash;
  753:     unless (ref($storearr) eq 'ARRAY') {
  754:         return %returnhash;
  755:     }
  756:     if (-l "$lonidsdir/$handle.id") {
  757:         my $link = readlink("$lonidsdir/$handle.id");
  758:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  759:             $handle = $1;
  760:         }
  761:     }
  762:     if ((-e "$lonidsdir/$handle.id") &&
  763:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  764:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  765:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  766:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  767:                 flock($idf,LOCK_SH);
  768:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  769:                         &GDBM_READER(),0640)) {
  770:                     foreach my $item (@{$storearr}) {
  771:                         $returnhash{$item} = $disk_env{$item};
  772:                     }
  773:                     untie(%disk_env);
  774:                 }
  775:             }
  776:         }
  777:     }
  778:     return %returnhash;
  779: }
  780: 
  781: # ---------------------------------------------------------- Append Environment
  782: 
  783: sub appenv {
  784:     my ($newenv,$roles) = @_;
  785:     if (ref($newenv) eq 'HASH') {
  786:         foreach my $key (keys(%{$newenv})) {
  787:             my $refused = 0;
  788: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  789:                 $refused = 1;
  790:                 if (ref($roles) eq 'ARRAY') {
  791:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  792:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  793:                         $refused = 0;
  794:                     }
  795:                 }
  796:             }
  797:             if ($refused) {
  798:                 &logthis("<font color=\"blue\">WARNING: ".
  799:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  800:                          .'</font>');
  801: 	        delete($newenv->{$key});
  802:             } else {
  803:                 $env{$key}=$newenv->{$key};
  804:             }
  805:         }
  806:         my $lonids = $perlvar{'lonIDsDir'};
  807:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  808:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  809:             if ($opened
  810: 	        && &timed_flock($env_file,LOCK_EX)
  811: 	        &&
  812: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  813: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  814: 	        while (my ($key,$value) = each(%{$newenv})) {
  815: 	            $disk_env{$key} = $value;
  816: 	        }
  817: 	        untie(%disk_env);
  818:             }
  819:         }
  820:     }
  821:     return 'ok';
  822: }
  823: # ----------------------------------------------------- Delete from Environment
  824: 
  825: sub delenv {
  826:     my ($delthis,$regexp,$roles) = @_;
  827:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  828:         my $refused = 1;
  829:         if (ref($roles) eq 'ARRAY') {
  830:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  831:             if (grep(/^\Q$role\E$/,@{$roles})) {
  832:                 $refused = 0;
  833:             }
  834:         }
  835:         if ($refused) {
  836:             &logthis("<font color=\"blue\">WARNING: ".
  837:                      "Attempt to delete from environment ".$delthis);
  838:             return 'error';
  839:         }
  840:     }
  841:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  842:     if ($opened
  843: 	&& &timed_flock($env_file,LOCK_EX)
  844: 	&&
  845: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  846: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  847: 	foreach my $key (keys(%disk_env)) {
  848: 	    if ($regexp) {
  849:                 if ($key=~/^$delthis/) {
  850:                     delete($env{$key});
  851:                     delete($disk_env{$key});
  852:                 } 
  853:             } else {
  854:                 if ($key=~/^\Q$delthis\E/) {
  855: 		    delete($env{$key});
  856: 		    delete($disk_env{$key});
  857: 	        }
  858:             }
  859: 	}
  860: 	untie(%disk_env);
  861:     }
  862:     return 'ok';
  863: }
  864: 
  865: sub get_env_multiple {
  866:     my ($name) = @_;
  867:     my @values;
  868:     if (defined($env{$name})) {
  869:         # exists is it an array
  870:         if (ref($env{$name})) {
  871:             @values=@{ $env{$name} };
  872:         } else {
  873:             $values[0]=$env{$name};
  874:         }
  875:     }
  876:     return(@values);
  877: }
  878: 
  879: # ------------------------------------------------------------------- Locking
  880: 
  881: sub set_lock {
  882:     my ($text)=@_;
  883:     $locknum++;
  884:     my $id=$$.'-'.$locknum;
  885:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  886:              'session.lock.'.$id => $text});
  887:     return $id;
  888: }
  889: 
  890: sub get_locks {
  891:     my $num=0;
  892:     my %texts=();
  893:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  894:        if ($lock=~/\w/) {
  895:           $num++;
  896:           $texts{$lock}=$env{'session.lock.'.$lock};
  897:        }
  898:    }
  899:    return ($num,%texts);
  900: }
  901: 
  902: sub remove_lock {
  903:     my ($id)=@_;
  904:     my $newlocks='';
  905:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  906:        if (($lock=~/\w/) && ($lock ne $id)) {
  907:           $newlocks.=','.$lock;
  908:        }
  909:     }
  910:     &appenv({'session.locks' => $newlocks});
  911:     &delenv('session.lock.'.$id);
  912: }
  913: 
  914: sub remove_all_locks {
  915:     my $activelocks=$env{'session.locks'};
  916:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  917:        if ($lock=~/\w/) {
  918:           &remove_lock($lock);
  919:        }
  920:     }
  921: }
  922: 
  923: 
  924: # ------------------------------------------ Find out current server userload
  925: sub userload {
  926:     my $numusers=0;
  927:     {
  928: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  929: 	my $filename;
  930: 	my $curtime=time;
  931: 	while ($filename=readdir(LONIDS)) {
  932: 	    next if ($filename eq '.' || $filename eq '..');
  933: 	    next if ($filename =~ /publicuser_\d+\.id/);
  934:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  935: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  936: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  937: 	}
  938: 	closedir(LONIDS);
  939:     }
  940:     my $userloadpercent=0;
  941:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  942:     if ($maxuserload) {
  943: 	$userloadpercent=100*$numusers/$maxuserload;
  944:     }
  945:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  946:     return $userloadpercent;
  947: }
  948: 
  949: # ------------------------------ Find server with least workload from spare.tab
  950: 
  951: sub spareserver {
  952:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  953:     my $spare_server;
  954:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  955:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  956:                                                      :  $userloadpercent;
  957:     my ($uint_dom,$remotesessions);
  958:     if (($udom ne '') && (&domain($udom) ne '')) {
  959:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  960:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  961:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  962:         $remotesessions = $udomdefaults{'remotesessions'};
  963:     }
  964:     my $spareshash = &this_host_spares($udom);
  965:     if (ref($spareshash) eq 'HASH') {
  966:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  967:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  968:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  969:                                              $try_server));
  970: 	        ($spare_server, $lowest_load) =
  971: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  972:             }
  973:         }
  974: 
  975:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  976: 
  977:         if (!$found_server) {
  978:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  979: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  980:                     next unless (&spare_can_host($udom,$uint_dom,
  981:                                                  $remotesessions,$try_server));
  982: 	            ($spare_server, $lowest_load) =
  983: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  984:                 }
  985: 	    }
  986:         }
  987:     }
  988: 
  989:     if (!$want_server_name) {
  990:         my $protocol = 'http';
  991:         if ($protocol{$spare_server} eq 'https') {
  992:             $protocol = $protocol{$spare_server};
  993:         }
  994:         if (defined($spare_server)) {
  995:             my $hostname = &hostname($spare_server);
  996:             if (defined($hostname)) {
  997: 	        $spare_server = $protocol.'://'.$hostname;
  998:             }
  999:         }
 1000:     }
 1001:     return $spare_server;
 1002: }
 1003: 
 1004: sub compare_server_load {
 1005:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1006: 
 1007:     if ($required) {
 1008:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1009:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1010:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1011:         if (($major eq '' && $minor eq '') ||
 1012:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1013:             return ($spare_server,$lowest_load);
 1014:         }
 1015:     }
 1016: 
 1017:     my $loadans     = &reply('load',    $try_server);
 1018:     my $userloadans = &reply('userload',$try_server);
 1019: 
 1020:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1021: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1022:     }
 1023: 
 1024:     my $load;
 1025:     if ($loadans =~ /\d/) {
 1026: 	if ($userloadans =~ /\d/) {
 1027: 	    #both are numbers, pick the bigger one
 1028: 	    $load = ($loadans > $userloadans) ? $loadans 
 1029: 		                              : $userloadans;
 1030: 	} else {
 1031: 	    $load = $loadans;
 1032: 	}
 1033:     } else {
 1034: 	$load = $userloadans;
 1035:     }
 1036: 
 1037:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1038: 	$spare_server = $try_server;
 1039: 	$lowest_load  = $load;
 1040:     }
 1041:     return ($spare_server,$lowest_load);
 1042: }
 1043: 
 1044: # --------------------------- ask offload servers if user already has a session
 1045: sub find_existing_session {
 1046:     my ($udom,$uname) = @_;
 1047:     my $spareshash = &this_host_spares($udom);
 1048:     if (ref($spareshash) eq 'HASH') {
 1049:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1050:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1051:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1052:             }
 1053:         }
 1054:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1055:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1056:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1057:             }
 1058:         }
 1059:     }
 1060:     return;
 1061: }
 1062: 
 1063: # check if user's browser sent load balancer cookie and server still has session
 1064: # and is not overloaded.
 1065: sub check_for_balancer_cookie {
 1066:     my ($r,$update_mtime) = @_;
 1067:     my ($otherserver,$cookie);
 1068:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1069:     if (exists($cookies{'balanceID'})) {
 1070:         my $balid = $cookies{'balanceID'};
 1071:         $cookie=&LONCAPA::clean_handle($balid->value);
 1072:         my $balancedir=$r->dir_config('lonBalanceDir');
 1073:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1074:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1075:                 my ($possudom,$possuname) = ($1,$2);
 1076:                 my $has_session = 0;
 1077:                 if ((&domain($possudom) ne '') &&
 1078:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1079:                     my $try_server;
 1080:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1081:                     if ($opened) {
 1082:                         flock($idf,LOCK_SH);
 1083:                         while (my $line = <$idf>) {
 1084:                             chomp($line);
 1085:                             if (&hostname($line) ne '') {
 1086:                                 $try_server = $line;
 1087:                                 last;
 1088:                             }
 1089:                         }
 1090:                         close($idf);
 1091:                         if (($try_server) &&
 1092:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1093:                             my $lowest_load = 30000;
 1094:                             ($otherserver,$lowest_load) =
 1095:                                 &compare_server_load($try_server,undef,$lowest_load);
 1096:                             if ($otherserver ne '' && $lowest_load < 100) {
 1097:                                 $has_session = 1;
 1098:                             } else {
 1099:                                 undef($otherserver);
 1100:                             }
 1101:                         }
 1102:                     }
 1103:                 }
 1104:                 if ($has_session) {
 1105:                     if ($update_mtime) {
 1106:                         my $atime = my $mtime = time;
 1107:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1108:                     }
 1109:                 } else {
 1110:                     unlink("$balancedir/$cookie.id");
 1111:                 }
 1112:             }
 1113:         }
 1114:     }
 1115:     return ($otherserver,$cookie);
 1116: }
 1117: 
 1118: sub delbalcookie {
 1119:     my ($cookie,$balancer) =@_;
 1120:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1121:         my ($udom,$uname) = ($1,$2);
 1122:         my $uprimary_id = &domain($udom,'primary');
 1123:         my $uintdom = &internet_dom($uprimary_id);
 1124:         my $intdom = &internet_dom($balancer);
 1125:         my $serverhomedom = &host_domain($balancer);
 1126:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1127:             return &reply("delbalcookie:$cookie",$balancer);
 1128:         }
 1129:     }
 1130: }
 1131: 
 1132: # -------------------------------- ask if server already has a session for user
 1133: sub has_user_session {
 1134:     my ($lonid,$udom,$uname) = @_;
 1135:     my $result = &reply(join(':','userhassession',
 1136: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1137:     return 1 if ($result eq 'ok');
 1138: 
 1139:     return 0;
 1140: }
 1141: 
 1142: # --------- determine least loaded server in a user's domain which allows login
 1143: 
 1144: sub choose_server {
 1145:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1146:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1147:     my %servers = &get_servers($udom);
 1148:     my $lowest_load = 30000;
 1149:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1150:     if ($skiploadbal) {
 1151:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1152:         unless (defined($cached)) {
 1153:             my $cachetime = 60*60*24;
 1154:             my %domconfig =
 1155:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1156:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1157:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1158:                                            $cachetime);
 1159:             }
 1160:         }
 1161:     }
 1162:     foreach my $lonhost (keys(%servers)) {
 1163:         if ($skiploadbal) {
 1164:             if (ref($balancers) eq 'HASH') {
 1165:                 next if (exists($balancers->{$lonhost}));
 1166:             }
 1167:         }
 1168:         my $loginvia;
 1169:         if ($checkloginvia) {
 1170:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1171:             if ($loginvia) {
 1172:                 my ($server,$path) = split(/:/,$loginvia);
 1173:                 ($login_host, $lowest_load) =
 1174:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1175:                 if ($login_host eq $server) {
 1176:                     $portal_path = $path;
 1177:                     $isredirect = 1;
 1178:                 }
 1179:             } else {
 1180:                 ($login_host, $lowest_load) =
 1181:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1182:                 if ($login_host eq $lonhost) {
 1183:                     $portal_path = '';
 1184:                     $isredirect = ''; 
 1185:                 }
 1186:             }
 1187:         } else {
 1188:             ($login_host, $lowest_load) =
 1189:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1190:         }
 1191:     }
 1192:     if ($login_host ne '') {
 1193:         $hostname = &hostname($login_host);
 1194:     }
 1195:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1196: }
 1197: 
 1198: # --------------------------------------------- Try to change a user's password
 1199: 
 1200: sub changepass {
 1201:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1202:     $currentpass = &escape($currentpass);
 1203:     $newpass     = &escape($newpass);
 1204:     my $lonhost = $perlvar{'lonHostID'};
 1205:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1206: 		       $server);
 1207:     if (! $answer) {
 1208: 	&logthis("No reply on password change request to $server ".
 1209: 		 "by $uname in domain $udom.");
 1210:     } elsif ($answer =~ "^ok") {
 1211:         &logthis("$uname in $udom successfully changed their password ".
 1212: 		 "on $server.");
 1213:     } elsif ($answer =~ "^pwchange_failure") {
 1214: 	&logthis("$uname in $udom was unable to change their password ".
 1215: 		 "on $server.  The action was blocked by either lcpasswd ".
 1216: 		 "or pwchange");
 1217:     } elsif ($answer =~ "^non_authorized") {
 1218:         &logthis("$uname in $udom did not get their password correct when ".
 1219: 		 "attempting to change it on $server.");
 1220:     } elsif ($answer =~ "^auth_mode_error") {
 1221:         &logthis("$uname in $udom attempted to change their password despite ".
 1222: 		 "not being locally or internally authenticated on $server.");
 1223:     } elsif ($answer =~ "^unknown_user") {
 1224:         &logthis("$uname in $udom attempted to change their password ".
 1225: 		 "on $server but were unable to because $server is not ".
 1226: 		 "their home server.");
 1227:     } elsif ($answer =~ "^refused") {
 1228: 	&logthis("$server refused to change $uname in $udom password because ".
 1229: 		 "it was sent an unencrypted request to change the password.");
 1230:     } elsif ($answer =~ "invalid_client") {
 1231:         &logthis("$server refused to change $uname in $udom password because ".
 1232:                  "it was a reset by e-mail originating from an invalid server.");
 1233:     }
 1234:     return $answer;
 1235: }
 1236: 
 1237: # ----------------------- Try to determine user's current authentication scheme
 1238: 
 1239: sub queryauthenticate {
 1240:     my ($uname,$udom)=@_;
 1241:     my $uhome=&homeserver($uname,$udom);
 1242:     if (!$uhome) {
 1243: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1244: 	return 'no_host';
 1245:     }
 1246:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1247:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1248: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1249:     }
 1250:     return $answer;
 1251: }
 1252: 
 1253: # --------- Try to authenticate user from domain's lib servers (first this one)
 1254: 
 1255: sub authenticate {
 1256:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1257:     $upass=&escape($upass);
 1258:     $uname= &LONCAPA::clean_username($uname);
 1259:     my $uhome=&homeserver($uname,$udom,1);
 1260:     my $newhome;
 1261:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1262: # Maybe the machine was offline and only re-appeared again recently?
 1263:         &reconlonc();
 1264: # One more
 1265: 	$uhome=&homeserver($uname,$udom,1);
 1266:         if (($uhome eq 'no_host') && $checkdefauth) {
 1267:             if (defined(&domain($udom,'primary'))) {
 1268:                 $newhome=&domain($udom,'primary');
 1269:             }
 1270:             if ($newhome ne '') {
 1271:                 $uhome = $newhome;
 1272:             }
 1273:         }
 1274: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1275: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1276: 	    return 'no_host';
 1277:         }
 1278:     }
 1279:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1280:     if ($answer eq 'authorized') {
 1281:         if ($newhome) {
 1282:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1283:             return 'no_account_on_host'; 
 1284:         } else {
 1285:             &logthis("User $uname at $udom authorized by $uhome");
 1286:             return $uhome;
 1287:         }
 1288:     }
 1289:     if ($answer eq 'non_authorized') {
 1290: 	&logthis("User $uname at $udom rejected by $uhome");
 1291: 	return 'no_host'; 
 1292:     }
 1293:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1294:     return 'no_host';
 1295: }
 1296: 
 1297: sub can_host_session {
 1298:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1299:     my $canhost = 1;
 1300:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1301:     if (ref($remotesessions) eq 'HASH') {
 1302:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1303:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1304:                 $canhost = 0;
 1305:             } else {
 1306:                 $canhost = 1;
 1307:             }
 1308:         }
 1309:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1310:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1311:                 $canhost = 1;
 1312:             } else {
 1313:                 $canhost = 0;
 1314:             }
 1315:         }
 1316:         if ($canhost) {
 1317:             if ($remotesessions->{'version'} ne '') {
 1318:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1319:                 if ($reqmajor ne '' && $reqminor ne '') {
 1320:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1321:                         my $major = $1;
 1322:                         my $minor = $2;
 1323:                         if (($major < $reqmajor ) ||
 1324:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1325:                             $canhost = 0;
 1326:                         }
 1327:                     } else {
 1328:                         $canhost = 0;
 1329:                     }
 1330:                 }
 1331:             }
 1332:         }
 1333:     }
 1334:     if ($canhost) {
 1335:         if (ref($hostedsessions) eq 'HASH') {
 1336:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1337:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1338:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1339:                 if (($uint_dom ne '') && 
 1340:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1341:                     $canhost = 0;
 1342:                 } else {
 1343:                     $canhost = 1;
 1344:                 }
 1345:             }
 1346:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1347:                 if (($uint_dom ne '') && 
 1348:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1349:                     $canhost = 1;
 1350:                 } else {
 1351:                     $canhost = 0;
 1352:                 }
 1353:             }
 1354:         }
 1355:     }
 1356:     return $canhost;
 1357: }
 1358: 
 1359: sub spare_can_host {
 1360:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1361:     my $canhost=1;
 1362:     my $try_server_hostname = &hostname($try_server);
 1363:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1364:     my $serverhomedom = &host_domain($serverhomeID);
 1365:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1366:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1367:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1368:             $canhost = 0;
 1369:         }
 1370:     }
 1371:     if (($canhost) && ($uint_dom)) {
 1372:         my @intdoms;
 1373:         my $internet_names = &get_internet_names($try_server);
 1374:         if (ref($internet_names) eq 'ARRAY') {
 1375:             @intdoms = @{$internet_names};
 1376:         }
 1377:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1378:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1379:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1380:                                          $remotesessions,
 1381:                                          $defdomdefaults{'hostedsessions'});
 1382:         }
 1383:     }
 1384:     return $canhost;
 1385: }
 1386: 
 1387: sub this_host_spares {
 1388:     my ($dom) = @_;
 1389:     my ($dom_in_use,$lonhost_in_use,$result);
 1390:     my @hosts = &current_machine_ids();
 1391:     foreach my $lonhost (@hosts) {
 1392:         if (&host_domain($lonhost) eq $dom) {
 1393:             $dom_in_use = $dom;
 1394:             $lonhost_in_use = $lonhost;
 1395:             last;
 1396:         }
 1397:     }
 1398:     if ($dom_in_use ne '') {
 1399:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1400:     }
 1401:     if (ref($result) ne 'HASH') {
 1402:         $lonhost_in_use = $perlvar{'lonHostID'};
 1403:         $dom_in_use = &host_domain($lonhost_in_use);
 1404:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1405:         if (ref($result) ne 'HASH') {
 1406:             $result = \%spareid;
 1407:         }
 1408:     }
 1409:     return $result;
 1410: }
 1411: 
 1412: sub spares_for_offload  {
 1413:     my ($dom_in_use,$lonhost_in_use) = @_;
 1414:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1415:     if (defined($cached)) {
 1416:         return $result;
 1417:     } else {
 1418:         my $cachetime = 60*60*24;
 1419:         my %domconfig =
 1420:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1421:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1422:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1423:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1424:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1425:                 }
 1426:             }
 1427:         }
 1428:     }
 1429:     return;
 1430: }
 1431: 
 1432: sub get_lonbalancer_config {
 1433:     my ($servers) = @_;
 1434:     my ($currbalancer,$currtargets);
 1435:     if (ref($servers) eq 'HASH') {
 1436:         foreach my $server (keys(%{$servers})) {
 1437:             my %what = (
 1438:                          spareid => 1,
 1439:                          perlvar => 1,
 1440:                        );
 1441:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1442:             if ($result eq 'ok') {
 1443:                 if (ref($returnhash) eq 'HASH') {
 1444:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1445:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1446:                             $currbalancer = $server;
 1447:                             $currtargets = {};
 1448:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1449:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1450:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1451:                                 }
 1452:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1453:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1454:                                 }
 1455:                             }
 1456:                             last;
 1457:                         }
 1458:                     }
 1459:                 }
 1460:             }
 1461:         }
 1462:     }
 1463:     return ($currbalancer,$currtargets);
 1464: }
 1465: 
 1466: sub check_loadbalancing {
 1467:     my ($uname,$udom,$caller) = @_;
 1468:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1469:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1470:     my $lonhost = $perlvar{'lonHostID'};
 1471:     my @hosts = &current_machine_ids();
 1472:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1473:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1474:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1475:     my $serverhomedom = &host_domain($lonhost);
 1476:     my $domneedscache;
 1477:     my $cachetime = 60*60*24;
 1478: 
 1479:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1480:         $dom_in_use = $udom;
 1481:         $homeintdom = 1;
 1482:     } else {
 1483:         $dom_in_use = $serverhomedom;
 1484:     }
 1485:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1486:     unless (defined($cached)) {
 1487:         my %domconfig =
 1488:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1489:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1490:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1491:         } else {
 1492:             $domneedscache = $dom_in_use;
 1493:         }
 1494:     }
 1495:     if (ref($result) eq 'HASH') {
 1496:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1497:             &check_balancer_result($result,@hosts);
 1498:         if ($is_balancer) {
 1499:             if (ref($currrules) eq 'HASH') {
 1500:                 if ($homeintdom) {
 1501:                     if ($uname ne '') {
 1502:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1503:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1504:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1505:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1506:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1507:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1508:                             }
 1509:                         }
 1510:                         if ($rule_in_effect eq '') {
 1511:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1512:                             if ($userenv{'inststatus'} ne '') {
 1513:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1514:                                 my ($othertitle,$usertypes,$types) =
 1515:                                     &Apache::loncommon::sorted_inst_types($udom);
 1516:                                 if (ref($types) eq 'ARRAY') {
 1517:                                     foreach my $type (@{$types}) {
 1518:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1519:                                             if (exists($currrules->{$type})) {
 1520:                                                 $rule_in_effect = $currrules->{$type};
 1521:                                             }
 1522:                                         }
 1523:                                     }
 1524:                                 }
 1525:                             } else {
 1526:                                 if (exists($currrules->{'default'})) {
 1527:                                     $rule_in_effect = $currrules->{'default'};
 1528:                                 }
 1529:                             }
 1530:                         }
 1531:                     } else {
 1532:                         if (exists($currrules->{'default'})) {
 1533:                             $rule_in_effect = $currrules->{'default'};
 1534:                         }
 1535:                     }
 1536:                 } else {
 1537:                     if ($currrules->{'_LC_external'} ne '') {
 1538:                         $rule_in_effect = $currrules->{'_LC_external'};
 1539:                     }
 1540:                 }
 1541:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1542:                                                        $uname,$udom);
 1543:             }
 1544:         }
 1545:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1546:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1547:         unless (defined($cached)) {
 1548:             my %domconfig =
 1549:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1550:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1551:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1552:             } else {
 1553:                 $domneedscache = $serverhomedom;
 1554:             }
 1555:         }
 1556:         if (ref($result) eq 'HASH') {
 1557:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1558:                 &check_balancer_result($result,@hosts);
 1559:             if ($is_balancer) {
 1560:                 if (ref($currrules) eq 'HASH') {
 1561:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1562:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1563:                     }
 1564:                 }
 1565:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1566:                                                        $uname,$udom);
 1567:             }
 1568:         } else {
 1569:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1570:                 $is_balancer = 1;
 1571:                 $offloadto = &this_host_spares($dom_in_use);
 1572:             }
 1573:             unless (defined($cached)) {
 1574:                 $domneedscache = $serverhomedom;
 1575:             }
 1576:         }
 1577:     } else {
 1578:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1579:             $is_balancer = 1;
 1580:             $offloadto = &this_host_spares($dom_in_use);
 1581:         }
 1582:         unless (defined($cached)) {
 1583:             $domneedscache = $serverhomedom;
 1584:         }
 1585:     }
 1586:     if ($domneedscache) {
 1587:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1588:     }
 1589:     if ($is_balancer) {
 1590:         my $lowest_load = 30000;
 1591:         if (ref($offloadto) eq 'HASH') {
 1592:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1593:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1594:                     ($otherserver,$lowest_load) =
 1595:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1596:                 }
 1597:             }
 1598:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1599: 
 1600:             if (!$found_server) {
 1601:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1602:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1603:                         ($otherserver,$lowest_load) =
 1604:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1605:                     }
 1606:                 }
 1607:             }
 1608:         } elsif (ref($offloadto) eq 'ARRAY') {
 1609:             if (@{$offloadto} == 1) {
 1610:                 $otherserver = $offloadto->[0];
 1611:             } elsif (@{$offloadto} > 1) {
 1612:                 foreach my $try_server (@{$offloadto}) {
 1613:                     ($otherserver,$lowest_load) =
 1614:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1615:                 }
 1616:             }
 1617:         }
 1618:         unless ($caller eq 'login') {
 1619:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1620:                 $is_balancer = 0;
 1621:                 if ($uname ne '' && $udom ne '') {
 1622:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1623:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1624:                                  'user.loadbalcheck.time' => time});
 1625:                     }
 1626:                 }
 1627:             }
 1628:         }
 1629:         unless ($homeintdom) {
 1630:             undef($setcookie);
 1631:         }
 1632:     }
 1633:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1634: }
 1635: 
 1636: sub check_balancer_result {
 1637:     my ($result,@hosts) = @_;
 1638:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1639:     if (ref($result) eq 'HASH') {
 1640:         if ($result->{'lonhost'} ne '') {
 1641:             my $currbalancer = $result->{'lonhost'};
 1642:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1643:                 $is_balancer = 1;
 1644:                 $currtargets = $result->{'targets'};
 1645:                 $currrules = $result->{'rules'};
 1646:             }
 1647:             $dom_balancers = $currbalancer;
 1648:         } else {
 1649:             if (keys(%{$result})) {
 1650:                 foreach my $key (keys(%{$result})) {
 1651:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1652:                         (ref($result->{$key}) eq 'HASH')) {
 1653:                         $is_balancer = 1;
 1654:                         $currrules = $result->{$key}{'rules'};
 1655:                         $currtargets = $result->{$key}{'targets'};
 1656:                         $setcookie = $result->{$key}{'cookie'};
 1657:                         last;
 1658:                     }
 1659:                 }
 1660:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1661:             }
 1662:         }
 1663:     }
 1664:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1665: }
 1666: 
 1667: sub get_loadbalancer_targets {
 1668:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1669:     my $offloadto;
 1670:     if ($rule_in_effect eq 'none') {
 1671:         return [$perlvar{'lonHostID'}];
 1672:     } elsif ($rule_in_effect eq '') {
 1673:         $offloadto = $currtargets;
 1674:     } else {
 1675:         if ($rule_in_effect eq 'homeserver') {
 1676:             my $homeserver = &homeserver($uname,$udom);
 1677:             if ($homeserver ne 'no_host') {
 1678:                 $offloadto = [$homeserver];
 1679:             }
 1680:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1681:             my %domconfig =
 1682:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1683:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1684:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1685:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1686:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1687:                     }
 1688:                 }
 1689:             } else {
 1690:                 my %servers = &internet_dom_servers($udom);
 1691:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1692:                 if (&hostname($remotebalancer) ne '') {
 1693:                     $offloadto = [$remotebalancer];
 1694:                 }
 1695:             }
 1696:         } elsif (&hostname($rule_in_effect) ne '') {
 1697:             $offloadto = [$rule_in_effect];
 1698:         }
 1699:     }
 1700:     return $offloadto;
 1701: }
 1702: 
 1703: sub internet_dom_servers {
 1704:     my ($dom) = @_;
 1705:     my (%uniqservers,%servers);
 1706:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1707:     my @machinedoms = &machine_domains($primaryserver);
 1708:     foreach my $mdom (@machinedoms) {
 1709:         my %currservers = %servers;
 1710:         my %server = &get_servers($mdom);
 1711:         %servers = (%currservers,%server);
 1712:     }
 1713:     my %by_hostname;
 1714:     foreach my $id (keys(%servers)) {
 1715:         push(@{$by_hostname{$servers{$id}}},$id);
 1716:     }
 1717:     foreach my $hostname (sort(keys(%by_hostname))) {
 1718:         if (@{$by_hostname{$hostname}} > 1) {
 1719:             my $match = 0;
 1720:             foreach my $id (@{$by_hostname{$hostname}}) {
 1721:                 if (&host_domain($id) eq $dom) {
 1722:                     $uniqservers{$id} = $hostname;
 1723:                     $match = 1;
 1724:                 }
 1725:             }
 1726:             unless ($match) {
 1727:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1728:             }
 1729:         } else {
 1730:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1731:         }
 1732:     }
 1733:     return %uniqservers;
 1734: }
 1735: 
 1736: sub trusted_domains {
 1737:     my ($cmdtype,$calldom) = @_;
 1738:     my ($trusted,$untrusted);
 1739:     if (&domain($calldom) eq '') {
 1740:         return ($trusted,$untrusted);
 1741:     }
 1742:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1743:         return ($trusted,$untrusted);
 1744:     }
 1745:     my $callprimary = &domain($calldom,'primary');
 1746:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1747:     if ($intcalldom eq '') {
 1748:         return ($trusted,$untrusted);
 1749:     }
 1750: 
 1751:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1752:     unless (defined($cached)) {
 1753:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1754:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1755:         $trustconfig = $domconfig{'trust'};
 1756:     }
 1757:     if (ref($trustconfig)) {
 1758:         my (%possexc,%possinc,@allexc,@allinc); 
 1759:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1760:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1761:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1762:             }
 1763:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1764:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1765:             }
 1766:         }
 1767:         if (keys(%possexc)) {
 1768:             if (keys(%possinc)) {
 1769:                 foreach my $key (sort(keys(%possexc))) {
 1770:                     next if ($key eq $intcalldom);
 1771:                     unless ($possinc{$key}) {
 1772:                         push(@allexc,$key);
 1773:                     }
 1774:                 }
 1775:             } else {
 1776:                 @allexc = sort(keys(%possexc));
 1777:             }
 1778:         }
 1779:         if (keys(%possinc)) {
 1780:             $possinc{$intcalldom} = 1;
 1781:             @allinc = sort(keys(%possinc));
 1782:         }
 1783:         if ((@allexc > 0) || (@allinc > 0)) {
 1784:             my %doms_by_intdom;
 1785:             my %allintdoms = &all_host_intdom();
 1786:             my %alldoms = &all_host_domain();
 1787:             foreach my $key (%allintdoms) {
 1788:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1789:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1790:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1791:                     }
 1792:                 } else {
 1793:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1794:                 }
 1795:             }
 1796:             foreach my $exc (@allexc) {
 1797:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1798:                     $untrusted = $doms_by_intdom{$exc};
 1799:                 }
 1800:             }
 1801:             foreach my $inc (@allinc) {
 1802:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1803:                     $trusted = $doms_by_intdom{$inc};
 1804:                 }
 1805:             }
 1806:         }
 1807:     }
 1808:     return ($trusted,$untrusted);
 1809: }
 1810: 
 1811: sub will_trust {
 1812:     my ($cmdtype,$domain,$possdom) = @_;
 1813:     return 1 if ($domain eq $possdom);
 1814:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1815:     my $willtrust; 
 1816:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1817:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1818:             $willtrust = 1;
 1819:         }
 1820:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1821:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1822:             $willtrust = 1;
 1823:         }
 1824:     } else {
 1825:         $willtrust = 1;
 1826:     }
 1827:     return $willtrust;
 1828: }
 1829: 
 1830: # ---------------------- Find the homebase for a user from domain's lib servers
 1831: 
 1832: my %homecache;
 1833: sub homeserver {
 1834:     my ($uname,$udom,$ignoreBadCache)=@_;
 1835:     my $index="$uname:$udom";
 1836: 
 1837:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1838: 
 1839:     my %servers = &get_servers($udom,'library');
 1840:     foreach my $tryserver (keys(%servers)) {
 1841:         next if ($ignoreBadCache ne 'true' && 
 1842: 		 exists($badServerCache{$tryserver}));
 1843: 
 1844: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1845: 	if ($answer eq 'found') {
 1846: 	    delete($badServerCache{$tryserver}); 
 1847: 	    return $homecache{$index}=$tryserver;
 1848: 	} elsif ($answer eq 'no_host') {
 1849: 	    $badServerCache{$tryserver}=1;
 1850: 	}
 1851:     }    
 1852:     return 'no_host';
 1853: }
 1854: 
 1855: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1856: 
 1857: sub idget {
 1858:     my ($udom,$idsref,$namespace)=@_;
 1859:     my %returnhash=();
 1860:     my @ids=(); 
 1861:     if (ref($idsref) eq 'ARRAY') {
 1862:         @ids = @{$idsref};
 1863:     } else {
 1864:         return %returnhash; 
 1865:     }
 1866:     if ($namespace eq '') {
 1867:         $namespace = 'ids';
 1868:     }
 1869:     
 1870:     my %servers = &get_servers($udom,'library');
 1871:     foreach my $tryserver (keys(%servers)) {
 1872: 	my $idlist=join('&', map { &escape($_); } @ids);
 1873: 	if ($namespace eq 'ids') {
 1874: 	    $idlist=~tr/A-Z/a-z/;
 1875: 	}
 1876: 	my $reply;
 1877: 	if ($namespace eq 'ids') {
 1878: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1879: 	} else {
 1880: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1881: 	}
 1882: 	my @answer=();
 1883: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1884: 	    @answer=split(/\&/,$reply);
 1885: 	}                    ;
 1886: 	my $i;
 1887: 	for ($i=0;$i<=$#ids;$i++) {
 1888: 	    if ($answer[$i]) {
 1889: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1890: 	    }
 1891: 	}
 1892:     }
 1893:     return %returnhash;
 1894: }
 1895: 
 1896: # ------------------------------------- Find the IDs behind a list of usernames
 1897: 
 1898: sub idrget {
 1899:     my ($udom,@unames)=@_;
 1900:     my %returnhash=();
 1901:     foreach my $uname (@unames) {
 1902:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1903:     }
 1904:     return %returnhash;
 1905: }
 1906: 
 1907: # Store away a list of names and associated student/employee IDs or clicker IDs
 1908: 
 1909: sub idput {
 1910:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1911:     my %servers=();
 1912:     my %ids=();
 1913:     my %byid = ();
 1914:     if (ref($idsref) eq 'HASH') {
 1915:         %ids=%{$idsref};
 1916:     }
 1917:     if ($namespace eq '') {
 1918:         $namespace = 'ids'; 
 1919:     }
 1920:     foreach my $uname (keys(%ids)) {
 1921: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1922:         if ($uhom eq '') {
 1923:             $uhom=&homeserver($uname,$udom);
 1924:         }
 1925:         if ($uhom ne 'no_host') {
 1926:             my $esc_unam=&escape($uname);
 1927:             if ($namespace eq 'ids') {
 1928:                 my $id=&escape($ids{$uname});
 1929:                 $id=~tr/A-Z/a-z/;
 1930:                 my $esc_unam=&escape($uname);
 1931:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1932:             } else {
 1933:                 my @currids = split(/,/,$ids{$uname});
 1934:                 foreach my $id (@currids) {
 1935:                     $byid{$uhom}{$id} .= $uname.',';
 1936:                 }
 1937:             }
 1938:         }
 1939:     }
 1940:     if ($namespace eq 'clickers') {
 1941:         foreach my $server (keys(%byid)) {
 1942:             if (ref($byid{$server}) eq 'HASH') {
 1943:                 foreach my $id (keys(%{$byid{$server}})) {
 1944:                     $byid{$server} =~ s/,$//;
 1945:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1946:                 }
 1947:             }
 1948:         }
 1949:     }
 1950:     foreach my $server (keys(%servers)) {
 1951:         $servers{$server} =~ s/\&$//;
 1952:         if ($namespace eq 'ids') {     
 1953:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1954:         } else {
 1955:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1956:         }
 1957:     }
 1958: }
 1959: 
 1960: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1961: 
 1962: sub iddel {
 1963:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1964:     my %result=();
 1965:     my %ids=();
 1966:     my %byid = ();
 1967:     if (ref($idshashref) eq 'HASH') {
 1968:         %ids=%{$idshashref};
 1969:     } else {
 1970:         return %result;
 1971:     }
 1972:     if ($namespace eq '') {
 1973:         $namespace = 'ids';
 1974:     }
 1975:     my %servers=();
 1976:     while (my ($id,$unamestr) = each(%ids)) {
 1977:         if ($namespace eq 'ids') {
 1978:             my $uhom = $uhome;
 1979:             if ($uhom eq '') { 
 1980:                 $uhom=&homeserver($unamestr,$udom);
 1981:             }
 1982:             if ($uhom ne 'no_host') {
 1983:                 $servers{$uhom}.='&'.&escape($id);
 1984:             }
 1985:          } else {
 1986:             my @curritems = split(/,/,$ids{$id});
 1987:             foreach my $uname (@curritems) {
 1988:                 my $uhom = $uhome;
 1989:                 if ($uhom eq '') {
 1990:                     $uhom=&homeserver($uname,$udom);
 1991:                 }
 1992:                 if ($uhom ne 'no_host') { 
 1993:                     $byid{$uhom}{$id} .= $uname.',';
 1994:                 }
 1995:             }
 1996:         }
 1997:     }
 1998:     if ($namespace eq 'clickers') {
 1999:         foreach my $server (keys(%byid)) {
 2000:             if (ref($byid{$server}) eq 'HASH') {
 2001:                 foreach my $id (keys(%{$byid{$server}})) {
 2002:                     $byid{$server}{$id} =~ s/,$//;
 2003:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2004:                 }
 2005:             }
 2006:         }
 2007:     }
 2008:     foreach my $server (keys(%servers)) {
 2009:         $servers{$server} =~ s/\&$//;
 2010:         if ($namespace eq 'ids') {
 2011:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2012:         } elsif ($namespace eq 'clickers') {
 2013:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2014:         }
 2015:     }
 2016:     return %result;
 2017: }
 2018: 
 2019: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2020: 
 2021: sub updateclickers {
 2022:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2023:     my %clickers;
 2024:     if (ref($idshashref) eq 'HASH') {
 2025:         %clickers=%{$idshashref};
 2026:     } else {
 2027:         return;
 2028:     }
 2029:     my $items='';
 2030:     foreach my $item (keys(%clickers)) {
 2031:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2032:     }
 2033:     $items=~s/\&$//;
 2034:     my $request = "updateclickers:$udom:$action:$items";
 2035:     if ($critical) {
 2036:         return &critical($request,$uhome);
 2037:     } else {
 2038:         return &reply($request,$uhome);
 2039:     }
 2040: }
 2041: 
 2042: # ------------------------------dump from db file owned by domainconfig user
 2043: sub dump_dom {
 2044:     my ($namespace, $udom, $regexp) = @_;
 2045: 
 2046:     $udom ||= $env{'user.domain'};
 2047: 
 2048:     return () unless $udom;
 2049: 
 2050:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2051: }
 2052: 
 2053: # ------------------------------------------ get items from domain db files   
 2054: 
 2055: sub get_dom {
 2056:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2057:     return if ($udom eq 'public');
 2058:     my $items='';
 2059:     foreach my $item (@$storearr) {
 2060:         $items.=&escape($item).'&';
 2061:     }
 2062:     $items=~s/\&$//;
 2063:     if (!$udom) {
 2064:         $udom=$env{'user.domain'};
 2065:         return if ($udom eq 'public');
 2066:         if (defined(&domain($udom,'primary'))) {
 2067:             $uhome=&domain($udom,'primary');
 2068:         } else {
 2069:             undef($uhome);
 2070:         }
 2071:     } else {
 2072:         if (!$uhome) {
 2073:             if (defined(&domain($udom,'primary'))) {
 2074:                 $uhome=&domain($udom,'primary');
 2075:             }
 2076:         }
 2077:     }
 2078:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2079:         my $rep;
 2080:         if ($namespace =~ /^enc/) {
 2081:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2082:         } else {
 2083:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2084:         }
 2085:         my %returnhash;
 2086:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2087:             return %returnhash;
 2088:         }
 2089:         my @pairs=split(/\&/,$rep);
 2090:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2091:             return @pairs;
 2092:         }
 2093:         my $i=0;
 2094:         foreach my $item (@$storearr) {
 2095:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2096:             $i++;
 2097:         }
 2098:         return %returnhash;
 2099:     } else {
 2100:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2101:     }
 2102: }
 2103: 
 2104: # -------------------------------------------- put items in domain db files 
 2105: 
 2106: sub put_dom {
 2107:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2108:     if (!$udom) {
 2109:         $udom=$env{'user.domain'};
 2110:         if (defined(&domain($udom,'primary'))) {
 2111:             $uhome=&domain($udom,'primary');
 2112:         } else {
 2113:             undef($uhome);
 2114:         }
 2115:     } else {
 2116:         if (!$uhome) {
 2117:             if (defined(&domain($udom,'primary'))) {
 2118:                 $uhome=&domain($udom,'primary');
 2119:             }
 2120:         }
 2121:     } 
 2122:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2123:         my $items='';
 2124:         foreach my $item (keys(%$storehash)) {
 2125:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2126:         }
 2127:         $items=~s/\&$//;
 2128:         if ($namespace =~ /^enc/) {
 2129:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2130:         } else {
 2131:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2132:         }
 2133:     } else {
 2134:         &logthis("put_dom failed - no homeserver and/or domain");
 2135:     }
 2136: }
 2137: 
 2138: # --------------------- newput for items in db file owned by domainconfig user
 2139: sub newput_dom {
 2140:     my ($namespace,$storehash,$udom) = @_;
 2141:     my $result;
 2142:     if (!$udom) {
 2143:         $udom=$env{'user.domain'};
 2144:     }
 2145:     if ($udom) {
 2146:         my $uname = &get_domainconfiguser($udom);
 2147:         $result = &newput($namespace,$storehash,$udom,$uname);
 2148:     }
 2149:     return $result;
 2150: }
 2151: 
 2152: # --------------------- delete for items in db file owned by domainconfig user
 2153: sub del_dom {
 2154:     my ($namespace,$storearr,$udom)=@_;
 2155:     if (ref($storearr) eq 'ARRAY') {
 2156:         if (!$udom) {
 2157:             $udom=$env{'user.domain'};
 2158:         }
 2159:         if ($udom) {
 2160:             my $uname = &get_domainconfiguser($udom); 
 2161:             return &del($namespace,$storearr,$udom,$uname);
 2162:         }
 2163:     }
 2164: }
 2165: 
 2166: # ----------------------------------construct domainconfig user for a domain 
 2167: sub get_domainconfiguser {
 2168:     my ($udom) = @_;
 2169:     return $udom.'-domainconfig';
 2170: }
 2171: 
 2172: sub retrieve_inst_usertypes {
 2173:     my ($udom) = @_;
 2174:     my (%returnhash,@order);
 2175:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2176:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2177:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2178:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2179:     } else {
 2180:         if (defined(&domain($udom,'primary'))) {
 2181:             my $uhome=&domain($udom,'primary');
 2182:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2183:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2184:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2185:                 return (\%returnhash,\@order);
 2186:             }
 2187:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2188:             my @pairs=split(/\&/,$hashitems);
 2189:             foreach my $item (@pairs) {
 2190:                 my ($key,$value)=split(/=/,$item,2);
 2191:                 $key = &unescape($key);
 2192:                 next if ($key =~ /^error: 2 /);
 2193:                 $returnhash{$key}=&thaw_unescape($value);
 2194:             }
 2195:             my @esc_order = split(/\&/,$orderitems);
 2196:             foreach my $item (@esc_order) {
 2197:                 push(@order,&unescape($item));
 2198:             }
 2199:         } else {
 2200:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2201:         }
 2202:         return (\%returnhash,\@order);
 2203:     }
 2204: }
 2205: 
 2206: sub is_domainimage {
 2207:     my ($url) = @_;
 2208:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2209:         if (&domain($1) ne '') {
 2210:             return '1';
 2211:         }
 2212:     }
 2213:     return;
 2214: }
 2215: 
 2216: sub inst_directory_query {
 2217:     my ($srch) = @_;
 2218:     my $udom = $srch->{'srchdomain'};
 2219:     my %results;
 2220:     my $homeserver = &domain($udom,'primary');
 2221:     my $outcome;
 2222:     if ($homeserver ne '') {
 2223:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2224:             if ($srch->{'srchby'} eq 'email') {
 2225:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2226:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2227:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2228:                     (($major == 2) && ($minor < 12))) {
 2229:                     return;
 2230:                 }
 2231:             }
 2232:         }
 2233: 	my $queryid=&reply("querysend:instdirsearch:".
 2234: 			   &escape($srch->{'srchby'}).':'.
 2235: 			   &escape($srch->{'srchterm'}).':'.
 2236: 			   &escape($srch->{'srchtype'}),$homeserver);
 2237: 	my $host=&hostname($homeserver);
 2238: 	if ($queryid !~/^\Q$host\E\_/) {
 2239: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2240: 	    return;
 2241: 	}
 2242: 	my $response = &get_query_reply($queryid);
 2243: 	my $maxtries = 5;
 2244: 	my $tries = 1;
 2245: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2246: 	    $response = &get_query_reply($queryid);
 2247: 	    $tries ++;
 2248: 	}
 2249: 
 2250:         if (!&error($response) && $response ne 'refused') {
 2251:             if ($response eq 'unavailable') {
 2252:                 $outcome = $response;
 2253:             } else {
 2254:                 $outcome = 'ok';
 2255:                 my @matches = split(/\n/,$response);
 2256:                 foreach my $match (@matches) {
 2257:                     my ($key,$value) = split(/=/,$match);
 2258:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2259:                 }
 2260:             }
 2261:         }
 2262:     }
 2263:     return ($outcome,%results);
 2264: }
 2265: 
 2266: sub usersearch {
 2267:     my ($srch) = @_;
 2268:     my $dom = $srch->{'srchdomain'};
 2269:     my %results;
 2270:     my %libserv = &all_library();
 2271:     my $query = 'usersearch';
 2272:     foreach my $tryserver (keys(%libserv)) {
 2273:         if (&host_domain($tryserver) eq $dom) {
 2274:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2275:                 if ($srch->{'srchby'} eq 'email') {
 2276:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2277:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2278:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2279:                              (($major == 2) && ($minor < 12)));
 2280:                 }
 2281:             }
 2282:             my $host=&hostname($tryserver);
 2283:             my $queryid=
 2284:                 &reply("querysend:".&escape($query).':'.
 2285:                        &escape($srch->{'srchby'}).':'.
 2286:                        &escape($srch->{'srchtype'}).':'.
 2287:                        &escape($srch->{'srchterm'}),$tryserver);
 2288:             if ($queryid !~/^\Q$host\E\_/) {
 2289:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2290:                 next;
 2291:             }
 2292:             my $reply = &get_query_reply($queryid);
 2293:             my $maxtries = 1;
 2294:             my $tries = 1;
 2295:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2296:                 $reply = &get_query_reply($queryid);
 2297:                 $tries ++;
 2298:             }
 2299:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2300:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2301:             } else {
 2302:                 my @matches;
 2303:                 if ($reply =~ /\n/) {
 2304:                     @matches = split(/\n/,$reply);
 2305:                 } else {
 2306:                     @matches = split(/\&/,$reply);
 2307:                 }
 2308:                 foreach my $match (@matches) {
 2309:                     my ($uname,$udom,%userhash);
 2310:                     foreach my $entry (split(/:/,$match)) {
 2311:                         my ($key,$value) =
 2312:                             map {&unescape($_);} split(/=/,$entry);
 2313:                         $userhash{$key} = $value;
 2314:                         if ($key eq 'username') {
 2315:                             $uname = $value;
 2316:                         } elsif ($key eq 'domain') {
 2317:                             $udom = $value;
 2318:                         }
 2319:                     }
 2320:                     $results{$uname.':'.$udom} = \%userhash;
 2321:                 }
 2322:             }
 2323:         }
 2324:     }
 2325:     return %results;
 2326: }
 2327: 
 2328: sub get_instuser {
 2329:     my ($udom,$uname,$id) = @_;
 2330:     my $homeserver = &domain($udom,'primary');
 2331:     my ($outcome,%results);
 2332:     if ($homeserver ne '') {
 2333:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2334:                            &escape($id).':'.&escape($udom),$homeserver);
 2335:         my $host=&hostname($homeserver);
 2336:         if ($queryid !~/^\Q$host\E\_/) {
 2337:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2338:             return;
 2339:         }
 2340:         my $response = &get_query_reply($queryid);
 2341:         my $maxtries = 5;
 2342:         my $tries = 1;
 2343:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2344:             $response = &get_query_reply($queryid);
 2345:             $tries ++;
 2346:         }
 2347:         if (!&error($response) && $response ne 'refused') {
 2348:             if ($response eq 'unavailable') {
 2349:                 $outcome = $response;
 2350:             } else {
 2351:                 $outcome = 'ok';
 2352:                 my @matches = split(/\n/,$response);
 2353:                 foreach my $match (@matches) {
 2354:                     my ($key,$value) = split(/=/,$match);
 2355:                     $results{&unescape($key)} = &thaw_unescape($value);
 2356:                 }
 2357:             }
 2358:         }
 2359:     }
 2360:     my %userinfo;
 2361:     if (ref($results{$uname}) eq 'HASH') {
 2362:         %userinfo = %{$results{$uname}};
 2363:     } 
 2364:     return ($outcome,%userinfo);
 2365: }
 2366: 
 2367: sub get_multiple_instusers {
 2368:     my ($udom,$users,$caller) = @_;
 2369:     my ($outcome,$results);
 2370:     if (ref($users) eq 'HASH') {
 2371:         my $count = keys(%{$users}); 
 2372:         my $requested = &freeze_escape($users);
 2373:         my $homeserver = &domain($udom,'primary');
 2374:         if ($homeserver ne '') {
 2375:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2376:             my $host=&hostname($homeserver);
 2377:             if ($queryid !~/^\Q$host\E\_/) {
 2378:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2379:                          ' for host: '.$homeserver.'in domain '.$udom);
 2380:                 return ($outcome,$results);
 2381:             }
 2382:             my $response = &get_query_reply($queryid);
 2383:             my $maxtries = 5;
 2384:             if ($count > 100) {
 2385:                 $maxtries = 1+int($count/20);
 2386:             }
 2387:             my $tries = 1;
 2388:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2389:                 $response = &get_query_reply($queryid);
 2390:                 $tries ++;
 2391:             }
 2392:             if ($response eq '') {
 2393:                 $results = {};
 2394:                 foreach my $key (keys(%{$users})) {
 2395:                     my ($uname,$id);
 2396:                     if ($caller eq 'id') {
 2397:                         $id = $key;
 2398:                     } else {
 2399:                         $uname = $key;
 2400:                     }
 2401:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2402:                     $outcome = $resp;
 2403:                     if ($resp eq 'ok') {
 2404:                         %{$results} = (%{$results}, %info);
 2405:                     } else {
 2406:                         last;
 2407:                     }
 2408:                 }
 2409:             } elsif(!&error($response) && ($response ne 'refused')) {
 2410:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2411:                     $outcome = $response;
 2412:                 } else {
 2413:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2414:                     if ($outcome eq 'ok') {
 2415:                         $results = &thaw_unescape($userdata); 
 2416:                     }
 2417:                 }
 2418:             }
 2419:         }
 2420:     }
 2421:     return ($outcome,$results);
 2422: }
 2423: 
 2424: sub inst_rulecheck {
 2425:     my ($udom,$uname,$id,$item,$rules) = @_;
 2426:     my %returnhash;
 2427:     if ($udom ne '') {
 2428:         if (ref($rules) eq 'ARRAY') {
 2429:             @{$rules} = map {&escape($_);} (@{$rules});
 2430:             my $rulestr = join(':',@{$rules});
 2431:             my $homeserver=&domain($udom,'primary');
 2432:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2433:                 my $response;
 2434:                 if ($item eq 'username') {                
 2435:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2436:                                               ':'.&escape($uname).':'.$rulestr,
 2437:                                               $homeserver));
 2438:                 } elsif ($item eq 'id') {
 2439:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2440:                                               ':'.&escape($id).':'.$rulestr,
 2441:                                               $homeserver));
 2442:                 } elsif ($item eq 'selfcreate') {
 2443:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2444:                                                &escape($udom).':'.&escape($uname).
 2445:                                               ':'.$rulestr,$homeserver));
 2446:                 }
 2447:                 if ($response ne 'refused') {
 2448:                     my @pairs=split(/\&/,$response);
 2449:                     foreach my $item (@pairs) {
 2450:                         my ($key,$value)=split(/=/,$item,2);
 2451:                         $key = &unescape($key);
 2452:                         next if ($key =~ /^error: 2 /);
 2453:                         $returnhash{$key}=&thaw_unescape($value);
 2454:                     }
 2455:                 }
 2456:             }
 2457:         }
 2458:     }
 2459:     return %returnhash;
 2460: }
 2461: 
 2462: sub inst_userrules {
 2463:     my ($udom,$check) = @_;
 2464:     my (%ruleshash,@ruleorder);
 2465:     if ($udom ne '') {
 2466:         my $homeserver=&domain($udom,'primary');
 2467:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2468:             my $response;
 2469:             if ($check eq 'id') {
 2470:                 $response=&reply('instidrules:'.&escape($udom),
 2471:                                  $homeserver);
 2472:             } elsif ($check eq 'email') {
 2473:                 $response=&reply('instemailrules:'.&escape($udom),
 2474:                                  $homeserver);
 2475:             } else {
 2476:                 $response=&reply('instuserrules:'.&escape($udom),
 2477:                                  $homeserver);
 2478:             }
 2479:             if (($response ne 'refused') && ($response ne 'error') && 
 2480:                 ($response ne 'unknown_cmd') && 
 2481:                 ($response ne 'no_such_host')) {
 2482:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2483:                 my @pairs=split(/\&/,$hashitems);
 2484:                 foreach my $item (@pairs) {
 2485:                     my ($key,$value)=split(/=/,$item,2);
 2486:                     $key = &unescape($key);
 2487:                     next if ($key =~ /^error: 2 /);
 2488:                     $ruleshash{$key}=&thaw_unescape($value);
 2489:                 }
 2490:                 my @esc_order = split(/\&/,$orderitems);
 2491:                 foreach my $item (@esc_order) {
 2492:                     push(@ruleorder,&unescape($item));
 2493:                 }
 2494:             }
 2495:         }
 2496:     }
 2497:     return (\%ruleshash,\@ruleorder);
 2498: }
 2499: 
 2500: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2501: 
 2502: sub get_domain_defaults {
 2503:     my ($domain,$ignore_cache) = @_;
 2504:     return if (($domain eq '') || ($domain eq 'public'));
 2505:     my $cachetime = 60*60*24;
 2506:     unless ($ignore_cache) {
 2507:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2508:         if (defined($cached)) {
 2509:             if (ref($result) eq 'HASH') {
 2510:                 return %{$result};
 2511:             }
 2512:         }
 2513:     }
 2514:     my %domdefaults;
 2515:     my %domconfig =
 2516:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2517:                                   'requestcourses','inststatus',
 2518:                                   'coursedefaults','usersessions',
 2519:                                   'requestauthor','selfenrollment',
 2520:                                   'coursecategories','ssl','autoenroll',
 2521:                                   'trust','helpsettings'],$domain);
 2522:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2523:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2524:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2525:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2526:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2527:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2528:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2529:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2530:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2531:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2532:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2533:     } else {
 2534:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2535:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2536:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2537:     }
 2538:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2539:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2540:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2541:         } else {
 2542:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2543:         }
 2544:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2545:         foreach my $item (@usertools) {
 2546:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2547:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2548:             }
 2549:         }
 2550:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2551:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2552:         }
 2553:     }
 2554:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2555:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2556:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2557:         }
 2558:     }
 2559:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2560:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2561:     }
 2562:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2563:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2564:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2565:         }
 2566:     }
 2567:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2568:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2569:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2570:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2571:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2572:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2573:         }
 2574:         foreach my $type (@coursetypes) {
 2575:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2576:                 unless ($type eq 'community') {
 2577:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2578:                 }
 2579:             }
 2580:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2581:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2582:             }
 2583:             if ($domdefaults{'postsubmit'} eq 'on') {
 2584:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2585:                     $domdefaults{$type.'postsubtimeout'} = 
 2586:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2587:                 }
 2588:             }
 2589:         }
 2590:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2591:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2592:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2593:                 if (@clonecodes) {
 2594:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2595:                 }
 2596:             }
 2597:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2598:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2599:         }
 2600:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2601:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2602:         } 
 2603:     }
 2604:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2605:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2606:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2607:         }
 2608:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2609:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2610:         }
 2611:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2612:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2613:         }
 2614:     }
 2615:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2616:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2617:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2618:                             'approval','limit');
 2619:             foreach my $type (@coursetypes) {
 2620:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2621:                     my @mgrdc = ();
 2622:                     foreach my $item (@settings) {
 2623:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2624:                             push(@mgrdc,$item);
 2625:                         }
 2626:                     }
 2627:                     if (@mgrdc) {
 2628:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2629:                     }
 2630:                 }
 2631:             }
 2632:         }
 2633:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2634:             foreach my $type (@coursetypes) {
 2635:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2636:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2637:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2638:                     }
 2639:                 }
 2640:             }
 2641:         }
 2642:     }
 2643:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2644:         $domdefaults{'catauth'} = 'std';
 2645:         $domdefaults{'catunauth'} = 'std';
 2646:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2647:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2648:         }
 2649:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2650:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2651:         }
 2652:     }
 2653:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2654:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2655:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2656:         }
 2657:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2658:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2659:         }
 2660:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2661:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2662:         }
 2663:     }
 2664:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2665:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2666:         foreach my $prefix (@prefixes) {
 2667:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2668:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2669:             }
 2670:         }
 2671:     }
 2672:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2673:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2674:     }
 2675:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2676:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2677:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2678:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2679:         }
 2680:     }
 2681:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2682:     return %domdefaults;
 2683: }
 2684: 
 2685: sub course_portal_url {
 2686:     my ($cnum,$cdom) = @_;
 2687:     my $chome = &homeserver($cnum,$cdom);
 2688:     my $hostname = &hostname($chome);
 2689:     my $protocol = $protocol{$chome};
 2690:     $protocol = 'http' if ($protocol ne 'https');
 2691:     my %domdefaults = &get_domain_defaults($cdom);
 2692:     my $firsturl;
 2693:     if ($domdefaults{'portal_def'}) {
 2694:         $firsturl = $domdefaults{'portal_def'};
 2695:     } else {
 2696:         $firsturl = $protocol.'://'.$hostname;
 2697:     }
 2698:     return $firsturl;
 2699: }
 2700: 
 2701: # --------------------------------------------------- Assign a key to a student
 2702: 
 2703: sub assign_access_key {
 2704: #
 2705: # a valid key looks like uname:udom#comments
 2706: # comments are being appended
 2707: #
 2708:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2709:     $kdom=
 2710:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2711:     $knum=
 2712:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2713:     $cdom=
 2714:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2715:     $cnum=
 2716:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2717:     $udom=$env{'user.name'} unless (defined($udom));
 2718:     $uname=$env{'user.domain'} unless (defined($uname));
 2719:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2720:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2721:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2722:                                                   # assigned to this person
 2723:                                                   # - this should not happen,
 2724:                                                   # unless something went wrong
 2725:                                                   # the first time around
 2726: # ready to assign
 2727:         $logentry=$1.'; '.$logentry;
 2728:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2729:                                                  $kdom,$knum) eq 'ok') {
 2730: # key now belongs to user
 2731: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2732:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2733:                 &appenv({'environment.'.$envkey => $ckey});
 2734:                 return 'ok';
 2735:             } else {
 2736:                 return 
 2737:   'error: Count not permanently assign key, will need to be re-entered later.';
 2738: 	    }
 2739:         } else {
 2740:             return 'error: Could not assign key, try again later.';
 2741:         }
 2742:     } elsif (!$existing{$ckey}) {
 2743: # the key does not exist
 2744: 	return 'error: The key does not exist';
 2745:     } else {
 2746: # the key is somebody else's
 2747: 	return 'error: The key is already in use';
 2748:     }
 2749: }
 2750: 
 2751: # ------------------------------------------ put an additional comment on a key
 2752: 
 2753: sub comment_access_key {
 2754: #
 2755: # a valid key looks like uname:udom#comments
 2756: # comments are being appended
 2757: #
 2758:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2759:     $cdom=
 2760:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2761:     $cnum=
 2762:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2763:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2764:     if ($existing{$ckey}) {
 2765:         $existing{$ckey}.='; '.$logentry;
 2766: # ready to assign
 2767:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2768:                                                  $cdom,$cnum) eq 'ok') {
 2769: 	    return 'ok';
 2770:         } else {
 2771: 	    return 'error: Count not store comment.';
 2772:         }
 2773:     } else {
 2774: # the key does not exist
 2775: 	return 'error: The key does not exist';
 2776:     }
 2777: }
 2778: 
 2779: # ------------------------------------------------------ Generate a set of keys
 2780: 
 2781: sub generate_access_keys {
 2782:     my ($number,$cdom,$cnum,$logentry)=@_;
 2783:     $cdom=
 2784:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2785:     $cnum=
 2786:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2787:     unless (&allowed('mky',$cdom)) { return 0; }
 2788:     unless (($cdom) && ($cnum)) { return 0; }
 2789:     if ($number>10000) { return 0; }
 2790:     sleep(2); # make sure don't get same seed twice
 2791:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2792:     my $total=0;
 2793:     for (my $i=1;$i<=$number;$i++) {
 2794:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2795:                   sprintf("%lx",int(100000*rand)).'-'.
 2796:                   sprintf("%lx",int(100000*rand));
 2797:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2798:        $newkey=~s/0/h/g; # and also 0 and O
 2799:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2800:        if ($existing{$newkey}) {
 2801:            $i--;
 2802:        } else {
 2803: 	  if (&put('accesskeys',
 2804:               { $newkey => '# generated '.localtime().
 2805:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2806:                            '; '.$logentry },
 2807: 		   $cdom,$cnum) eq 'ok') {
 2808:               $total++;
 2809: 	  }
 2810:        }
 2811:     }
 2812:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2813:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2814:     return $total;
 2815: }
 2816: 
 2817: # ------------------------------------------------------- Validate an accesskey
 2818: 
 2819: sub validate_access_key {
 2820:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2821:     $cdom=
 2822:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2823:     $cnum=
 2824:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2825:     $udom=$env{'user.domain'} unless (defined($udom));
 2826:     $uname=$env{'user.name'} unless (defined($uname));
 2827:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2828:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2829: }
 2830: 
 2831: # ------------------------------------- Find the section of student in a course
 2832: sub devalidate_getsection_cache {
 2833:     my ($udom,$unam,$courseid)=@_;
 2834:     my $hashid="$udom:$unam:$courseid";
 2835:     &devalidate_cache_new('getsection',$hashid);
 2836: }
 2837: 
 2838: sub courseid_to_courseurl {
 2839:     my ($courseid) = @_;
 2840:     #already url style courseid
 2841:     return $courseid if ($courseid =~ m{^/});
 2842: 
 2843:     if (exists($env{'course.'.$courseid.'.num'})) {
 2844: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2845: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2846: 	return "/$cdom/$cnum";
 2847:     }
 2848: 
 2849:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2850:     if (exists($courseinfo{'num'})) {
 2851: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2852:     }
 2853: 
 2854:     return undef;
 2855: }
 2856: 
 2857: sub getsection {
 2858:     my ($udom,$unam,$courseid)=@_;
 2859:     my $cachetime=1800;
 2860: 
 2861:     my $hashid="$udom:$unam:$courseid";
 2862:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2863:     if (defined($cached)) { return $result; }
 2864: 
 2865:     my %Pending; 
 2866:     my %Expired;
 2867:     #
 2868:     # Each role can either have not started yet (pending), be active, 
 2869:     #    or have expired.
 2870:     #
 2871:     # If there is an active role, we are done.
 2872:     #
 2873:     # If there is more than one role which has not started yet, 
 2874:     #     choose the one which will start sooner
 2875:     # If there is one role which has not started yet, return it.
 2876:     #
 2877:     # If there is more than one expired role, choose the one which ended last.
 2878:     # If there is a role which has expired, return it.
 2879:     #
 2880:     $courseid = &courseid_to_courseurl($courseid);
 2881:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2882:     foreach my $key (keys(%roleshash)) {
 2883:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2884:         my $section=$1;
 2885:         if ($key eq $courseid.'_st') { $section=''; }
 2886:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2887:         my $now=time;
 2888:         if (defined($end) && $end && ($now > $end)) {
 2889:             $Expired{$end}=$section;
 2890:             next;
 2891:         }
 2892:         if (defined($start) && $start && ($now < $start)) {
 2893:             $Pending{$start}=$section;
 2894:             next;
 2895:         }
 2896:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2897:     }
 2898:     #
 2899:     # Presumedly there will be few matching roles from the above
 2900:     # loop and the sorting time will be negligible.
 2901:     if (scalar(keys(%Pending))) {
 2902:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2903:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2904:     } 
 2905:     if (scalar(keys(%Expired))) {
 2906:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2907:         my $time = pop(@sorted);
 2908:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2909:     }
 2910:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2911: }
 2912: 
 2913: sub save_cache {
 2914:     &purge_remembered();
 2915:     #&Apache::loncommon::validate_page();
 2916:     undef(%env);
 2917:     undef($env_loaded);
 2918: }
 2919: 
 2920: my $to_remember=-1;
 2921: my %remembered;
 2922: my %accessed;
 2923: my $kicks=0;
 2924: my $hits=0;
 2925: sub make_key {
 2926:     my ($name,$id) = @_;
 2927:     if (length($id) > 65 
 2928: 	&& length(&escape($id)) > 200) {
 2929: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2930:     }
 2931:     return &escape($name.':'.$id);
 2932: }
 2933: 
 2934: sub devalidate_cache_new {
 2935:     my ($name,$id,$debug) = @_;
 2936:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2937:     my $remembered_id=$name.':'.$id;
 2938:     $id=&make_key($name,$id);
 2939:     $memcache->delete($id);
 2940:     delete($remembered{$remembered_id});
 2941:     delete($accessed{$remembered_id});
 2942: }
 2943: 
 2944: sub is_cached_new {
 2945:     my ($name,$id,$debug) = @_;
 2946:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2947:     if (exists($remembered{$remembered_id})) {
 2948: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2949: 	$accessed{$remembered_id}=[&gettimeofday()];
 2950: 	$hits++;
 2951: 	return ($remembered{$remembered_id},1);
 2952:     }
 2953:     $id=&make_key($name,$id);
 2954:     my $value = $memcache->get($id);
 2955:     if (!(defined($value))) {
 2956: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2957: 	return (undef,undef);
 2958:     }
 2959:     if ($value eq '__undef__') {
 2960: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2961: 	$value=undef;
 2962:     }
 2963:     &make_room($remembered_id,$value,$debug);
 2964:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2965:     return ($value,1);
 2966: }
 2967: 
 2968: sub do_cache_new {
 2969:     my ($name,$id,$value,$time,$debug) = @_;
 2970:     my $remembered_id=$name.':'.$id;
 2971:     $id=&make_key($name,$id);
 2972:     my $setvalue=$value;
 2973:     if (!defined($setvalue)) {
 2974: 	$setvalue='__undef__';
 2975:     }
 2976:     if (!defined($time) ) {
 2977: 	$time=600;
 2978:     }
 2979:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2980:     my $result = $memcache->set($id,$setvalue,$time);
 2981:     if (! $result) {
 2982: 	&logthis("caching of id -> $id  failed");
 2983: 	$memcache->disconnect_all();
 2984:     }
 2985:     # need to make a copy of $value
 2986:     &make_room($remembered_id,$value,$debug);
 2987:     return $value;
 2988: }
 2989: 
 2990: sub make_room {
 2991:     my ($remembered_id,$value,$debug)=@_;
 2992: 
 2993:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2994:                                     : $value;
 2995:     if ($to_remember<0) { return; }
 2996:     $accessed{$remembered_id}=[&gettimeofday()];
 2997:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2998:     my $to_kick;
 2999:     my $max_time=0;
 3000:     foreach my $other (keys(%accessed)) {
 3001: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3002: 	    $to_kick=$other;
 3003: 	    $max_time=&tv_interval($accessed{$other});
 3004: 	}
 3005:     }
 3006:     delete($remembered{$to_kick});
 3007:     delete($accessed{$to_kick});
 3008:     $kicks++;
 3009:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3010:     return;
 3011: }
 3012: 
 3013: sub purge_remembered {
 3014:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3015:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3016:     undef(%remembered);
 3017:     undef(%accessed);
 3018: }
 3019: # ------------------------------------- Read an entry from a user's environment
 3020: 
 3021: sub userenvironment {
 3022:     my ($udom,$unam,@what)=@_;
 3023:     my $items;
 3024:     foreach my $item (@what) {
 3025:         $items.=&escape($item).'&';
 3026:     }
 3027:     $items=~s/\&$//;
 3028:     my %returnhash=();
 3029:     my $uhome = &homeserver($unam,$udom);
 3030:     unless ($uhome eq 'no_host') {
 3031:         my @answer=split(/\&/, 
 3032:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3033:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3034:             return %returnhash;
 3035:         }
 3036:         my $i;
 3037:         for ($i=0;$i<=$#what;$i++) {
 3038: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3039:         }
 3040:     }
 3041:     return %returnhash;
 3042: }
 3043: 
 3044: # ---------------------------------------------------------- Get a studentphoto
 3045: sub studentphoto {
 3046:     my ($udom,$unam,$ext) = @_;
 3047:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3048:     if (defined($env{'request.course.id'})) {
 3049:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3050:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3051:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3052:             } else {
 3053:                 my ($result,$perm_reqd)=
 3054: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3055:                 if ($result eq 'ok') {
 3056:                     if (!($perm_reqd eq 'yes')) {
 3057:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3058:                     }
 3059:                 }
 3060:             }
 3061:         }
 3062:     } else {
 3063:         my ($result,$perm_reqd) = 
 3064: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3065:         if ($result eq 'ok') {
 3066:             if (!($perm_reqd eq 'yes')) {
 3067:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3068:             }
 3069:         }
 3070:     }
 3071:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3072: }
 3073: 
 3074: sub retrievestudentphoto {
 3075:     my ($udom,$unam,$ext,$type) = @_;
 3076:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3077:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3078:     if ($ret eq 'ok') {
 3079:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3080:         if ($type eq 'thumbnail') {
 3081:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3082:         }
 3083:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3084:         return $tokenurl;
 3085:     } else {
 3086:         if ($type eq 'thumbnail') {
 3087:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3088:         } else { 
 3089:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3090:         }
 3091:     }
 3092: }
 3093: 
 3094: # -------------------------------------------------------------------- New chat
 3095: 
 3096: sub chatsend {
 3097:     my ($newentry,$anon,$group)=@_;
 3098:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3099:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3100:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3101:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3102: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3103: 		   &escape($newentry)).':'.$group,$chome);
 3104: }
 3105: 
 3106: # ------------------------------------------ Find current version of a resource
 3107: 
 3108: sub getversion {
 3109:     my $fname=&clutter(shift);
 3110:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3111:     return &currentversion(&filelocation('',$fname));
 3112: }
 3113: 
 3114: sub currentversion {
 3115:     my $fname=shift;
 3116:     my $author=$fname;
 3117:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3118:     my ($udom,$uname)=split(/\//,$author);
 3119:     my $home=&homeserver($uname,$udom);
 3120:     if ($home eq 'no_host') { 
 3121:         return -1; 
 3122:     }
 3123:     my $answer=&reply("currentversion:$fname",$home);
 3124:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3125: 	return -1;
 3126:     }
 3127:     return $answer;
 3128: }
 3129: 
 3130: #
 3131: # Return special version number of resource if set by override, empty otherwise
 3132: #
 3133: sub usedversion {
 3134:     my $fname=shift;
 3135:     unless ($fname) { $fname=$env{'request.uri'}; }
 3136:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3137:     if ($urlversion) { return $urlversion; }
 3138:     return '';
 3139: }
 3140: 
 3141: # ----------------------------- Subscribe to a resource, return URL if possible
 3142: 
 3143: sub subscribe {
 3144:     my $fname=shift;
 3145:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3146:     $fname=~s/[\n\r]//g;
 3147:     my $author=$fname;
 3148:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3149:     my ($udom,$uname)=split(/\//,$author);
 3150:     my $home=homeserver($uname,$udom);
 3151:     if ($home eq 'no_host') {
 3152:         return 'not_found';
 3153:     }
 3154:     my $answer=reply("sub:$fname",$home);
 3155:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3156: 	$answer.=' by '.$home;
 3157:     }
 3158:     return $answer;
 3159: }
 3160:     
 3161: # -------------------------------------------------------------- Replicate file
 3162: 
 3163: sub repcopy {
 3164:     my $filename=shift;
 3165:     $filename=~s/\/+/\//g;
 3166:     my $londocroot = $perlvar{'lonDocRoot'};
 3167:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3168:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3169:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3170: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3171: 	return &repcopy_userfile($filename);
 3172:     }
 3173:     $filename=~s/[\n\r]//g;
 3174:     my $transname="$filename.in.transfer";
 3175: # FIXME: this should flock
 3176:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3177:     my $remoteurl=subscribe($filename);
 3178:     if ($remoteurl =~ /^con_lost by/) {
 3179: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3180:            return 'unavailable';
 3181:     } elsif ($remoteurl eq 'not_found') {
 3182: 	   #&logthis("Subscribe returned not_found: $filename");
 3183: 	   return 'not_found';
 3184:     } elsif ($remoteurl =~ /^rejected by/) {
 3185: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3186:            return 'forbidden';
 3187:     } elsif ($remoteurl eq 'directory') {
 3188:            return 'ok';
 3189:     } else {
 3190:         my $author=$filename;
 3191:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3192:         my ($udom,$uname)=split(/\//,$author);
 3193:         my $home=homeserver($uname,$udom);
 3194:         unless ($home eq $perlvar{'lonHostID'}) {
 3195:            my @parts=split(/\//,$filename);
 3196:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3197:            if ($path ne "$londocroot/res") {
 3198:                &logthis("Malconfiguration for replication: $filename");
 3199: 	       return 'bad_request';
 3200:            }
 3201:            my $count;
 3202:            for ($count=5;$count<$#parts;$count++) {
 3203:                $path.="/$parts[$count]";
 3204:                if ((-e $path)!=1) {
 3205: 		   mkdir($path,0777);
 3206:                }
 3207:            }
 3208:            my $request=new HTTP::Request('GET',"$remoteurl");
 3209:            my $response;
 3210:            if ($remoteurl =~ m{/raw/}) {
 3211:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3212:            } else {
 3213:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3214:            }
 3215:            if ($response->is_error()) {
 3216: 	       unlink($transname);
 3217:                my $message=$response->status_line;
 3218:                &logthis("<font color=\"blue\">WARNING:"
 3219:                        ." LWP get: $message: $filename</font>");
 3220:                return 'unavailable';
 3221:            } else {
 3222: 	       if ($remoteurl!~/\.meta$/) {
 3223:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3224:                   my $mresponse;
 3225:                   if ($remoteurl =~ m{/raw/}) {
 3226:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3227:                   } else {
 3228:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3229:                   }
 3230:                   if ($mresponse->is_error()) {
 3231: 		      unlink($filename.'.meta');
 3232:                       &logthis(
 3233:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3234:                   }
 3235: 	       }
 3236:                rename($transname,$filename);
 3237:                return 'ok';
 3238:            }
 3239:        }
 3240:     }
 3241: }
 3242: 
 3243: # ------------------------------------------------ Get server side include body
 3244: sub ssi_body {
 3245:     my ($filelink,%form)=@_;
 3246:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3247:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3248:     }
 3249:     my $output='';
 3250:     my $response;
 3251:     if ($filelink=~/^https?\:/) {
 3252:        ($output,$response)=&externalssi($filelink);
 3253:     } else {
 3254:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3255:        $filelink .= 'inhibitmenu=yes';
 3256:        ($output,$response)=&ssi($filelink,%form);
 3257:     }
 3258:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3259:     $output=~s/^.*?\<body[^\>]*\>//si;
 3260:     $output=~s/\<\/body\s*\>.*?$//si;
 3261:     if (wantarray) {
 3262:         return ($output, $response);
 3263:     } else {
 3264:         return $output;
 3265:     }
 3266: }
 3267: 
 3268: # --------------------------------------------------------- Server Side Include
 3269: 
 3270: sub absolute_url {
 3271:     my ($host_name) = @_;
 3272:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3273:     if ($host_name eq '') {
 3274: 	$host_name = $ENV{'SERVER_NAME'};
 3275:     }
 3276:     return $protocol.$host_name;
 3277: }
 3278: 
 3279: #
 3280: #   Server side include.
 3281: # Parameters:
 3282: #  fn     Possibly encrypted resource name/id.
 3283: #  form   Hash that describes how the rendering should be done
 3284: #         and other things.
 3285: # Returns:
 3286: #   Scalar context: The content of the response.
 3287: #   Array context:  2 element list of the content and the full response object.
 3288: #     
 3289: sub ssi {
 3290: 
 3291:     my ($fn,%form)=@_;
 3292:     my $request;
 3293: 
 3294:     $form{'no_update_last_known'}=1;
 3295:     &Apache::lonenc::check_encrypt(\$fn);
 3296:     if (%form) {
 3297:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3298:       $request->content(join('&',map { 
 3299:             my $name = escape($_);
 3300:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3301:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3302:             : &escape($form{$_}) );    
 3303:         } keys(%form)));
 3304:     } else {
 3305:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3306:     }
 3307: 
 3308:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3309:     my $lonhost = $perlvar{'lonHostID'};
 3310:     my $islocal;
 3311:     if (($env{'request.course.id'}) &&
 3312:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3313:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3314:         ($form{'grade_symb'} ne '') &&
 3315:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3316:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3317:         $islocal = 1;
 3318:     }
 3319:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3320:                                                 '','','',$islocal);
 3321: 
 3322:     if (wantarray) {
 3323: 	return ($response->content, $response);
 3324:     } else {
 3325: 	return $response->content;
 3326:     }
 3327: }
 3328: 
 3329: sub externalssi {
 3330:     my ($url)=@_;
 3331:     my $request=new HTTP::Request('GET',$url);
 3332:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3333:     if (wantarray) {
 3334:         return ($response->content, $response);
 3335:     } else {
 3336:         return $response->content;
 3337:     }
 3338: }
 3339: 
 3340: 
 3341: # If the local copy of a replicated resource is outdated, trigger a  
 3342: # connection from the homeserver to flush the delayed queue. If no update 
 3343: # happens, remove local copies of outdated resource (and corresponding
 3344: # metadata file).
 3345: 
 3346: sub remove_stale_resfile {
 3347:     my ($url) = @_;
 3348:     my $removed;
 3349:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3350:         my $audom = $1;
 3351:         my $auname = $2;
 3352:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3353:             my $homeserver = &homeserver($auname,$audom);
 3354:             unless (($homeserver eq 'no_host') ||
 3355:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3356:                 my $fname = &filelocation('',$url);
 3357:                 if (-e $fname) {
 3358:                     my $protocol = $protocol{$homeserver};
 3359:                     $protocol = 'http' if ($protocol ne 'https');
 3360:                     my $hostname = &hostname($homeserver);
 3361:                     if ($hostname) {
 3362:                         my $uri = &declutter($url);
 3363:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3364:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3365:                         if ($response->is_success()) {
 3366:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3367:                             my $locmodtime = (stat($fname))[9];
 3368:                             if ($locmodtime < $remmodtime) {
 3369:                                 my $stale;
 3370:                                 my $answer = &reply('pong',$homeserver);
 3371:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3372:                                     sleep(0.2);
 3373:                                     $locmodtime = (stat($fname))[9];
 3374:                                     if ($locmodtime < $remmodtime) {
 3375:                                         my $posstransfer = $fname.'.in.transfer';
 3376:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3377:                                             $removed = 1;
 3378:                                         } else {
 3379:                                             $stale = 1;
 3380:                                         }
 3381:                                     } else {
 3382:                                         $removed = 1;
 3383:                                     }
 3384:                                 } else {
 3385:                                     $stale = 1;
 3386:                                 }
 3387:                                 if ($stale) {
 3388:                                     unlink($fname);
 3389:                                     if ($uri!~/\.meta$/) {
 3390:                                         unlink($fname.'.meta');
 3391:                                     }
 3392:                                     &reply("unsub:$fname",$homeserver);
 3393:                                     $removed = 1;
 3394:                                 }
 3395:                             }
 3396:                         }
 3397:                     }
 3398:                 }
 3399:             }
 3400:         }
 3401:     }
 3402:     return $removed;
 3403: }
 3404: 
 3405: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3406: 
 3407: sub allowuploaded {
 3408:     my ($srcurl,$url)=@_;
 3409:     $url=&clutter(&declutter($url));
 3410:     my $dir=$url;
 3411:     $dir=~s/\/[^\/]+$//;
 3412:     my %httpref=();
 3413:     my $httpurl=&hreflocation('',$url);
 3414:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3415:     &Apache::lonnet::appenv(\%httpref);
 3416: }
 3417: 
 3418: #
 3419: # Determine if the current user should be able to edit a particular resource,
 3420: # when viewing in course context.
 3421: # (a) When viewing resource used to determine if "Edit" item is included in 
 3422: #     Functions.
 3423: # (b) When displaying folder contents in course editor, used to determine if
 3424: #     "Edit" link will be displayed alongside resource.
 3425: #
 3426: #  input: six args -- filename (decluttered), course number, course domain,
 3427: #                   url, symb (if registered) and group (if this is a group
 3428: #                   item -- e.g., bulletin board, group page etc.).
 3429: #  output: array of five scalars -- 
 3430: #          $cfile -- url for file editing if editable on current server
 3431: #          $home -- homeserver of resource (i.e., for author if published,
 3432: #                                           or course if uploaded.).
 3433: #          $switchserver --  1 if server switch will be needed.
 3434: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3435: #          $forceview -- 1 if icon/link should be to go to view mode
 3436: #
 3437: 
 3438: sub can_edit_resource {
 3439:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3440:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3441: #
 3442: # For aboutme pages user can only edit his/her own.
 3443: #
 3444:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3445:         my ($sdom,$sname) = ($1,$2);
 3446:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3447:             $home = $env{'user.home'};
 3448:             $cfile = $resurl;
 3449:             if ($env{'form.forceedit'}) {
 3450:                 $forceview = 1;
 3451:             } else {
 3452:                 $forceedit = 1;
 3453:             }
 3454:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3455:         } else {
 3456:             return;
 3457:         }
 3458:     }
 3459: 
 3460:     if ($env{'request.course.id'}) {
 3461:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3462:         if ($group ne '') {
 3463: # if this is a group homepage or group bulletin board, check group privs
 3464:             my $allowed = 0;
 3465:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3466:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3467:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3468:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3469:                     $allowed = 1;
 3470:                 }
 3471:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3472:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3473:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3474:                     $allowed = 1;
 3475:                 }
 3476:             }
 3477:             if ($allowed) {
 3478:                 $home=&homeserver($cnum,$cdom);
 3479:                 if ($env{'form.forceedit'}) {
 3480:                     $forceview = 1;
 3481:                 } else {
 3482:                     $forceedit = 1;
 3483:                 }
 3484:                 $cfile = $resurl;
 3485:             } else {
 3486:                 return;
 3487:             }
 3488:         } else {
 3489:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3490:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3491:                     return;
 3492:                 }
 3493:             } elsif (!$crsedit) {
 3494: #
 3495: # No edit allowed where CC has switched to student role.
 3496: #
 3497:                 return;
 3498:             }
 3499:         }
 3500:     }
 3501: 
 3502:     if ($file ne '') {
 3503:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3504:             if (&is_course_upload($file,$cnum,$cdom)) {
 3505:                 $uploaded = 1;
 3506:                 $incourse = 1;
 3507:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3508:                     $cfile = &hreflocation('',$file);
 3509:                     if ($env{'form.forceedit'}) {
 3510:                         $forceview = 1;
 3511:                     } else {
 3512:                         $forceedit = 1;
 3513:                     }
 3514:                 }
 3515:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3516:                 $incourse = 1;
 3517:                 if ($env{'form.forceedit'}) {
 3518:                     $forceview = 1;
 3519:                 } else {
 3520:                     $forceedit = 1;
 3521:                 }
 3522:                 $cfile = $resurl;
 3523:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3524:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3525:                     $incourse = 1;
 3526:                     if ($env{'form.forceedit'}) {
 3527:                         $forceview = 1;
 3528:                     } else {
 3529:                         $forceedit = 1;
 3530:                     }
 3531:                     $cfile = $resurl;
 3532:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3533:                     $incourse = 1;
 3534:                     $cfile = $resurl.'/smpedit';
 3535:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3536:                     $incourse = 1;
 3537:                     if ($env{'form.forceedit'}) {
 3538:                         $forceview = 1;
 3539:                     } else {
 3540:                         $forceedit = 1;
 3541:                     }
 3542:                     $cfile = $resurl;
 3543:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3544:                     $incourse = 1;
 3545:                     if ($env{'form.forceedit'}) {
 3546:                         $forceview = 1;
 3547:                     } else {
 3548:                         $forceedit = 1;
 3549:                     }
 3550:                     $cfile = $resurl;
 3551:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3552:                     $incourse = 1;
 3553:                     if ($env{'form.forceedit'}) {
 3554:                         $forceview = 1;
 3555:                     } else {
 3556:                         $forceedit = 1;
 3557:                     }
 3558:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3559:                 }
 3560:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3561:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3562:                 if (&is_on_map($template)) { 
 3563:                     $incourse = 1;
 3564:                     $forceview = 1;
 3565:                     $cfile = $template;
 3566:                 }
 3567:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3568:                     $incourse = 1;
 3569:                     if ($env{'form.forceedit'}) {
 3570:                         $forceview = 1;
 3571:                     } else {
 3572:                         $forceedit = 1;
 3573:                     }
 3574:                     $cfile = $resurl;
 3575:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3576:                 $incourse = 1;
 3577:                 if ($env{'form.forceedit'}) {
 3578:                     $forceview = 1;
 3579:                 } else {
 3580:                     $forceedit = 1;
 3581:                 }
 3582:                 $cfile = $resurl;
 3583:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3584:                 $incourse = 1;
 3585:                 $forceview = 1;
 3586:                 if ($symb) {
 3587:                     my ($map,$id,$res)=&decode_symb($symb);
 3588:                     $env{'request.symb'} = $symb;
 3589:                     $cfile = &clutter($res);
 3590:                 } else {
 3591:                     $cfile = $env{'form.suppurl'};
 3592:                     my $escfile = &unescape($cfile);
 3593:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3594:                         $cfile = '/adm/wrapper'.$escfile;
 3595:                     } else {
 3596:                         $escfile =~ s{^http://}{};
 3597:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3598:                     }
 3599:                 }
 3600:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3601:                 if ($env{'form.forceedit'}) {
 3602:                     $forceview = 1;
 3603:                 } else {
 3604:                     $forceedit = 1;
 3605:                 }
 3606:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3607:             }
 3608:         }
 3609:         if ($uploaded || $incourse) {
 3610:             $home=&homeserver($cnum,$cdom);
 3611:         } elsif ($file !~ m{/$}) {
 3612:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3613:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3614:             # Check that the user has permission to edit this resource
 3615:             my $setpriv = 1;
 3616:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3617:             if (defined($cfudom)) {
 3618:                 $home=&homeserver($cfuname,$cfudom);
 3619:                 $cfile=$file;
 3620:             }
 3621:         }
 3622:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3623:             (($home ne '') && ($home ne 'no_host'))) {
 3624:             my @ids=&current_machine_ids();
 3625:             unless (grep(/^\Q$home\E$/,@ids)) {
 3626:                 $switchserver=1;
 3627:             }
 3628:         }
 3629:     }
 3630:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3631: }
 3632: 
 3633: sub is_course_upload {
 3634:     my ($file,$cnum,$cdom) = @_;
 3635:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3636:     $uploadpath =~ s{^\/}{};
 3637:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3638:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3639:         return 1;
 3640:     }
 3641:     return;
 3642: }
 3643: 
 3644: sub in_course {
 3645:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3646:     if ($hideprivileged) {
 3647:         my $skipuser;
 3648:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3649:         my @possdoms = ($cdom);  
 3650:         if ($coursehash{'checkforpriv'}) { 
 3651:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3652:         }
 3653:         if (&privileged($uname,$udom,\@possdoms)) {
 3654:             $skipuser = 1;
 3655:             if ($coursehash{'nothideprivileged'}) {
 3656:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3657:                     my $user;
 3658:                     if ($item =~ /:/) {
 3659:                         $user = $item;
 3660:                     } else {
 3661:                         $user = join(':',split(/[\@]/,$item));
 3662:                     }
 3663:                     if ($user eq $uname.':'.$udom) {
 3664:                         undef($skipuser);
 3665:                         last;
 3666:                     }
 3667:                 }
 3668:             }
 3669:             if ($skipuser) {
 3670:                 return 0;
 3671:             }
 3672:         }
 3673:     }
 3674:     $type ||= 'any';
 3675:     if (!defined($cdom) || !defined($cnum)) {
 3676:         my $cid  = $env{'request.course.id'};
 3677:         $cdom = $env{'course.'.$cid.'.domain'};
 3678:         $cnum = $env{'course.'.$cid.'.num'};
 3679:     }
 3680:     my $typesref;
 3681:     if (($type eq 'any') || ($type eq 'all')) {
 3682:         $typesref = ['active','previous','future'];
 3683:     } elsif ($type eq 'previous' || $type eq 'future') {
 3684:         $typesref = [$type];
 3685:     }
 3686:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3687:                               $typesref,undef,[$cdom]);
 3688:     my ($tmp) = keys(%roles);
 3689:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3690:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3691:     if (@course_roles > 0) {
 3692:         return 1;
 3693:     }
 3694:     return 0;
 3695: }
 3696: 
 3697: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3698: # input: action, courseID, current domain, intended
 3699: #        path to file, source of file, instruction to parse file for objects,
 3700: #        ref to hash for embedded objects,
 3701: #        ref to hash for codebase of java objects.
 3702: #        reference to scalar to accommodate mime type determined
 3703: #          from File::MMagic if $parser = parse.
 3704: #
 3705: # output: url to file (if action was uploaddoc), 
 3706: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3707: #
 3708: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3709: # course.
 3710: #
 3711: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3712: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3713: #          course's home server.
 3714: #
 3715: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3716: #          be copied from $source (current location) to 
 3717: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3718: #         and will then be copied to
 3719: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3720: #         course's home server.
 3721: #
 3722: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3723: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3724: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3725: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3726: #         in course's home server.
 3727: #
 3728: 
 3729: sub process_coursefile {
 3730:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3731:         $mimetype)=@_;
 3732:     my $fetchresult;
 3733:     my $home=&homeserver($docuname,$docudom);
 3734:     if ($action eq 'propagate') {
 3735:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3736: 			     $home);
 3737:     } else {
 3738:         my $fpath = '';
 3739:         my $fname = $file;
 3740:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3741:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3742:         my $filepath = &build_filepath($fpath);
 3743:         if ($action eq 'copy') {
 3744:             if ($source eq '') {
 3745:                 $fetchresult = 'no source file';
 3746:                 return $fetchresult;
 3747:             } else {
 3748:                 my $destination = $filepath.'/'.$fname;
 3749:                 rename($source,$destination);
 3750:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3751:                                  $home);
 3752:             }
 3753:         } elsif ($action eq 'uploaddoc') {
 3754:             open(my $fh,'>',$filepath.'/'.$fname);
 3755:             print $fh $env{'form.'.$source};
 3756:             close($fh);
 3757:             if ($parser eq 'parse') {
 3758:                 my $mm = new File::MMagic;
 3759:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3760:                 if ($type eq 'text/html') {
 3761:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3762:                     unless ($parse_result eq 'ok') {
 3763:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3764:                     }
 3765:                 }
 3766:                 if (ref($mimetype)) {
 3767:                     $$mimetype = $type;
 3768:                 } 
 3769:             }
 3770:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3771:                                  $home);
 3772:             if ($fetchresult eq 'ok') {
 3773:                 return '/uploaded/'.$fpath.'/'.$fname;
 3774:             } else {
 3775:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3776:                         ' to host '.$home.': '.$fetchresult);
 3777:                 return '/adm/notfound.html';
 3778:             }
 3779:         }
 3780:     }
 3781:     unless ( $fetchresult eq 'ok') {
 3782:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3783:              ' to host '.$home.': '.$fetchresult);
 3784:     }
 3785:     return $fetchresult;
 3786: }
 3787: 
 3788: sub build_filepath {
 3789:     my ($fpath) = @_;
 3790:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3791:     unless ($fpath eq '') {
 3792:         my @parts=split('/',$fpath);
 3793:         foreach my $part (@parts) {
 3794:             $filepath.= '/'.$part;
 3795:             if ((-e $filepath)!=1) {
 3796:                 mkdir($filepath,0777);
 3797:             }
 3798:         }
 3799:     }
 3800:     return $filepath;
 3801: }
 3802: 
 3803: sub store_edited_file {
 3804:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3805:     my $file = $primary_url;
 3806:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3807:     my $fpath = '';
 3808:     my $fname = $file;
 3809:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3810:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3811:     my $filepath = &build_filepath($fpath);
 3812:     open(my $fh,'>',$filepath.'/'.$fname);
 3813:     print $fh $content;
 3814:     close($fh);
 3815:     my $home=&homeserver($docuname,$docudom);
 3816:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3817: 			  $home);
 3818:     if ($$fetchresult eq 'ok') {
 3819:         return '/uploaded/'.$fpath.'/'.$fname;
 3820:     } else {
 3821:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3822: 		 ' to host '.$home.': '.$$fetchresult);
 3823:         return '/adm/notfound.html';
 3824:     }
 3825: }
 3826: 
 3827: sub clean_filename {
 3828:     my ($fname,$args)=@_;
 3829: # Replace Windows backslashes by forward slashes
 3830:     $fname=~s/\\/\//g;
 3831:     if (!$args->{'keep_path'}) {
 3832:         # Get rid of everything but the actual filename
 3833: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3834:     }
 3835: # Replace spaces by underscores
 3836:     $fname=~s/\s+/\_/g;
 3837: # Replace all other weird characters by nothing
 3838:     $fname=~s{[^/\w\.\-]}{}g;
 3839: # Replace all .\d. sequences with _\d. so they no longer look like version
 3840: # numbers
 3841:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3842:     return $fname;
 3843: }
 3844: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3845: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3846: # image with the same aspect ratio as the original, but with dimensions which do 
 3847: # not exceed $resizewidth and $resizeheight.
 3848:  
 3849: sub resizeImage {
 3850:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3851:     my $ima = Image::Magick->new;
 3852:     my $resized;
 3853:     if (-e $img_path) {
 3854:         $ima->Read($img_path);
 3855:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3856:             my $width = $ima->Get('width');
 3857:             my $height = $ima->Get('height');
 3858:             if ($width > $resizewidth) {
 3859: 	        my $factor = $width/$resizewidth;
 3860:                 my $newheight = $height/$factor;
 3861:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3862:                 $resized = 1;
 3863:             }
 3864:         }
 3865:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3866:             my $width = $ima->Get('width');
 3867:             my $height = $ima->Get('height');
 3868:             if ($height > $resizeheight) {
 3869:                 my $factor = $height/$resizeheight;
 3870:                 my $newwidth = $width/$factor;
 3871:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3872:                 $resized = 1;
 3873:             }
 3874:         }
 3875:         if ($resized) {
 3876:             $ima->Write($img_path);
 3877:         }
 3878:     }
 3879:     return;
 3880: }
 3881: 
 3882: # --------------- Take an uploaded file and put it into the userfiles directory
 3883: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3884: #                    the desired filename is in $env{"form.$formname.filename"}
 3885: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3886: #                                    canceloverwrite, or ''. 
 3887: #                   if 'coursedoc': upload to the current course
 3888: #                   if 'existingfile': write file to tmp/overwrites directory 
 3889: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3890: #                   $context is passed as argument to &finishuserfileupload
 3891: #        $subdir - directory in userfile to store the file into
 3892: #        $parser - instruction to parse file for objects ($parser = parse)    
 3893: #        $allfiles - reference to hash for embedded objects
 3894: #        $codebase - reference to hash for codebase of java objects
 3895: #        $desuname - username for permanent storage of uploaded file
 3896: #        $dsetudom - domain for permanaent storage of uploaded file
 3897: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3898: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3899: #        $resizewidth - width (pixels) to which to resize uploaded image
 3900: #        $resizeheight - height (pixels) to which to resize uploaded image
 3901: #        $mimetype - reference to scalar to accommodate mime type determined
 3902: #                    from File::MMagic.
 3903: # 
 3904: # output: url of file in userspace, or error: <message> 
 3905: #             or /adm/notfound.html if failure to upload occurse
 3906: 
 3907: sub userfileupload {
 3908:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3909:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3910:     if (!defined($subdir)) { $subdir='unknown'; }
 3911:     my $fname=$env{'form.'.$formname.'.filename'};
 3912:     $fname=&clean_filename($fname);
 3913:     # See if there is anything left
 3914:     unless ($fname) { return 'error: no uploaded file'; }
 3915:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3916:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3917:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3918:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3919:         my $now = time;
 3920:         my $filepath;
 3921:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3922:              $filepath = 'tmp/helprequests/'.$now;
 3923:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3924:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3925:                          '_'.$env{'user.domain'}.'/pending';
 3926:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3927:             my ($docuname,$docudom);
 3928:             if ($destudom =~ /^$match_domain$/) {
 3929:                 $docudom = $destudom;
 3930:             } else {
 3931:                 $docudom = $env{'user.domain'};
 3932:             }
 3933:             if ($destuname =~ /^$match_username$/) {
 3934:                 $docuname = $destuname;
 3935:             } else {
 3936:                 $docuname = $env{'user.name'};
 3937:             }
 3938:             if (exists($env{'form.group'})) {
 3939:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3940:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3941:             }
 3942:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3943:             if ($context eq 'canceloverwrite') {
 3944:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3945:                 if (-e  $tempfile) {
 3946:                     my @info = stat($tempfile);
 3947:                     if ($info[9] eq $env{'form.timestamp'}) {
 3948:                         unlink($tempfile);
 3949:                     }
 3950:                 }
 3951:                 return;
 3952:             }
 3953:         }
 3954:         # Create the directory if not present
 3955:         my @parts=split(/\//,$filepath);
 3956:         my $fullpath = $perlvar{'lonDaemons'};
 3957:         for (my $i=0;$i<@parts;$i++) {
 3958:             $fullpath .= '/'.$parts[$i];
 3959:             if ((-e $fullpath)!=1) {
 3960:                 mkdir($fullpath,0777);
 3961:             }
 3962:         }
 3963:         open(my $fh,'>',$fullpath.'/'.$fname);
 3964:         print $fh $env{'form.'.$formname};
 3965:         close($fh);
 3966:         if ($context eq 'existingfile') {
 3967:             my @info = stat($fullpath.'/'.$fname);
 3968:             return ($fullpath.'/'.$fname,$info[9]);
 3969:         } else {
 3970:             return $fullpath.'/'.$fname;
 3971:         }
 3972:     }
 3973:     if ($subdir eq 'scantron') {
 3974:         $fname = 'scantron_orig_'.$fname;
 3975:     } else {
 3976:         $fname="$subdir/$fname";
 3977:     }
 3978:     if ($context eq 'coursedoc') {
 3979: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3980: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3981:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3982:             return &finishuserfileupload($docuname,$docudom,
 3983: 					 $formname,$fname,$parser,$allfiles,
 3984: 					 $codebase,$thumbwidth,$thumbheight,
 3985:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3986:         } else {
 3987:             if ($env{'form.folder'}) {
 3988:                 $fname=$env{'form.folder'}.'/'.$fname;
 3989:             }
 3990:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3991: 				       $fname,$formname,$parser,
 3992: 				       $allfiles,$codebase,$mimetype);
 3993:         }
 3994:     } elsif (defined($destuname)) {
 3995:         my $docuname=$destuname;
 3996:         my $docudom=$destudom;
 3997: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3998: 				     $parser,$allfiles,$codebase,
 3999:                                      $thumbwidth,$thumbheight,
 4000:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4001:     } else {
 4002:         my $docuname=$env{'user.name'};
 4003:         my $docudom=$env{'user.domain'};
 4004:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4005:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4006:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4007:         }
 4008: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4009: 				     $parser,$allfiles,$codebase,
 4010:                                      $thumbwidth,$thumbheight,
 4011:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4012:     }
 4013: }
 4014: 
 4015: sub finishuserfileupload {
 4016:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4017:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4018:     my $path=$docudom.'/'.$docuname.'/';
 4019:     my $filepath=$perlvar{'lonDocRoot'};
 4020:   
 4021:     my ($fnamepath,$file,$fetchthumb);
 4022:     $file=$fname;
 4023:     if ($fname=~m|/|) {
 4024:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4025: 	$path.=$fnamepath.'/';
 4026:     }
 4027:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4028:     my $count;
 4029:     for ($count=4;$count<=$#parts;$count++) {
 4030:         $filepath.="/$parts[$count]";
 4031:         if ((-e $filepath)!=1) {
 4032: 	    mkdir($filepath,0777);
 4033:         }
 4034:     }
 4035: 
 4036: # Save the file
 4037:     {
 4038: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4039: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4040: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4041: 	    return '/adm/notfound.html';
 4042: 	}
 4043:         if ($context eq 'overwrite') {
 4044:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4045:             my $target = $filepath.'/'.$file;
 4046:             if (-e $source) {
 4047:                 my @info = stat($source);
 4048:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4049:                     unless (&File::Copy::move($source,$target)) {
 4050:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4051:                         return "Moving from $source failed";
 4052:                     }
 4053:                 } else {
 4054:                     return "Temporary file: $source had unexpected date/time for last modification";
 4055:                 }
 4056:             } else {
 4057:                 return "Temporary file: $source missing";
 4058:             }
 4059:         } elsif (!print FH ($env{'form.'.$formname})) {
 4060: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4061: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4062: 	    return '/adm/notfound.html';
 4063: 	}
 4064: 	close(FH);
 4065:         if ($resizewidth && $resizeheight) {
 4066:             my $mm = new File::MMagic;
 4067:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4068:             if ($mime_type =~ m{^image/}) {
 4069: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4070:             }  
 4071: 	}
 4072:     }
 4073:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4074:         if (ref($mimetype)) {
 4075:             if ($$mimetype eq '') {
 4076:                 my $mm = new File::MMagic;
 4077:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4078:                 $$mimetype = $type;
 4079:             }
 4080:         }
 4081:     }
 4082:     if ($parser eq 'parse') {
 4083:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4084:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4085:                                                        $allfiles,$codebase);
 4086:             unless ($parse_result eq 'ok') {
 4087:                 &logthis('Failed to parse '.$filepath.$file.
 4088: 	   	         ' for embedded media: '.$parse_result); 
 4089:             }
 4090:         }
 4091:     }
 4092:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4093:         my $input = $filepath.'/'.$file;
 4094:         my $output = $filepath.'/'.'tn-'.$file;
 4095:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4096:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4097:         system({$args[0]} @args);
 4098:         if (-e $filepath.'/'.'tn-'.$file) {
 4099:             $fetchthumb  = 1; 
 4100:         }
 4101:     }
 4102:  
 4103: # Notify homeserver to grep it
 4104: #
 4105:     my $docuhome=&homeserver($docuname,$docudom);	
 4106:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4107:     if ($fetchresult eq 'ok') {
 4108:         if ($fetchthumb) {
 4109:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4110:             if ($thumbresult ne 'ok') {
 4111:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4112:                          $docuhome.': '.$thumbresult);
 4113:             }
 4114:         }
 4115: #
 4116: # Return the URL to it
 4117:         return '/uploaded/'.$path.$file;
 4118:     } else {
 4119:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4120: 		 ': '.$fetchresult);
 4121:         return '/adm/notfound.html';
 4122:     }
 4123: }
 4124: 
 4125: sub extract_embedded_items {
 4126:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4127:     my @state = ();
 4128:     my (%lastids,%related,%shockwave,%flashvars);
 4129:     my %javafiles = (
 4130:                       codebase => '',
 4131:                       code => '',
 4132:                       archive => ''
 4133:                     );
 4134:     my %mediafiles = (
 4135:                       src => '',
 4136:                       movie => '',
 4137:                      );
 4138:     my $p;
 4139:     if ($content) {
 4140:         $p = HTML::LCParser->new($content);
 4141:     } else {
 4142:         $p = HTML::LCParser->new($fullpath);
 4143:     }
 4144:     while (my $t=$p->get_token()) {
 4145: 	if ($t->[0] eq 'S') {
 4146: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4147: 	    push(@state, $tagname);
 4148:             if (lc($tagname) eq 'allow') {
 4149:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4150:             }
 4151: 	    if (lc($tagname) eq 'img') {
 4152: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4153: 	    }
 4154: 	    if (lc($tagname) eq 'a') {
 4155:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4156:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4157:                 }
 4158: 	    }
 4159:             if (lc($tagname) eq 'script') {
 4160:                 my $src;
 4161:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4162:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4163:                 } else {
 4164:                     if ($attr->{'src'} ne '') {
 4165:                         $src = $attr->{'src'};
 4166:                         &add_filetype($allfiles,$src,'src');
 4167:                     }
 4168:                 }
 4169:                 my $text = $p->get_trimmed_text();
 4170:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4171:                     my @swfargs = split(/,/,$1);
 4172:                     foreach my $item (@swfargs) {
 4173:                         $item =~ s/["']//g;
 4174:                         $item =~ s/^\s+//;
 4175:                         $item =~ s/\s+$//;
 4176:                     }
 4177:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4178:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4179:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4180:                         } else {
 4181:                             $related{$swfargs[0]} = [$swfargs[2]];
 4182:                         }
 4183:                     }
 4184:                 }
 4185:             }
 4186:             if (lc($tagname) eq 'link') {
 4187:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4188:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4189:                 }
 4190:             }
 4191: 	    if (lc($tagname) eq 'object' ||
 4192: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4193: 		foreach my $item (keys(%javafiles)) {
 4194: 		    $javafiles{$item} = '';
 4195: 		}
 4196:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4197:                     $lastids{lc($tagname)} = $attr->{'id'};
 4198:                 }
 4199: 	    }
 4200: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4201: 		my $name = lc($attr->{'name'});
 4202: 		foreach my $item (keys(%javafiles)) {
 4203: 		    if ($name eq $item) {
 4204: 			$javafiles{$item} = $attr->{'value'};
 4205: 			last;
 4206: 		    }
 4207: 		}
 4208:                 my $pathfrom;
 4209: 		foreach my $item (keys(%mediafiles)) {
 4210: 		    if ($name eq $item) {
 4211:                         $pathfrom = $attr->{'value'};
 4212:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4213: 			&add_filetype($allfiles,$pathfrom,$name);
 4214: 			last;
 4215: 		    }
 4216: 		}
 4217:                 if ($name eq 'flashvars') {
 4218:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4219:                 }
 4220:                 if ($pathfrom ne '') {
 4221:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4222:                                          $pathfrom);
 4223:                 }
 4224: 	    }
 4225: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4226: 		foreach my $item (keys(%javafiles)) {
 4227: 		    if ($attr->{$item}) {
 4228: 			$javafiles{$item} = $attr->{$item};
 4229: 			last;
 4230: 		    }
 4231: 		}
 4232: 		foreach my $item (keys(%mediafiles)) {
 4233: 		    if ($attr->{$item}) {
 4234: 			&add_filetype($allfiles,$attr->{$item},$item);
 4235: 			last;
 4236: 		    }
 4237: 		}
 4238:                 if (lc($tagname) eq 'embed') {
 4239:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4240:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4241:                                              $attr->{'src'});
 4242:                     }
 4243:                 }
 4244: 	    }
 4245:             if (lc($tagname) eq 'iframe') {
 4246:                 my $src = $attr->{'src'} ;
 4247:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4248:                     &add_filetype($allfiles,$src,'src');
 4249:                 } elsif ($src =~ m{^/}) {
 4250:                     if ($env{'request.course.id'}) {
 4251:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4252:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4253:                         my $url = &hreflocation('',$fullpath);
 4254:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4255:                             my $relpath = $1;
 4256:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4257:                                 &add_filetype($allfiles,$1,'src');
 4258:                             }
 4259:                         }
 4260:                     }
 4261:                 }
 4262:             }
 4263:             if ($t->[4] =~ m{/>$}) {
 4264:                 pop(@state);
 4265:             }
 4266: 	} elsif ($t->[0] eq 'E') {
 4267: 	    my ($tagname) = ($t->[1]);
 4268: 	    if ($javafiles{'codebase'} ne '') {
 4269: 		$javafiles{'codebase'} .= '/';
 4270: 	    }  
 4271: 	    if (lc($tagname) eq 'applet' ||
 4272: 		lc($tagname) eq 'object' ||
 4273: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4274: 		) {
 4275: 		foreach my $item (keys(%javafiles)) {
 4276: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4277: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4278: 			&add_filetype($allfiles,$file,$item);
 4279: 		    }
 4280: 		}
 4281: 	    } 
 4282: 	    pop @state;
 4283: 	}
 4284:     }
 4285:     foreach my $id (sort(keys(%flashvars))) {
 4286:         if ($shockwave{$id} ne '') {
 4287:             my @pairs = split(/\&/,$flashvars{$id});
 4288:             foreach my $pair (@pairs) {
 4289:                 my ($key,$value) = split(/\=/,$pair);
 4290:                 if ($key eq 'thumb') {
 4291:                     &add_filetype($allfiles,$value,$key);
 4292:                 } elsif ($key eq 'content') {
 4293:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4294:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4295:                     if ($ext ne '') {
 4296:                         &add_filetype($allfiles,$path.$value,$ext);
 4297:                     }
 4298:                 }
 4299:             }
 4300:         }
 4301:     }
 4302:     return 'ok';
 4303: }
 4304: 
 4305: sub add_filetype {
 4306:     my ($allfiles,$file,$type)=@_;
 4307:     if (exists($allfiles->{$file})) {
 4308: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4309: 	    push(@{$allfiles->{$file}}, &escape($type));
 4310: 	}
 4311:     } else {
 4312: 	@{$allfiles->{$file}} = (&escape($type));
 4313:     }
 4314: }
 4315: 
 4316: sub embedded_dependency {
 4317:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4318:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4319:         if (($identifier ne '') &&
 4320:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4321:             ($pathfrom ne '')) {
 4322:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4323:             foreach my $dep (@{$related->{$identifier}}) {
 4324:                 &add_filetype($allfiles,$path.$dep,'object');
 4325:             }
 4326:         }
 4327:     }
 4328:     return;
 4329: }
 4330: 
 4331: sub removeuploadedurl {
 4332:     my ($url)=@_;	
 4333:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4334:     return &removeuserfile($uname,$udom,$fname);
 4335: }
 4336: 
 4337: sub removeuserfile {
 4338:     my ($docuname,$docudom,$fname)=@_;
 4339:     my $home=&homeserver($docuname,$docudom);    
 4340:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4341:     if ($result eq 'ok') {	
 4342:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4343:             my $metafile = $fname.'.meta';
 4344:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4345: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4346:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4347:             my $sqlresult = 
 4348:                 &update_portfolio_table($docuname,$docudom,$file,
 4349:                                         'portfolio_metadata',$group,
 4350:                                         'delete');
 4351:         }
 4352:     }
 4353:     return $result;
 4354: }
 4355: 
 4356: sub mkdiruserfile {
 4357:     my ($docuname,$docudom,$dir)=@_;
 4358:     my $home=&homeserver($docuname,$docudom);
 4359:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4360: }
 4361: 
 4362: sub renameuserfile {
 4363:     my ($docuname,$docudom,$old,$new)=@_;
 4364:     my $home=&homeserver($docuname,$docudom);
 4365:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4366:                         &escape("$old").':'.&escape("$new"),$home);
 4367:     if ($result eq 'ok') {
 4368:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4369:             my $oldmeta = $old.'.meta';
 4370:             my $newmeta = $new.'.meta';
 4371:             my $metaresult = 
 4372:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4373: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4374:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4375:             my $sqlresult = 
 4376:                 &update_portfolio_table($docuname,$docudom,$file,
 4377:                                         'portfolio_metadata',$group,
 4378:                                         'delete');
 4379:         }
 4380:     }
 4381:     return $result;
 4382: }
 4383: 
 4384: # ------------------------------------------------------------------------- Log
 4385: 
 4386: sub log {
 4387:     my ($dom,$nam,$hom,$what)=@_;
 4388:     return critical("log:$dom:$nam:$what",$hom);
 4389: }
 4390: 
 4391: # ------------------------------------------------------------------ Course Log
 4392: #
 4393: # This routine flushes several buffers of non-mission-critical nature
 4394: #
 4395: 
 4396: sub flushcourselogs {
 4397:     &logthis('Flushing log buffers');
 4398: #
 4399: # course logs
 4400: # This is a log of all transactions in a course, which can be used
 4401: # for data mining purposes
 4402: #
 4403: # It also collects the courseid database, which lists last transaction
 4404: # times and course titles for all courseids
 4405: #
 4406:     my %courseidbuffer=();
 4407:     foreach my $crsid (keys(%courselogs)) {
 4408:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4409: 		          &escape($courselogs{$crsid}),
 4410: 		          $coursehombuf{$crsid}) eq 'ok') {
 4411: 	    delete $courselogs{$crsid};
 4412:         } else {
 4413:             &logthis('Failed to flush log buffer for '.$crsid);
 4414:             if (length($courselogs{$crsid})>40000) {
 4415:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4416:                         " exceeded maximum size, deleting.</font>");
 4417:                delete $courselogs{$crsid};
 4418:             }
 4419:         }
 4420:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4421:             'description' => $coursedescrbuf{$crsid},
 4422:             'inst_code'    => $courseinstcodebuf{$crsid},
 4423:             'type'        => $coursetypebuf{$crsid},
 4424:             'owner'       => $courseownerbuf{$crsid},
 4425:         };
 4426:     }
 4427: #
 4428: # Write course id database (reverse lookup) to homeserver of courses 
 4429: # Is used in pickcourse
 4430: #
 4431:     foreach my $crs_home (keys(%courseidbuffer)) {
 4432:         my $response = &courseidput(&host_domain($crs_home),
 4433:                                     $courseidbuffer{$crs_home},
 4434:                                     $crs_home,'timeonly');
 4435:     }
 4436: #
 4437: # File accesses
 4438: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4439: #
 4440:     foreach my $entry (keys(%accesshash)) {
 4441:         if ($entry =~ /___count$/) {
 4442:             my ($dom,$name);
 4443:             ($dom,$name,undef)=
 4444: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4445:             if (! defined($dom) || $dom eq '' || 
 4446:                 ! defined($name) || $name eq '') {
 4447:                 my $cid = $env{'request.course.id'};
 4448:                 $dom  = $env{'request.'.$cid.'.domain'};
 4449:                 $name = $env{'request.'.$cid.'.num'};
 4450:             }
 4451:             my $value = $accesshash{$entry};
 4452:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4453:             my %temphash=($url => $value);
 4454:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4455:             if ($result eq 'ok') {
 4456:                 delete $accesshash{$entry};
 4457:             }
 4458:         } else {
 4459:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4460:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4461:             my %temphash=($entry => $accesshash{$entry});
 4462:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4463:                 delete $accesshash{$entry};
 4464:             }
 4465:         }
 4466:     }
 4467: #
 4468: # Roles
 4469: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4470: #
 4471:     foreach my $entry (keys(%userrolehash)) {
 4472:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4473: 	    split(/\:/,$entry);
 4474:         if (&Apache::lonnet::put('nohist_userroles',
 4475:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4476:                 $rudom,$runame) eq 'ok') {
 4477: 	    delete $userrolehash{$entry};
 4478:         }
 4479:     }
 4480: #
 4481: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4482: #
 4483:     my %domrolebuffer = ();
 4484:     foreach my $entry (keys(%domainrolehash)) {
 4485:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4486:         if ($domrolebuffer{$rudom}) {
 4487:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4488:                       '='.&escape($domainrolehash{$entry});
 4489:         } else {
 4490:             $domrolebuffer{$rudom}.=&escape($entry).
 4491:                       '='.&escape($domainrolehash{$entry});
 4492:         }
 4493:         delete $domainrolehash{$entry};
 4494:     }
 4495:     foreach my $dom (keys(%domrolebuffer)) {
 4496: 	my %servers;
 4497: 	if (defined(&domain($dom,'primary'))) {
 4498: 	    my $primary=&domain($dom,'primary');
 4499: 	    my $hostname=&hostname($primary);
 4500: 	    $servers{$primary} = $hostname;
 4501: 	} else { 
 4502: 	    %servers = &get_servers($dom,'library');
 4503: 	}
 4504: 	foreach my $tryserver (keys(%servers)) {
 4505: 	    if (&reply('domroleput:'.$dom.':'.
 4506: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4507: 		last;
 4508: 	    } else {  
 4509: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4510: 	    }
 4511:         }
 4512:     }
 4513:     $dumpcount++;
 4514: }
 4515: 
 4516: sub courselog {
 4517:     my $what=shift;
 4518:     $what=time.':'.$what;
 4519:     unless ($env{'request.course.id'}) { return ''; }
 4520:     $coursedombuf{$env{'request.course.id'}}=
 4521:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4522:     $coursenumbuf{$env{'request.course.id'}}=
 4523:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4524:     $coursehombuf{$env{'request.course.id'}}=
 4525:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4526:     $coursedescrbuf{$env{'request.course.id'}}=
 4527:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4528:     $courseinstcodebuf{$env{'request.course.id'}}=
 4529:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4530:     $courseownerbuf{$env{'request.course.id'}}=
 4531:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4532:     $coursetypebuf{$env{'request.course.id'}}=
 4533:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4534:     if (defined $courselogs{$env{'request.course.id'}}) {
 4535: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4536:     } else {
 4537: 	$courselogs{$env{'request.course.id'}}.=$what;
 4538:     }
 4539:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4540: 	&flushcourselogs();
 4541:     }
 4542: }
 4543: 
 4544: sub courseacclog {
 4545:     my $fnsymb=shift;
 4546:     unless ($env{'request.course.id'}) { return ''; }
 4547:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4548:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4549:         $what.=':POST';
 4550:         # FIXME: Probably ought to escape things....
 4551: 	foreach my $key (keys(%env)) {
 4552:             if ($key=~/^form\.(.*)/) {
 4553:                 my $formitem = $1;
 4554:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4555:                     $what.=':'.$formitem.'='.$env{$key};
 4556:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4557:                     $what.=':'.$formitem.'='.$env{$key};
 4558:                 }
 4559:             }
 4560:         }
 4561:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4562:         # FIXME: We should not be depending on a form parameter that someone
 4563:         # editing lonsearchcat.pm might change in the future.
 4564:         if ($env{'form.phase'} eq 'course_search') {
 4565:             $what.= ':POST';
 4566:             # FIXME: Probably ought to escape things....
 4567:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4568:                                  'crsdiscuss') {
 4569:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4570:             }
 4571:         }
 4572:     }
 4573:     &courselog($what);
 4574: }
 4575: 
 4576: sub countacc {
 4577:     my $url=&declutter(shift);
 4578:     return if (! defined($url) || $url eq '');
 4579:     unless ($env{'request.course.id'}) { return ''; }
 4580: #
 4581: # Mark that this url was used in this course
 4582: #
 4583:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4584: #
 4585: # Increase the access count for this resource in this child process
 4586: #
 4587:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4588:     $accesshash{$key}++;
 4589: }
 4590: 
 4591: sub linklog {
 4592:     my ($from,$to)=@_;
 4593:     $from=&declutter($from);
 4594:     $to=&declutter($to);
 4595:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4596:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4597: }
 4598: 
 4599: sub statslog {
 4600:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4601:     if ($users<2) { return; }
 4602:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4603:             'course'       => $env{'request.course.id'},
 4604:             'sections'     => '"all"',
 4605:             'num_students' => $users,
 4606:             'part'         => $part,
 4607:             'symb'         => $symb,
 4608:             'mean_tries'   => $av_attempts,
 4609:             'deg_of_diff'  => $degdiff});
 4610:     foreach my $key (keys(%dynstore)) {
 4611:         $accesshash{$key}=$dynstore{$key};
 4612:     }
 4613: }
 4614:   
 4615: sub userrolelog {
 4616:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4617:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4618:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4619:        $userrolehash
 4620:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4621:                     =$tend.':'.$tstart;
 4622:     }
 4623:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4624:        $userrolehash
 4625:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4626:                     =$tend.':'.$tstart;
 4627:     }
 4628:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4629:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4630:        $domainrolehash
 4631:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4632:                     = $tend.':'.$tstart;
 4633:     }
 4634: }
 4635: 
 4636: sub courserolelog {
 4637:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4638:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4639:         my $cdom = $1;
 4640:         my $cnum = $2;
 4641:         my $sec = $3;
 4642:         my $namespace = 'rolelog';
 4643:         my %storehash = (
 4644:                            role    => $trole,
 4645:                            start   => $tstart,
 4646:                            end     => $tend,
 4647:                            selfenroll => $selfenroll,
 4648:                            context    => $context,
 4649:                         );
 4650:         if ($trole eq 'gr') {
 4651:             $namespace = 'groupslog';
 4652:             $storehash{'group'} = $sec;
 4653:         } else {
 4654:             $storehash{'section'} = $sec;
 4655:         }
 4656:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4657:                    $domain,$cnum,$cdom);
 4658:         if (($trole ne 'st') || ($sec ne '')) {
 4659:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4660:         }
 4661:     }
 4662:     return;
 4663: }
 4664: 
 4665: sub domainrolelog {
 4666:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4667:     if ($area =~ m{^/($match_domain)/$}) {
 4668:         my $cdom = $1;
 4669:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4670:         my $namespace = 'rolelog';
 4671:         my %storehash = (
 4672:                            role    => $trole,
 4673:                            start   => $tstart,
 4674:                            end     => $tend,
 4675:                            context => $context,
 4676:                         );
 4677:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4678:                    $domain,$domconfiguser,$cdom);
 4679:     }
 4680:     return;
 4681: 
 4682: }
 4683: 
 4684: sub coauthorrolelog {
 4685:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4686:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4687:         my $audom = $1;
 4688:         my $auname = $2;
 4689:         my $namespace = 'rolelog';
 4690:         my %storehash = (
 4691:                            role    => $trole,
 4692:                            start   => $tstart,
 4693:                            end     => $tend,
 4694:                            context => $context,
 4695:                         );
 4696:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4697:                    $domain,$auname,$audom);
 4698:     }
 4699:     return;
 4700: }
 4701: 
 4702: sub get_course_adv_roles {
 4703:     my ($cid,$codes) = @_;
 4704:     $cid=$env{'request.course.id'} unless (defined($cid));
 4705:     my %coursehash=&coursedescription($cid);
 4706:     my $crstype = &Apache::loncommon::course_type($cid);
 4707:     my %nothide=();
 4708:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4709:         if ($user !~ /:/) {
 4710: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4711:         } else {
 4712:             $nothide{$user}=1;
 4713:         }
 4714:     }
 4715:     my @possdoms = ($coursehash{'domain'});
 4716:     if ($coursehash{'checkforpriv'}) {
 4717:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4718:     }
 4719:     my %returnhash=();
 4720:     my %dumphash=
 4721:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4722:     my $now=time;
 4723:     my %privileged;
 4724:     foreach my $entry (keys(%dumphash)) {
 4725: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4726:         if (($tstart) && ($tstart<0)) { next; }
 4727:         if (($tend) && ($tend<$now)) { next; }
 4728:         if (($tstart) && ($now<$tstart)) { next; }
 4729:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4730: 	if ($username eq '' || $domain eq '') { next; }
 4731:         if ((&privileged($username,$domain,\@possdoms)) &&
 4732:             (!$nothide{$username.':'.$domain})) { next; }
 4733: 	if ($role eq 'cr') { next; }
 4734:         if ($codes) {
 4735:             if ($section) { $role .= ':'.$section; }
 4736:             if ($returnhash{$role}) {
 4737:                 $returnhash{$role}.=','.$username.':'.$domain;
 4738:             } else {
 4739:                 $returnhash{$role}=$username.':'.$domain;
 4740:             }
 4741:         } else {
 4742:             my $key=&plaintext($role,$crstype);
 4743:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4744:             if ($returnhash{$key}) {
 4745: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4746:             } else {
 4747:                 $returnhash{$key}=$username.':'.$domain;
 4748:             }
 4749:         }
 4750:     }
 4751:     return %returnhash;
 4752: }
 4753: 
 4754: sub get_my_roles {
 4755:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4756:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4757:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4758:     my (%dumphash,%nothide);
 4759:     if ($context eq 'userroles') {
 4760:         %dumphash = &dump('roles',$udom,$uname);
 4761:     } else {
 4762:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4763:         if ($hidepriv) {
 4764:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4765:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4766:                 if ($user !~ /:/) {
 4767:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4768:                 } else {
 4769:                     $nothide{$user} = 1;
 4770:                 }
 4771:             }
 4772:         }
 4773:     }
 4774:     my %returnhash=();
 4775:     my $now=time;
 4776:     my %privileged;
 4777:     foreach my $entry (keys(%dumphash)) {
 4778:         my ($role,$tend,$tstart);
 4779:         if ($context eq 'userroles') {
 4780:             next if ($entry =~ /^rolesdef/);
 4781: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4782:         } else {
 4783:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4784:         }
 4785:         if (($tstart) && ($tstart<0)) { next; }
 4786:         my $status = 'active';
 4787:         if (($tend) && ($tend<=$now)) {
 4788:             $status = 'previous';
 4789:         } 
 4790:         if (($tstart) && ($now<$tstart)) {
 4791:             $status = 'future';
 4792:         }
 4793:         if (ref($types) eq 'ARRAY') {
 4794:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4795:                 next;
 4796:             } 
 4797:         } else {
 4798:             if ($status ne 'active') {
 4799:                 next;
 4800:             }
 4801:         }
 4802:         my ($rolecode,$username,$domain,$section,$area);
 4803:         if ($context eq 'userroles') {
 4804:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4805:             (undef,$domain,$username,$section) = split(/\//,$area);
 4806:         } else {
 4807:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4808:         }
 4809:         if (ref($roledoms) eq 'ARRAY') {
 4810:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4811:                 next;
 4812:             }
 4813:         }
 4814:         if (ref($roles) eq 'ARRAY') {
 4815:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4816:                 if ($role =~ /^cr\//) {
 4817:                     if (!grep(/^cr$/,@{$roles})) {
 4818:                         next;
 4819:                     }
 4820:                 } elsif ($role =~ /^gr\//) {
 4821:                     if (!grep(/^gr$/,@{$roles})) {
 4822:                         next;
 4823:                     }
 4824:                 } else {
 4825:                     next;
 4826:                 }
 4827:             }
 4828:         }
 4829:         if ($hidepriv) {
 4830:             my @privroles = ('dc','su');
 4831:             if ($context eq 'userroles') {
 4832:                 next if (grep(/^\Q$role\E$/,@privroles));
 4833:             } else {
 4834:                 my $possdoms = [$domain];
 4835:                 if (ref($roledoms) eq 'ARRAY') {
 4836:                    push(@{$possdoms},@{$roledoms}); 
 4837:                 }
 4838:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4839:                     if (!$nothide{$username.':'.$domain}) {
 4840:                         next;
 4841:                     }
 4842:                 }
 4843:             }
 4844:         }
 4845:         if ($withsec) {
 4846:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4847:                 $tstart.':'.$tend;
 4848:         } else {
 4849:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4850:         }
 4851:     }
 4852:     return %returnhash;
 4853: }
 4854: 
 4855: sub get_all_adhocroles {
 4856:     my ($dom) = @_;
 4857:     my @roles_by_num = ();
 4858:     my %domdefaults = &get_domain_defaults($dom);
 4859:     my (%description,%access_in_dom,%access_info);
 4860:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4861:         my $count = 0;
 4862:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4863:         my %ordered;
 4864:         foreach my $role (sort(keys(%domcurrent))) {
 4865:             my ($order,$desc,$access_in_dom);
 4866:             if (ref($domcurrent{$role}) eq 'HASH') {
 4867:                 $order = $domcurrent{$role}{'order'};
 4868:                 $desc = $domcurrent{$role}{'desc'};
 4869:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4870:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4871:             }
 4872:             if ($order eq '') {
 4873:                 $order = $count;
 4874:             }
 4875:             $ordered{$order} = $role;
 4876:             if ($desc ne '') {
 4877:                 $description{$role} = $desc;
 4878:             } else {
 4879:                 $description{$role}= $role;
 4880:             }
 4881:             $count++;
 4882:         }
 4883:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4884:             push(@roles_by_num,$ordered{$item});
 4885:         }
 4886:     }
 4887:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4888: }
 4889: 
 4890: sub get_my_adhocroles {
 4891:     my ($cid,$checkreg) = @_;
 4892:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4893:     if ($env{'request.course.id'} eq $cid) {
 4894:         $cdom = $env{'course.'.$cid.'.domain'};
 4895:         $cnum = $env{'course.'.$cid.'.num'};
 4896:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4897:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4898:         $cdom = $1;
 4899:         $cnum = $2;
 4900:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4901:                                      $cdom,$cnum);
 4902:     }
 4903:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4904:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4905:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4906:         if ($rosterhash{$user} ne '') {
 4907:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4908:             return ([],{}) if ($type eq 'auto');
 4909:         }
 4910:     }
 4911:     if (($cdom ne '') && ($cnum ne ''))  {
 4912:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4913:             my $then=$env{'user.login.time'};
 4914:             my $update=$env{'user.update.time'};
 4915:             if (!$update) {
 4916:                 $update = $then;
 4917:             }
 4918:             my @liveroles;
 4919:             foreach my $role ('dh','da') {
 4920:                 if ($env{"user.role.$role./$cdom/"}) {
 4921:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4922:                     my $limit = $update;
 4923:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4924:                         $limit = $then;
 4925:                     }
 4926:                     my $activerole = 1;
 4927:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4928:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4929:                     if ($activerole) {
 4930:                         push(@liveroles,$role);
 4931:                     }
 4932:                 }
 4933:             }
 4934:             if (@liveroles) {
 4935:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4936:                     my ($accessref,$accessinfo,%access_in_dom);
 4937:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4938:                     if (ref($roles_by_num) eq 'ARRAY') {
 4939:                         if (@{$roles_by_num}) {
 4940:                             my %settings;
 4941:                             if ($env{'request.course.id'} eq $cid) {
 4942:                                 foreach my $envkey (keys(%env)) {
 4943:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4944:                                         $settings{$1} = $env{$envkey};
 4945:                                     }
 4946:                                 }
 4947:                             } else {
 4948:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4949:                             }
 4950:                             my %setincrs;
 4951:                             if ($settings{'internal.adhocaccess'}) {
 4952:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4953:                             }
 4954:                             my @statuses;
 4955:                             if ($env{'environment.inststatus'}) {
 4956:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4957:                             }
 4958:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4959:                             if (ref($accessref) eq 'HASH') {
 4960:                                 %access_in_dom = %{$accessref};
 4961:                             }
 4962:                             foreach my $role (@{$roles_by_num}) {
 4963:                                 my ($curraccess,@okstatus,@personnel);
 4964:                                 if ($setincrs{$role}) {
 4965:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4966:                                     if ($curraccess eq 'status') {
 4967:                                         @okstatus = split(/\&/,$rest);
 4968:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4969:                                         @personnel = split(/\&/,$rest);
 4970:                                     }
 4971:                                 } else {
 4972:                                     $curraccess = $access_in_dom{$role};
 4973:                                     if (ref($accessinfo) eq 'HASH') {
 4974:                                         if ($curraccess eq 'status') {
 4975:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4976:                                                 @okstatus = @{$accessinfo->{$role}};
 4977:                                             }
 4978:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4979:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4980:                                                 @personnel = @{$accessinfo->{$role}};
 4981:                                             }
 4982:                                         }
 4983:                                     }
 4984:                                 }
 4985:                                 if ($curraccess eq 'none') {
 4986:                                     next;
 4987:                                 } elsif ($curraccess eq 'all') {
 4988:                                     push(@possroles,$role);
 4989:                                 } elsif ($curraccess eq 'dh') {
 4990:                                     if (grep(/^dh$/,@liveroles)) {
 4991:                                         push(@possroles,$role);
 4992:                                     } else {
 4993:                                         next;
 4994:                                     }
 4995:                                 } elsif ($curraccess eq 'da') {
 4996:                                     if (grep(/^da$/,@liveroles)) {
 4997:                                         push(@possroles,$role);
 4998:                                     } else {
 4999:                                         next;
 5000:                                     }
 5001:                                 } elsif ($curraccess eq 'status') {
 5002:                                     if (@okstatus) {
 5003:                                         if (!@statuses) {
 5004:                                             if (grep(/^default$/,@okstatus)) {
 5005:                                                 push(@possroles,$role);
 5006:                                             }
 5007:                                         } else {
 5008:                                             foreach my $status (@okstatus) {
 5009:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5010:                                                     push(@possroles,$role);
 5011:                                                     last;
 5012:                                                 }
 5013:                                             }
 5014:                                         }
 5015:                                     }
 5016:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5017:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5018:                                         if ($curraccess eq 'exc') {
 5019:                                             push(@possroles,$role);
 5020:                                         }
 5021:                                     } elsif ($curraccess eq 'inc') {
 5022:                                         push(@possroles,$role);
 5023:                                     }
 5024:                                 }
 5025:                             }
 5026:                         }
 5027:                     }
 5028:                 }
 5029:             }
 5030:         }
 5031:     }
 5032:     unless (ref($description) eq 'HASH') {
 5033:         if (ref($roles_by_num) eq 'ARRAY') {
 5034:             my %desc;
 5035:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5036:             $description = \%desc;
 5037:         } else {
 5038:             $description = {};
 5039:         }
 5040:     }
 5041:     return (\@possroles,$description);
 5042: }
 5043: 
 5044: # ----------------------------------------------------- Frontpage Announcements
 5045: #
 5046: #
 5047: 
 5048: sub postannounce {
 5049:     my ($server,$text)=@_;
 5050:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5051:     unless ($text=~/\w/) { $text=''; }
 5052:     return &reply('setannounce:'.&escape($text),$server);
 5053: }
 5054: 
 5055: sub getannounce {
 5056: 
 5057:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5058: 	my $announcement='';
 5059: 	while (my $line = <$fh>) { $announcement .= $line; }
 5060: 	close($fh);
 5061: 	if ($announcement=~/\w/) { 
 5062: 	    return 
 5063:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5064:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5065: 	} else {
 5066: 	    return '';
 5067: 	}
 5068:     } else {
 5069: 	return '';
 5070:     }
 5071: }
 5072: 
 5073: # ---------------------------------------------------------- Course ID routines
 5074: # Deal with domain's nohist_courseid.db files
 5075: #
 5076: 
 5077: sub courseidput {
 5078:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5079:     return unless (ref($storehash) eq 'HASH');
 5080:     my $outcome;
 5081:     if ($caller eq 'timeonly') {
 5082:         my $cids = '';
 5083:         foreach my $item (keys(%$storehash)) {
 5084:             $cids.=&escape($item).'&';
 5085:         }
 5086:         $cids=~s/\&$//;
 5087:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5088:                           $coursehome);       
 5089:     } else {
 5090:         my $items = '';
 5091:         foreach my $item (keys(%$storehash)) {
 5092:             $items.= &escape($item).'='.
 5093:                      &freeze_escape($$storehash{$item}).'&';
 5094:         }
 5095:         $items=~s/\&$//;
 5096:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5097:                           $coursehome);
 5098:     }
 5099:     if ($outcome eq 'unknown_cmd') {
 5100:         my $what;
 5101:         foreach my $cid (keys(%$storehash)) {
 5102:             $what .= &escape($cid).'=';
 5103:             foreach my $item ('description','inst_code','owner','type') {
 5104:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5105:             }
 5106:             $what =~ s/\:$/&/;
 5107:         }
 5108:         $what =~ s/\&$//;  
 5109:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5110:     } else {
 5111:         return $outcome;
 5112:     }
 5113: }
 5114: 
 5115: sub courseiddump {
 5116:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5117:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5118:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5119:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5120:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5121:     my $as_hash = 1;
 5122:     my %returnhash;
 5123:     if (!$domfilter) { $domfilter=''; }
 5124:     my %libserv = &all_library();
 5125:     foreach my $tryserver (keys(%libserv)) {
 5126:         if ( (  $hostidflag == 1 
 5127: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5128: 	     || (!defined($hostidflag)) ) {
 5129: 
 5130: 	    if (($domfilter eq '') ||
 5131: 		(&host_domain($tryserver) eq $domfilter)) {
 5132:                 my $rep;
 5133:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5134:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5135:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5136:                                 &escape($descfilter), &escape($instcodefilter), 
 5137:                                 &escape($ownerfilter), &escape($coursefilter),
 5138:                                 &escape($typefilter), &escape($regexp_ok), 
 5139:                                 $as_hash, &escape($selfenrollonly), 
 5140:                                 &escape($catfilter), $showhidden, $caller, 
 5141:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5142:                                 &escape($createdbefore), &escape($createdafter), 
 5143:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5144:                                 $reqcrsdom,&escape($reqinstcode))));
 5145:                 } else {
 5146:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5147:                              $sincefilter.':'.&escape($descfilter).':'.
 5148:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5149:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5150:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5151:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5152:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5153:                              &escape($cc_clone).':'.$cloneonly.':'.
 5154:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5155:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5156:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5157:                 }
 5158:                      
 5159:                 my @pairs=split(/\&/,$rep);
 5160:                 foreach my $item (@pairs) {
 5161:                     my ($key,$value)=split(/\=/,$item,2);
 5162:                     $key = &unescape($key);
 5163:                     next if ($key =~ /^error: 2 /);
 5164:                     my $result = &thaw_unescape($value);
 5165:                     if (ref($result) eq 'HASH') {
 5166:                         $returnhash{$key}=$result;
 5167:                     } else {
 5168:                         my @responses = split(/:/,$value);
 5169:                         my @items = ('description','inst_code','owner','type');
 5170:                         for (my $i=0; $i<@responses; $i++) {
 5171:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5172:                         }
 5173:                     }
 5174:                 }
 5175:             }
 5176:         }
 5177:     }
 5178:     return %returnhash;
 5179: }
 5180: 
 5181: sub courselastaccess {
 5182:     my ($cdom,$cnum,$hostidref) = @_;
 5183:     my %returnhash;
 5184:     if ($cdom && $cnum) {
 5185:         my $chome = &homeserver($cnum,$cdom);
 5186:         if ($chome ne 'no_host') {
 5187:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5188:             &extract_lastaccess(\%returnhash,$rep);
 5189:         }
 5190:     } else {
 5191:         if (!$cdom) { $cdom=''; }
 5192:         my %libserv = &all_library();
 5193:         foreach my $tryserver (keys(%libserv)) {
 5194:             if (ref($hostidref) eq 'ARRAY') {
 5195:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5196:             } 
 5197:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5198:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5199:                 &extract_lastaccess(\%returnhash,$rep);
 5200:             }
 5201:         }
 5202:     }
 5203:     return %returnhash;
 5204: }
 5205: 
 5206: sub extract_lastaccess {
 5207:     my ($returnhash,$rep) = @_;
 5208:     if (ref($returnhash) eq 'HASH') {
 5209:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5210:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5211:                  $rep eq '') {
 5212:             my @pairs=split(/\&/,$rep);
 5213:             foreach my $item (@pairs) {
 5214:                 my ($key,$value)=split(/\=/,$item,2);
 5215:                 $key = &unescape($key);
 5216:                 next if ($key =~ /^error: 2 /);
 5217:                 $returnhash->{$key} = &thaw_unescape($value);
 5218:             }
 5219:         }
 5220:     }
 5221:     return;
 5222: }
 5223: 
 5224: # ---------------------------------------------------------- DC e-mail
 5225: 
 5226: sub dcmailput {
 5227:     my ($domain,$msgid,$message,$server)=@_;
 5228:     my $status = &Apache::lonnet::critical(
 5229:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5230:        &escape($message),$server);
 5231:     return $status;
 5232: }
 5233: 
 5234: sub dcmaildump {
 5235:     my ($dom,$startdate,$enddate,$senders) = @_;
 5236:     my %returnhash=();
 5237: 
 5238:     if (defined(&domain($dom,'primary'))) {
 5239:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5240:                                                          &escape($enddate).':';
 5241: 	my @esc_senders=map { &escape($_)} @$senders;
 5242: 	$cmd.=&escape(join('&',@esc_senders));
 5243: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5244:             my ($key,$value) = split(/\=/,$line,2);
 5245:             if (($key) && ($value)) {
 5246:                 $returnhash{&unescape($key)} = &unescape($value);
 5247:             }
 5248:         }
 5249:     }
 5250:     return %returnhash;
 5251: }
 5252: # ---------------------------------------------------------- Domain roles
 5253: 
 5254: sub get_domain_roles {
 5255:     my ($dom,$roles,$startdate,$enddate)=@_;
 5256:     if ((!defined($startdate)) || ($startdate eq '')) {
 5257:         $startdate = '.';
 5258:     }
 5259:     if ((!defined($enddate)) || ($enddate eq '')) {
 5260:         $enddate = '.';
 5261:     }
 5262:     my $rolelist;
 5263:     if (ref($roles) eq 'ARRAY') {
 5264:         $rolelist = join('&',@{$roles});
 5265:     }
 5266:     my %personnel = ();
 5267: 
 5268:     my %servers = &get_servers($dom,'library');
 5269:     foreach my $tryserver (keys(%servers)) {
 5270: 	%{$personnel{$tryserver}}=();
 5271: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5272: 					    &escape($startdate).':'.
 5273: 					    &escape($enddate).':'.
 5274: 					    &escape($rolelist), $tryserver))) {
 5275: 	    my ($key,$value) = split(/\=/,$line,2);
 5276: 	    if (($key) && ($value)) {
 5277: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5278: 	    }
 5279: 	}
 5280:     }
 5281:     return %personnel;
 5282: }
 5283: 
 5284: sub get_active_domroles {
 5285:     my ($dom,$roles) = @_;
 5286:     return () unless (ref($roles) eq 'ARRAY');
 5287:     my $now = time;
 5288:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5289:     my %domroles;
 5290:     foreach my $server (keys(%dompersonnel)) {
 5291:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5292:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5293:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5294:         }
 5295:     }
 5296:     return %domroles;
 5297: }
 5298: 
 5299: # ----------------------------------------------------------- Interval timing 
 5300: 
 5301: {
 5302: # Caches needed for speedup of navmaps
 5303: # We don't want to cache this for very long at all (5 seconds at most)
 5304: # 
 5305: # The user for whom we cache
 5306: my $cachedkey='';
 5307: # The cached times for this user
 5308: my %cachedtimes=();
 5309: # When this was last done
 5310: my $cachedtime='';
 5311: 
 5312: sub load_all_first_access {
 5313:     my ($uname,$udom,$ignorecache)=@_;
 5314:     if (($cachedkey eq $uname.':'.$udom) &&
 5315:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5316:         (!$ignorecache)) {
 5317:         return;
 5318:     }
 5319:     $cachedtime=time;
 5320:     $cachedkey=$uname.':'.$udom;
 5321:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5322: }
 5323: 
 5324: sub get_first_access {
 5325:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5326:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5327:     if ($argsymb) { $symb=$argsymb; }
 5328:     my ($map,$id,$res)=&decode_symb($symb);
 5329:     if ($argmap) { $map = $argmap; }
 5330:     if ($type eq 'course') {
 5331: 	$res='course';
 5332:     } elsif ($type eq 'map') {
 5333: 	$res=&symbread($map);
 5334:     } else {
 5335: 	$res=$symb;
 5336:     }
 5337:     &load_all_first_access($uname,$udom,$ignorecache);
 5338:     return $cachedtimes{"$courseid\0$res"};
 5339: }
 5340: 
 5341: sub set_first_access {
 5342:     my ($type,$interval)=@_;
 5343:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5344:     my ($map,$id,$res)=&decode_symb($symb);
 5345:     if ($type eq 'course') {
 5346: 	$res='course';
 5347:     } elsif ($type eq 'map') {
 5348: 	$res=&symbread($map);
 5349:     } else {
 5350: 	$res=$symb;
 5351:     }
 5352:     $cachedkey='';
 5353:     my $firstaccess=&get_first_access($type,$symb,$map);
 5354:     if ($firstaccess) {
 5355:         &logthis("First access time already set ($firstaccess) when attempting ".
 5356:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5357:                  "in $courseid");
 5358:         return 'already_set';
 5359:     } else {
 5360:         my $start = time;
 5361: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5362:                           $udom,$uname);
 5363:         if ($putres eq 'ok') {
 5364:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5365:                  $udom,$uname); 
 5366:             &appenv(
 5367:                      {
 5368:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5369:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5370:                      }
 5371:                   );
 5372:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5373:                 $cachedtimes{"$courseid\0$res"} = $start;
 5374:             }
 5375:         } elsif ($putres ne 'refused') {
 5376:             &logthis("Result: $putres when attempting to set first access time ".
 5377:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5378:         }
 5379:         return $putres;
 5380:     }
 5381:     return 'already_set';
 5382: }
 5383: }
 5384: 
 5385: # --------------------------------------------- Set Expire Date for Spreadsheet
 5386: 
 5387: sub expirespread {
 5388:     my ($uname,$udom,$stype,$usymb)=@_;
 5389:     my $cid=$env{'request.course.id'}; 
 5390:     if ($cid) {
 5391:        my $now=time;
 5392:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5393:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5394:                             $env{'course.'.$cid.'.num'}.
 5395: 	        	    ':nohist_expirationdates:'.
 5396:                             &escape($key).'='.$now,
 5397:                             $env{'course.'.$cid.'.home'})
 5398:     }
 5399:     return 'ok';
 5400: }
 5401: 
 5402: # ----------------------------------------------------- Devalidate Spreadsheets
 5403: 
 5404: sub devalidate {
 5405:     my ($symb,$uname,$udom)=@_;
 5406:     my $cid=$env{'request.course.id'}; 
 5407:     if ($cid) {
 5408:         # delete the stored spreadsheets for
 5409:         # - the student level sheet of this user in course's homespace
 5410:         # - the assessment level sheet for this resource 
 5411:         #   for this user in user's homespace
 5412: 	# - current conditional state info
 5413: 	my $key=$uname.':'.$udom.':';
 5414:         my $status=
 5415: 	    &del('nohist_calculatedsheets',
 5416: 		 [$key.'studentcalc:'],
 5417: 		 $env{'course.'.$cid.'.domain'},
 5418: 		 $env{'course.'.$cid.'.num'})
 5419: 		.' '.
 5420: 	    &del('nohist_calculatedsheets_'.$cid,
 5421: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5422:         unless ($status eq 'ok ok') {
 5423:            &logthis('Could not devalidate spreadsheet '.
 5424:                     $uname.' at '.$udom.' for '.
 5425: 		    $symb.': '.$status);
 5426:         }
 5427: 	&delenv('user.state.'.$cid);
 5428:     }
 5429: }
 5430: 
 5431: sub get_scalar {
 5432:     my ($string,$end) = @_;
 5433:     my $value;
 5434:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5435: 	$value = $1;
 5436:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5437: 	$value = $1;
 5438:     }
 5439:     return &unescape($value);
 5440: }
 5441: 
 5442: sub array2str {
 5443:   my (@array) = @_;
 5444:   my $result=&arrayref2str(\@array);
 5445:   $result=~s/^__ARRAY_REF__//;
 5446:   $result=~s/__END_ARRAY_REF__$//;
 5447:   return $result;
 5448: }
 5449: 
 5450: sub arrayref2str {
 5451:   my ($arrayref) = @_;
 5452:   my $result='__ARRAY_REF__';
 5453:   foreach my $elem (@$arrayref) {
 5454:     if(ref($elem) eq 'ARRAY') {
 5455:       $result.=&arrayref2str($elem).'&';
 5456:     } elsif(ref($elem) eq 'HASH') {
 5457:       $result.=&hashref2str($elem).'&';
 5458:     } elsif(ref($elem)) {
 5459:       #print("Got a ref of ".(ref($elem))." skipping.");
 5460:     } else {
 5461:       $result.=&escape($elem).'&';
 5462:     }
 5463:   }
 5464:   $result=~s/\&$//;
 5465:   $result .= '__END_ARRAY_REF__';
 5466:   return $result;
 5467: }
 5468: 
 5469: sub hash2str {
 5470:   my (%hash) = @_;
 5471:   my $result=&hashref2str(\%hash);
 5472:   $result=~s/^__HASH_REF__//;
 5473:   $result=~s/__END_HASH_REF__$//;
 5474:   return $result;
 5475: }
 5476: 
 5477: sub hashref2str {
 5478:   my ($hashref)=@_;
 5479:   my $result='__HASH_REF__';
 5480:   foreach my $key (sort(keys(%$hashref))) {
 5481:     if (ref($key) eq 'ARRAY') {
 5482:       $result.=&arrayref2str($key).'=';
 5483:     } elsif (ref($key) eq 'HASH') {
 5484:       $result.=&hashref2str($key).'=';
 5485:     } elsif (ref($key)) {
 5486:       $result.='=';
 5487:       #print("Got a ref of ".(ref($key))." skipping.");
 5488:     } else {
 5489: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5490:     }
 5491: 
 5492:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5493:       $result.=&arrayref2str($hashref->{$key}).'&';
 5494:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5495:       $result.=&hashref2str($hashref->{$key}).'&';
 5496:     } elsif(ref($hashref->{$key})) {
 5497:        $result.='&';
 5498:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5499:     } else {
 5500:       $result.=&escape($hashref->{$key}).'&';
 5501:     }
 5502:   }
 5503:   $result=~s/\&$//;
 5504:   $result .= '__END_HASH_REF__';
 5505:   return $result;
 5506: }
 5507: 
 5508: sub str2hash {
 5509:     my ($string)=@_;
 5510:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5511:     return %$hash;
 5512: }
 5513: 
 5514: sub str2hashref {
 5515:   my ($string) = @_;
 5516: 
 5517:   my %hash;
 5518: 
 5519:   if($string !~ /^__HASH_REF__/) {
 5520:       if (! ($string eq '' || !defined($string))) {
 5521: 	  $hash{'error'}='Not hash reference';
 5522:       }
 5523:       return (\%hash, $string);
 5524:   }
 5525: 
 5526:   $string =~ s/^__HASH_REF__//;
 5527: 
 5528:   while($string !~ /^__END_HASH_REF__/) {
 5529:       #key
 5530:       my $key='';
 5531:       if($string =~ /^__HASH_REF__/) {
 5532:           ($key, $string)=&str2hashref($string);
 5533:           if(defined($key->{'error'})) {
 5534:               $hash{'error'}='Bad data';
 5535:               return (\%hash, $string);
 5536:           }
 5537:       } elsif($string =~ /^__ARRAY_REF__/) {
 5538:           ($key, $string)=&str2arrayref($string);
 5539:           if($key->[0] eq 'Array reference error') {
 5540:               $hash{'error'}='Bad data';
 5541:               return (\%hash, $string);
 5542:           }
 5543:       } else {
 5544:           $string =~ s/^(.*?)=//;
 5545: 	  $key=&unescape($1);
 5546:       }
 5547:       $string =~ s/^=//;
 5548: 
 5549:       #value
 5550:       my $value='';
 5551:       if($string =~ /^__HASH_REF__/) {
 5552:           ($value, $string)=&str2hashref($string);
 5553:           if(defined($value->{'error'})) {
 5554:               $hash{'error'}='Bad data';
 5555:               return (\%hash, $string);
 5556:           }
 5557:       } elsif($string =~ /^__ARRAY_REF__/) {
 5558:           ($value, $string)=&str2arrayref($string);
 5559:           if($value->[0] eq 'Array reference error') {
 5560:               $hash{'error'}='Bad data';
 5561:               return (\%hash, $string);
 5562:           }
 5563:       } else {
 5564: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5565:       }
 5566:       $string =~ s/^&//;
 5567: 
 5568:       $hash{$key}=$value;
 5569:   }
 5570: 
 5571:   $string =~ s/^__END_HASH_REF__//;
 5572: 
 5573:   return (\%hash, $string);
 5574: }
 5575: 
 5576: sub str2array {
 5577:     my ($string)=@_;
 5578:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5579:     return @$array;
 5580: }
 5581: 
 5582: sub str2arrayref {
 5583:   my ($string) = @_;
 5584:   my @array;
 5585: 
 5586:   if($string !~ /^__ARRAY_REF__/) {
 5587:       if (! ($string eq '' || !defined($string))) {
 5588: 	  $array[0]='Array reference error';
 5589:       }
 5590:       return (\@array, $string);
 5591:   }
 5592: 
 5593:   $string =~ s/^__ARRAY_REF__//;
 5594: 
 5595:   while($string !~ /^__END_ARRAY_REF__/) {
 5596:       my $value='';
 5597:       if($string =~ /^__HASH_REF__/) {
 5598:           ($value, $string)=&str2hashref($string);
 5599:           if(defined($value->{'error'})) {
 5600:               $array[0] ='Array reference error';
 5601:               return (\@array, $string);
 5602:           }
 5603:       } elsif($string =~ /^__ARRAY_REF__/) {
 5604:           ($value, $string)=&str2arrayref($string);
 5605:           if($value->[0] eq 'Array reference error') {
 5606:               $array[0] ='Array reference error';
 5607:               return (\@array, $string);
 5608:           }
 5609:       } else {
 5610: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5611:       }
 5612:       $string =~ s/^&//;
 5613: 
 5614:       push(@array, $value);
 5615:   }
 5616: 
 5617:   $string =~ s/^__END_ARRAY_REF__//;
 5618: 
 5619:   return (\@array, $string);
 5620: }
 5621: 
 5622: # -------------------------------------------------------------------Temp Store
 5623: 
 5624: sub tmpreset {
 5625:   my ($symb,$namespace,$domain,$stuname) = @_;
 5626:   if (!$symb) {
 5627:     $symb=&symbread();
 5628:     if (!$symb) { $symb= $env{'request.url'}; }
 5629:   }
 5630:   $symb=escape($symb);
 5631: 
 5632:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5633:   $namespace=~s/\//\_/g;
 5634:   $namespace=~s/\W//g;
 5635: 
 5636:   if (!$domain) { $domain=$env{'user.domain'}; }
 5637:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5638:   if ($domain eq 'public' && $stuname eq 'public') {
 5639:       $stuname=$ENV{'REMOTE_ADDR'};
 5640:   }
 5641:   my $path=LONCAPA::tempdir();
 5642:   my %hash;
 5643:   if (tie(%hash,'GDBM_File',
 5644: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5645: 	  &GDBM_WRCREAT(),0640)) {
 5646:     foreach my $key (keys(%hash)) {
 5647:       if ($key=~ /:$symb/) {
 5648: 	delete($hash{$key});
 5649:       }
 5650:     }
 5651:   }
 5652: }
 5653: 
 5654: sub tmpstore {
 5655:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5656: 
 5657:   if (!$symb) {
 5658:     $symb=&symbread();
 5659:     if (!$symb) { $symb= $env{'request.url'}; }
 5660:   }
 5661:   $symb=escape($symb);
 5662: 
 5663:   if (!$namespace) {
 5664:     # I don't think we would ever want to store this for a course.
 5665:     # it seems this will only be used if we don't have a course.
 5666:     #$namespace=$env{'request.course.id'};
 5667:     #if (!$namespace) {
 5668:       $namespace=$env{'request.state'};
 5669:     #}
 5670:   }
 5671:   $namespace=~s/\//\_/g;
 5672:   $namespace=~s/\W//g;
 5673:   if (!$domain) { $domain=$env{'user.domain'}; }
 5674:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5675:   if ($domain eq 'public' && $stuname eq 'public') {
 5676:       $stuname=$ENV{'REMOTE_ADDR'};
 5677:   }
 5678:   my $now=time;
 5679:   my %hash;
 5680:   my $path=LONCAPA::tempdir();
 5681:   if (tie(%hash,'GDBM_File',
 5682: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5683: 	  &GDBM_WRCREAT(),0640)) {
 5684:     $hash{"version:$symb"}++;
 5685:     my $version=$hash{"version:$symb"};
 5686:     my $allkeys=''; 
 5687:     foreach my $key (keys(%$storehash)) {
 5688:       $allkeys.=$key.':';
 5689:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5690:     }
 5691:     $hash{"$version:$symb:timestamp"}=$now;
 5692:     $allkeys.='timestamp';
 5693:     $hash{"$version:keys:$symb"}=$allkeys;
 5694:     if (untie(%hash)) {
 5695:       return 'ok';
 5696:     } else {
 5697:       return "error:$!";
 5698:     }
 5699:   } else {
 5700:     return "error:$!";
 5701:   }
 5702: }
 5703: 
 5704: # -----------------------------------------------------------------Temp Restore
 5705: 
 5706: sub tmprestore {
 5707:   my ($symb,$namespace,$domain,$stuname) = @_;
 5708: 
 5709:   if (!$symb) {
 5710:     $symb=&symbread();
 5711:     if (!$symb) { $symb= $env{'request.url'}; }
 5712:   }
 5713:   $symb=escape($symb);
 5714: 
 5715:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5716: 
 5717:   if (!$domain) { $domain=$env{'user.domain'}; }
 5718:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5719:   if ($domain eq 'public' && $stuname eq 'public') {
 5720:       $stuname=$ENV{'REMOTE_ADDR'};
 5721:   }
 5722:   my %returnhash;
 5723:   $namespace=~s/\//\_/g;
 5724:   $namespace=~s/\W//g;
 5725:   my %hash;
 5726:   my $path=LONCAPA::tempdir();
 5727:   if (tie(%hash,'GDBM_File',
 5728: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5729: 	  &GDBM_READER(),0640)) {
 5730:     my $version=$hash{"version:$symb"};
 5731:     $returnhash{'version'}=$version;
 5732:     my $scope;
 5733:     for ($scope=1;$scope<=$version;$scope++) {
 5734:       my $vkeys=$hash{"$scope:keys:$symb"};
 5735:       my @keys=split(/:/,$vkeys);
 5736:       my $key;
 5737:       $returnhash{"$scope:keys"}=$vkeys;
 5738:       foreach $key (@keys) {
 5739: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5740: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5741:       }
 5742:     }
 5743:     if (!(untie(%hash))) {
 5744:       return "error:$!";
 5745:     }
 5746:   } else {
 5747:     return "error:$!";
 5748:   }
 5749:   return %returnhash;
 5750: }
 5751: 
 5752: # ----------------------------------------------------------------------- Store
 5753: 
 5754: sub store {
 5755:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5756:     my $home='';
 5757: 
 5758:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5759: 
 5760:     $symb=&symbclean($symb);
 5761:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5762: 
 5763:     if (!$domain) { $domain=$env{'user.domain'}; }
 5764:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5765: 
 5766:     &devalidate($symb,$stuname,$domain);
 5767: 
 5768:     $symb=escape($symb);
 5769:     if (!$namespace) { 
 5770:        unless ($namespace=$env{'request.course.id'}) { 
 5771:           return ''; 
 5772:        } 
 5773:     }
 5774:     if (!$home) { $home=$env{'user.home'}; }
 5775: 
 5776:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5777:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5778: 
 5779:     my $namevalue='';
 5780:     foreach my $key (keys(%$storehash)) {
 5781:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5782:     }
 5783:     $namevalue=~s/\&$//;
 5784:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5785:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5786: }
 5787: 
 5788: # -------------------------------------------------------------- Critical Store
 5789: 
 5790: sub cstore {
 5791:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5792:     my $home='';
 5793: 
 5794:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5795: 
 5796:     $symb=&symbclean($symb);
 5797:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5798: 
 5799:     if (!$domain) { $domain=$env{'user.domain'}; }
 5800:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5801: 
 5802:     &devalidate($symb,$stuname,$domain);
 5803: 
 5804:     $symb=escape($symb);
 5805:     if (!$namespace) { 
 5806:        unless ($namespace=$env{'request.course.id'}) { 
 5807:           return ''; 
 5808:        } 
 5809:     }
 5810:     if (!$home) { $home=$env{'user.home'}; }
 5811: 
 5812:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5813:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5814: 
 5815:     my $namevalue='';
 5816:     foreach my $key (keys(%$storehash)) {
 5817:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5818:     }
 5819:     $namevalue=~s/\&$//;
 5820:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5821:     return critical
 5822:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5823: }
 5824: 
 5825: # --------------------------------------------------------------------- Restore
 5826: 
 5827: sub restore {
 5828:     my ($symb,$namespace,$domain,$stuname) = @_;
 5829:     my $home='';
 5830: 
 5831:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5832: 
 5833:     if (!$symb) {
 5834:         return if ($namespace eq 'courserequests');
 5835:         unless ($symb=escape(&symbread())) { return ''; }
 5836:     } else {
 5837:         unless ($namespace eq 'courserequests') {
 5838:             $symb=&escape(&symbclean($symb));
 5839:         }
 5840:     }
 5841:     if (!$namespace) { 
 5842:        unless ($namespace=$env{'request.course.id'}) { 
 5843:           return ''; 
 5844:        } 
 5845:     }
 5846:     if (!$domain) { $domain=$env{'user.domain'}; }
 5847:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5848:     if (!$home) { $home=$env{'user.home'}; }
 5849:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5850: 
 5851:     my %returnhash=();
 5852:     foreach my $line (split(/\&/,$answer)) {
 5853: 	my ($name,$value)=split(/\=/,$line);
 5854:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5855:     }
 5856:     my $version;
 5857:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5858:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5859:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5860:        }
 5861:     }
 5862:     return %returnhash;
 5863: }
 5864: 
 5865: # ---------------------------------------------------------- Course Description
 5866: #
 5867: #  
 5868: 
 5869: sub coursedescription {
 5870:     my ($courseid,$args)=@_;
 5871:     $courseid=~s/^\///;
 5872:     $courseid=~s/\_/\//g;
 5873:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5874:     my $chome=&homeserver($cnum,$cdomain);
 5875:     my $normalid=$cdomain.'_'.$cnum;
 5876:     # need to always cache even if we get errors otherwise we keep 
 5877:     # trying and trying and trying to get the course description.
 5878:     my %envhash=();
 5879:     my %returnhash=();
 5880:     
 5881:     my $expiretime=600;
 5882:     if ($env{'request.course.id'} eq $normalid) {
 5883: 	$expiretime=120;
 5884:     }
 5885: 
 5886:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5887:     if (!$args->{'freshen_cache'}
 5888: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5889: 	foreach my $key (keys(%env)) {
 5890: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5891: 	    my ($setting) = $1;
 5892: 	    $returnhash{$setting} = $env{$key};
 5893: 	}
 5894: 	return %returnhash;
 5895:     }
 5896: 
 5897:     # get the data again
 5898: 
 5899:     if (!$args->{'one_time'}) {
 5900: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5901:     }
 5902: 
 5903:     if ($chome ne 'no_host') {
 5904:        %returnhash=&dump('environment',$cdomain,$cnum);
 5905:        if (!exists($returnhash{'con_lost'})) {
 5906: 	   my $username = $env{'user.name'}; # Defult username
 5907: 	   if(defined $args->{'user'}) {
 5908: 	       $username = $args->{'user'};
 5909: 	   }
 5910:            $returnhash{'home'}= $chome;
 5911: 	   $returnhash{'domain'} = $cdomain;
 5912: 	   $returnhash{'num'} = $cnum;
 5913:            if (!defined($returnhash{'type'})) {
 5914:                $returnhash{'type'} = 'Course';
 5915:            }
 5916:            while (my ($name,$value) = each %returnhash) {
 5917:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5918:            }
 5919:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5920:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5921: 	       $username.'_'.$cdomain.'_'.$cnum;
 5922:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5923:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5924:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5925:        }
 5926:     }
 5927:     if (!$args->{'one_time'}) {
 5928: 	&appenv(\%envhash);
 5929:     }
 5930:     return %returnhash;
 5931: }
 5932: 
 5933: sub update_released_required {
 5934:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5935:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5936:         $cid = $env{'request.course.id'};
 5937:         $cdom = $env{'course.'.$cid.'.domain'};
 5938:         $cnum = $env{'course.'.$cid.'.num'};
 5939:         $chome = $env{'course.'.$cid.'.home'};
 5940:     }
 5941:     if ($needsrelease) {
 5942:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5943:         my $needsupdate;
 5944:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5945:             $needsupdate = 1;
 5946:         } else {
 5947:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5948:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5949:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5950:                 $needsupdate = 1;
 5951:             }
 5952:         }
 5953:         if ($needsupdate) {
 5954:             my %needshash = (
 5955:                              'internal.releaserequired' => $needsrelease,
 5956:                             );
 5957:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5958:             if ($putresult eq 'ok') {
 5959:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5960:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5961:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5962:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5963:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5964:                 }
 5965:             }
 5966:         }
 5967:     }
 5968:     return;
 5969: }
 5970: 
 5971: # -------------------------------------------------See if a user is privileged
 5972: 
 5973: sub privileged {
 5974:     my ($username,$domain,$possdomains,$possroles)=@_;
 5975:     my $now = time;
 5976:     my $roles;
 5977:     if (ref($possroles) eq 'ARRAY') {
 5978:         $roles = $possroles; 
 5979:     } else {
 5980:         $roles = ['dc','su'];
 5981:     }
 5982:     if (ref($possdomains) eq 'ARRAY') {
 5983:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5984:         foreach my $dom (@{$possdomains}) {
 5985:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5986:                 (ref($privileged{$dom}) eq 'HASH')) {
 5987:                 foreach my $role (@{$roles}) {
 5988:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5989:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5990:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5991:                             return 1 unless (($end && $end < $now) ||
 5992:                                              ($start && $start > $now));
 5993:                         }
 5994:                     }
 5995:                 }
 5996:             }
 5997:         }
 5998:     } else {
 5999:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6000:         my $now = time;
 6001: 
 6002:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6003:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6004:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6005:                 return 1 unless ($tend && $tend < $now) 
 6006:                         or ($tstart && $tstart > $now);
 6007:             }
 6008:         }
 6009:     }
 6010:     return 0;
 6011: }
 6012: 
 6013: sub privileged_by_domain {
 6014:     my ($domains,$roles) = @_;
 6015:     my %privileged = ();
 6016:     my $cachetime = 60*60*24;
 6017:     my $now = time;
 6018:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6019:         return %privileged;
 6020:     }
 6021:     foreach my $dom (@{$domains}) {
 6022:         next if (ref($privileged{$dom}) eq 'HASH');
 6023:         my $needroles;
 6024:         foreach my $role (@{$roles}) {
 6025:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6026:             if (defined($cached)) {
 6027:                 if (ref($result) eq 'HASH') {
 6028:                     $privileged{$dom}{$role} = $result;
 6029:                 }
 6030:             } else {
 6031:                 $needroles = 1;
 6032:             }
 6033:         }
 6034:         if ($needroles) {
 6035:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6036:             $privileged{$dom} = {};
 6037:             foreach my $server (keys(%dompersonnel)) {
 6038:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6039:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6040:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6041:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6042:                         next if ($end && $end < $now);
 6043:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6044:                             $dompersonnel{$server}{$item};
 6045:                     }
 6046:                 }
 6047:             }
 6048:             if (ref($privileged{$dom}) eq 'HASH') {
 6049:                 foreach my $role (@{$roles}) {
 6050:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6051:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6052:                     } else {
 6053:                         my %hash = ();
 6054:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6055:                     }
 6056:                 }
 6057:             }
 6058:         }
 6059:     }
 6060:     return %privileged;
 6061: }
 6062: 
 6063: # -------------------------------------------------------- Get user privileges
 6064: 
 6065: sub rolesinit {
 6066:     my ($domain, $username) = @_;
 6067:     my %userroles = ('user.login.time' => time);
 6068:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6069: 
 6070:     # firstaccess and timerinterval are related to timed maps/resources. 
 6071:     # also, blocking can be triggered by an activating timer
 6072:     # it's saved in the user's %env.
 6073:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6074:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6075:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6076:         %timerintchk, %timerintenv);
 6077: 
 6078:     foreach my $key (keys(%firstaccess)) {
 6079:         my ($cid, $rest) = split(/\0/, $key);
 6080:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6081:     }
 6082: 
 6083:     foreach my $key (keys(%timerinterval)) {
 6084:         my ($cid,$rest) = split(/\0/,$key);
 6085:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6086:     }
 6087: 
 6088:     my %allroles=();
 6089:     my %allgroups=();
 6090: 
 6091:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6092:         my $role = $rolesdump{$area};
 6093:         $area =~ s/\_\w\w$//;
 6094: 
 6095:         my ($trole, $tend, $tstart, $group_privs);
 6096: 
 6097:         if ($role =~ /^cr/) {
 6098:         # Custom role, defined by a user 
 6099:         # e.g., user.role.cr/msu/smith/mynewrole
 6100:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6101:                 $trole = $1;
 6102:                 ($tend, $tstart) = split('_', $2);
 6103:             } else {
 6104:                 $trole = $role;
 6105:             }
 6106:         } elsif ($role =~ m|^gr/|) {
 6107:         # Role of member in a group, defined within a course/community
 6108:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6109:             ($trole, $tend, $tstart) = split(/_/, $role);
 6110:             next if $tstart eq '-1';
 6111:             ($trole, $group_privs) = split(/\//, $trole);
 6112:             $group_privs = &unescape($group_privs);
 6113:         } else {
 6114:         # Just a normal role, defined in roles.tab
 6115:             ($trole, $tend, $tstart) = split(/_/,$role);
 6116:         }
 6117: 
 6118:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6119:                  $username);
 6120:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6121: 
 6122:         # role expired or not available yet?
 6123:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6124:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6125: 
 6126:         next if $area eq '' or $trole eq '';
 6127: 
 6128:         my $spec = "$trole.$area";
 6129:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6130: 
 6131:         if ($trole =~ /^cr\//) {
 6132:         # Custom role, defined by a user
 6133:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6134:         } elsif ($trole eq 'gr') {
 6135:         # Role of a member in a group, defined within a course/community
 6136:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6137:             next;
 6138:         } else {
 6139:         # Normal role, defined in roles.tab
 6140:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6141:         }
 6142: 
 6143:         my $cid = $tdomain.'_'.$trest;
 6144:         unless ($firstaccchk{$cid}) {
 6145:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6146:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6147:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6148:                         $coursetimerstarts{$cid}{$item}; 
 6149:                 }
 6150:             }
 6151:             $firstaccchk{$cid} = 1;
 6152:         }
 6153:         unless ($timerintchk{$cid}) {
 6154:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6155:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6156:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6157:                        $coursetimerintervals{$cid}{$item};
 6158:                 }
 6159:             }
 6160:             $timerintchk{$cid} = 1;
 6161:         }
 6162:     }
 6163: 
 6164:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6165:                                                           \%allroles, \%allgroups);
 6166:     $env{'user.adv'} = $userroles{'user.adv'};
 6167:     $env{'user.rar'} = $userroles{'user.rar'};
 6168: 
 6169:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6170: }
 6171: 
 6172: sub set_arearole {
 6173:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6174:     unless ($nolog) {
 6175: # log the associated role with the area
 6176:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6177:     }
 6178:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6179: }
 6180: 
 6181: sub custom_roleprivs {
 6182:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6183:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6184:     my $homsvr = &homeserver($rauthor,$rdomain);
 6185:     if (&hostname($homsvr) ne '') {
 6186:         my ($rdummy,$roledef)=
 6187:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6188:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6189:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6190:             if (defined($syspriv)) {
 6191:                 if ($trest =~ /^$match_community$/) {
 6192:                     $syspriv =~ s/bre\&S//; 
 6193:                 }
 6194:                 $$allroles{'cm./'}.=':'.$syspriv;
 6195:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6196:             }
 6197:             if ($tdomain ne '') {
 6198:                 if (defined($dompriv)) {
 6199:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6200:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6201:                 }
 6202:                 if (($trest ne '') && (defined($coursepriv))) {
 6203:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6204:                         my $rolename = $1;
 6205:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6206:                     }
 6207:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6208:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6209:                 }
 6210:             }
 6211:         }
 6212:     }
 6213: }
 6214: 
 6215: sub course_adhocrole_privs {
 6216:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6217:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6218:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6219:         my (%currprivs,%storeprivs);
 6220:         foreach my $item (split(/:/,$coursepriv)) {
 6221:             my ($priv,$restrict) = split(/\&/,$item);
 6222:             $currprivs{$priv} = $restrict;
 6223:         }
 6224:         my (%possadd,%possremove,%full);
 6225:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6226:             my ($priv,$restrict)=split(/\&/,$item);
 6227:             $full{$priv} = $restrict;
 6228:         }
 6229:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6230:              next if ($item eq '');
 6231:              my ($rule,$rest) = split(/=/,$item);
 6232:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6233:              foreach my $priv (split(/:/,$rest)) {
 6234:                  if ($priv ne '') {
 6235:                      if ($rule eq 'off') {
 6236:                          $possremove{$priv} = 1;
 6237:                      } else {
 6238:                          $possadd{$priv} = 1;
 6239:                      }
 6240:                  }
 6241:              }
 6242:          }
 6243:          foreach my $priv (sort(keys(%full))) {
 6244:              if (exists($currprivs{$priv})) {
 6245:                  unless (exists($possremove{$priv})) {
 6246:                      $storeprivs{$priv} = $currprivs{$priv};
 6247:                  }
 6248:              } elsif (exists($possadd{$priv})) {
 6249:                  $storeprivs{$priv} = $full{$priv};
 6250:              }
 6251:          }
 6252:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6253:      }
 6254:      return $coursepriv;
 6255: }
 6256: 
 6257: sub group_roleprivs {
 6258:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6259:     my $access = 1;
 6260:     my $now = time;
 6261:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6262:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6263:     if ($access) {
 6264:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6265:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6266:     }
 6267: }
 6268: 
 6269: sub standard_roleprivs {
 6270:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6271:     if (defined($pr{$trole.':s'})) {
 6272:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6273:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6274:     }
 6275:     if ($tdomain ne '') {
 6276:         if (defined($pr{$trole.':d'})) {
 6277:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6278:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6279:         }
 6280:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6281:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6282:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6283:         }
 6284:     }
 6285: }
 6286: 
 6287: sub set_userprivs {
 6288:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6289:     my $author=0;
 6290:     my $adv=0;
 6291:     my $rar=0;
 6292:     my %grouproles = ();
 6293:     if (keys(%{$allgroups}) > 0) {
 6294:         my @groupkeys; 
 6295:         foreach my $role (keys(%{$allroles})) {
 6296:             push(@groupkeys,$role);
 6297:         }
 6298:         if (ref($groups_roles) eq 'HASH') {
 6299:             foreach my $key (keys(%{$groups_roles})) {
 6300:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6301:                     push(@groupkeys,$key);
 6302:                 }
 6303:             }
 6304:         }
 6305:         if (@groupkeys > 0) {
 6306:             foreach my $role (@groupkeys) {
 6307:                 my ($trole,$area,$sec,$extendedarea);
 6308:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6309:                     $trole = $1;
 6310:                     $area = $2;
 6311:                     $sec = $3;
 6312:                     $extendedarea = $area.$sec;
 6313:                     if (exists($$allgroups{$area})) {
 6314:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6315:                             my $spec = $trole.'.'.$extendedarea;
 6316:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6317:                                                 $$allgroups{$area}{$group};
 6318:                         }
 6319:                     }
 6320:                 }
 6321:             }
 6322:         }
 6323:     }
 6324:     foreach my $group (keys(%grouproles)) {
 6325:         $$allroles{$group} = $grouproles{$group};
 6326:     }
 6327:     foreach my $role (keys(%{$allroles})) {
 6328:         my %thesepriv;
 6329:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6330:         foreach my $item (split(/:/,$$allroles{$role})) {
 6331:             if ($item ne '') {
 6332:                 my ($privilege,$restrictions)=split(/&/,$item);
 6333:                 if ($restrictions eq '') {
 6334:                     $thesepriv{$privilege}='F';
 6335:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6336:                     $thesepriv{$privilege}.=$restrictions;
 6337:                 }
 6338:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6339:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6340:             }
 6341:         }
 6342:         my $thesestr='';
 6343:         foreach my $priv (sort(keys(%thesepriv))) {
 6344: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6345: 	}
 6346:         $userroles->{'user.priv.'.$role} = $thesestr;
 6347:     }
 6348:     return ($author,$adv,$rar);
 6349: }
 6350: 
 6351: sub role_status {
 6352:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6353:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6354:         my ($one,$two) = split(m{\./},$rolekey,2);
 6355:         (undef,undef,$$role) = split(/\./,$one,3);
 6356:         unless (!defined($$role) || $$role eq '') {
 6357:             $$where = '/'.$two;
 6358:             $$trolecode=$$role.'.'.$$where;
 6359:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6360:             $$tstatus='is';
 6361:             if ($$tstart && $$tstart>$update) {
 6362:                 $$tstatus='future';
 6363:                 if ($$tstart<$now) {
 6364:                     if ($$tstart && $$tstart>$refresh) {
 6365:                         if (($$where ne '') && ($$role ne '')) {
 6366:                             my (%allroles,%allgroups,$group_privs,
 6367:                                 %groups_roles,@rolecodes);
 6368:                             my %userroles = (
 6369:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6370:                             );
 6371:                             @rolecodes = ('cm'); 
 6372:                             my $spec=$$role.'.'.$$where;
 6373:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6374:                             if ($$role =~ /^cr\//) {
 6375:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6376:                                 push(@rolecodes,'cr');
 6377:                             } elsif ($$role eq 'gr') {
 6378:                                 push(@rolecodes,$$role);
 6379:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6380:                                                     $env{'user.name'});
 6381:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6382:                                 (undef,my $group_privs) = split(/\//,$trole);
 6383:                                 $group_privs = &unescape($group_privs);
 6384:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6385:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6386:                                 &get_groups_roles($tdomain,$trest,
 6387:                                                   \%course_roles,\@rolecodes,
 6388:                                                   \%groups_roles);
 6389:                             } else {
 6390:                                 push(@rolecodes,$$role);
 6391:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6392:                             }
 6393:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6394:                                                                    \%groups_roles);
 6395:                             &appenv(\%userroles,\@rolecodes);
 6396:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6397:                         }
 6398:                     }
 6399:                     $$tstatus = 'is';
 6400:                 }
 6401:             }
 6402:             if ($$tend) {
 6403:                 if ($$tend<$update) {
 6404:                     $$tstatus='expired';
 6405:                 } elsif ($$tend<$now) {
 6406:                     $$tstatus='will_not';
 6407:                 }
 6408:             }
 6409:         }
 6410:     }
 6411: }
 6412: 
 6413: sub get_groups_roles {
 6414:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6415:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6416:                   (ref($rolecodes) eq 'ARRAY') && 
 6417:                   (ref($groups_roles) eq 'HASH')); 
 6418:     if (keys(%{$cdom_courseroles}) > 0) {
 6419:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6420:         if ($cdom ne '' && $cnum ne '') {
 6421:             foreach my $key (keys(%{$cdom_courseroles})) {
 6422:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6423:                     my $crsrole = $1;
 6424:                     my $crssec = $2;
 6425:                     if ($crsrole =~ /^cr/) {
 6426:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6427:                             push(@{$rolecodes},'cr');
 6428:                         }
 6429:                     } else {
 6430:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6431:                             push(@{$rolecodes},$crsrole);
 6432:                         }
 6433:                     }
 6434:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6435:                     if ($crssec ne '') {
 6436:                         $rolekey .= "/$crssec";
 6437:                     }
 6438:                     $rolekey .= './';
 6439:                     $groups_roles->{$rolekey} = $rolecodes;
 6440:                 }
 6441:             }
 6442:         }
 6443:     }
 6444:     return;
 6445: }
 6446: 
 6447: sub delete_env_groupprivs {
 6448:     my ($where,$courseroles,$possroles) = @_;
 6449:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6450:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6451:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6452:         %{$courseroles->{$udom}} =
 6453:             &get_my_roles('','','userroles',['active'],
 6454:                           $possroles,[$udom],1);
 6455:     }
 6456:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6457:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6458:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6459:             my $area = '/'.$cdom.'/'.$cnum;
 6460:             my $privkey = "user.priv.$crsrole.$area";
 6461:             if ($crssec ne '') {
 6462:                 $privkey .= '/'.$crssec;
 6463:             }
 6464:             $privkey .= ".$area/$group";
 6465:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6466:         }
 6467:     }
 6468:     return;
 6469: }
 6470: 
 6471: sub check_adhoc_privs {
 6472:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6473:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6474:     if ($sec) {
 6475:         $cckey .= '/'.$sec;
 6476:     } 
 6477:     my $setprivs;
 6478:     if ($env{$cckey}) {
 6479:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6480:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6481:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6482:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6483:             $setprivs = 1;
 6484:         }
 6485:     } else {
 6486:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6487:         $setprivs = 1;
 6488:     }
 6489:     return $setprivs;
 6490: }
 6491: 
 6492: sub set_adhoc_privileges {
 6493: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6494:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6495:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6496:     if ($sec ne '') {
 6497:         $area .= '/'.$sec;
 6498:     }
 6499:     my $spec = $role.'.'.$area;
 6500:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6501:                                   $env{'user.name'},1);
 6502:     my %rolehash = ();
 6503:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6504:         my $rolename = $1;
 6505:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6506:         my %domdef = &get_domain_defaults($dcdom);
 6507:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6508:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6509:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6510:             }
 6511:         }
 6512:     } else {
 6513:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6514:     }
 6515:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6516:     &appenv(\%userroles,[$role,'cm']);
 6517:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6518:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6519:         &appenv( {'request.role'        => $spec,
 6520:                   'request.role.domain' => $dcdom,
 6521:                   'request.course.sec'  => $sec,
 6522:                  }
 6523:                );
 6524:         my $tadv=0;
 6525:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6526:         &appenv({'request.role.adv'    => $tadv});
 6527:     }
 6528: }
 6529: 
 6530: # --------------------------------------------------------------- get interface
 6531: 
 6532: sub get {
 6533:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6534:    my $items='';
 6535:    foreach my $item (@$storearr) {
 6536:        $items.=&escape($item).'&';
 6537:    }
 6538:    $items=~s/\&$//;
 6539:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6540:    if (!$uname) { $uname=$env{'user.name'}; }
 6541:    my $uhome=&homeserver($uname,$udomain);
 6542: 
 6543:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6544:    my @pairs=split(/\&/,$rep);
 6545:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6546:      return @pairs;
 6547:    }
 6548:    my %returnhash=();
 6549:    my $i=0;
 6550:    foreach my $item (@$storearr) {
 6551:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6552:       $i++;
 6553:    }
 6554:    return %returnhash;
 6555: }
 6556: 
 6557: # --------------------------------------------------------------- del interface
 6558: 
 6559: sub del {
 6560:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6561:    my $items='';
 6562:    foreach my $item (@$storearr) {
 6563:        $items.=&escape($item).'&';
 6564:    }
 6565: 
 6566:    $items=~s/\&$//;
 6567:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6568:    if (!$uname) { $uname=$env{'user.name'}; }
 6569:    my $uhome=&homeserver($uname,$udomain);
 6570:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6571: }
 6572: 
 6573: # -------------------------------------------------------------- dump interface
 6574: 
 6575: sub unserialize {
 6576:     my ($rep, $escapedkeys) = @_;
 6577: 
 6578:     return {} if $rep =~ /^error/;
 6579: 
 6580:     my %returnhash=();
 6581: 	foreach my $item (split(/\&/,$rep)) {
 6582: 	    my ($key, $value) = split(/=/, $item, 2);
 6583: 	    $key = unescape($key) unless $escapedkeys;
 6584: 	    next if $key =~ /^error: 2 /;
 6585: 	    $returnhash{$key} = &thaw_unescape($value);
 6586: 	}
 6587:     #return %returnhash;
 6588:     return \%returnhash;
 6589: }        
 6590: 
 6591: # see Lond::dump_with_regexp
 6592: # if $escapedkeys hash keys won't get unescaped.
 6593: sub dump {
 6594:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6595:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6596:     if (!$uname) { $uname=$env{'user.name'}; }
 6597:     my $uhome=&homeserver($uname,$udomain);
 6598: 
 6599:     if ($regexp) {
 6600:         $regexp=&escape($regexp);
 6601:     } else {
 6602:         $regexp='.';
 6603:     }
 6604:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6605:         # user is hosted on this machine
 6606:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6607:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6608:         return %{unserialize($reply, $escapedkeys)};
 6609:     }
 6610:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6611:     my @pairs=split(/\&/,$rep);
 6612:     my %returnhash=();
 6613:     if (!($rep =~ /^error/ )) {
 6614: 	foreach my $item (@pairs) {
 6615: 	    my ($key,$value)=split(/=/,$item,2);
 6616:         $key = unescape($key) unless $escapedkeys;
 6617:         #$key = &unescape($key);
 6618: 	    next if ($key =~ /^error: 2 /);
 6619: 	    $returnhash{$key}=&thaw_unescape($value);
 6620: 	}
 6621:     }
 6622:     return %returnhash;
 6623: }
 6624: 
 6625: 
 6626: # --------------------------------------------------------- dumpstore interface
 6627: 
 6628: sub dumpstore {
 6629:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6630:    # same as dump but keys must be escaped. They may contain colon separated
 6631:    # lists of values that may themself contain colons (e.g. symbs).
 6632:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6633: }
 6634: 
 6635: # -------------------------------------------------------------- keys interface
 6636: 
 6637: sub getkeys {
 6638:    my ($namespace,$udomain,$uname)=@_;
 6639:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6640:    if (!$uname) { $uname=$env{'user.name'}; }
 6641:    my $uhome=&homeserver($uname,$udomain);
 6642:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6643:    my @keyarray=();
 6644:    foreach my $key (split(/\&/,$rep)) {
 6645:       next if ($key =~ /^error: 2 /);
 6646:       push(@keyarray,&unescape($key));
 6647:    }
 6648:    return @keyarray;
 6649: }
 6650: 
 6651: # --------------------------------------------------------------- currentdump
 6652: sub currentdump {
 6653:    my ($courseid,$sdom,$sname)=@_;
 6654:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6655:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6656:    $sname    = $env{'user.name'}         if (! defined($sname));
 6657:    my $uhome = &homeserver($sname,$sdom);
 6658:    my $rep;
 6659: 
 6660:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6661:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6662:                    $courseid)));
 6663:    } else {
 6664:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6665:    }
 6666: 
 6667:    return if ($rep =~ /^(error:|no_such_host)/);
 6668:    #
 6669:    my %returnhash=();
 6670:    #
 6671:    if ($rep eq 'unknown_cmd') {
 6672:        # an old lond will not know currentdump
 6673:        # Do a dump and make it look like a currentdump
 6674:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6675:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6676:        my %hash = @tmp;
 6677:        @tmp=();
 6678:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6679:    } else {
 6680:        my @pairs=split(/\&/,$rep);
 6681:        foreach my $pair (@pairs) {
 6682:            my ($key,$value)=split(/=/,$pair,2);
 6683:            my ($symb,$param) = split(/:/,$key);
 6684:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6685:                                                         &thaw_unescape($value);
 6686:        }
 6687:    }
 6688:    return %returnhash;
 6689: }
 6690: 
 6691: sub convert_dump_to_currentdump{
 6692:     my %hash = %{shift()};
 6693:     my %returnhash;
 6694:     # Code ripped from lond, essentially.  The only difference
 6695:     # here is the unescaping done by lonnet::dump().  Conceivably
 6696:     # we might run in to problems with parameter names =~ /^v\./
 6697:     while (my ($key,$value) = each(%hash)) {
 6698:         my ($v,$symb,$param) = split(/:/,$key);
 6699: 	$symb  = &unescape($symb);
 6700: 	$param = &unescape($param);
 6701:         next if ($v eq 'version' || $symb eq 'keys');
 6702:         next if (exists($returnhash{$symb}) &&
 6703:                  exists($returnhash{$symb}->{$param}) &&
 6704:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6705:         $returnhash{$symb}->{$param}=$value;
 6706:         $returnhash{$symb}->{'v.'.$param}=$v;
 6707:     }
 6708:     #
 6709:     # Remove all of the keys in the hashes which keep track of
 6710:     # the version of the parameter.
 6711:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6712:         # use a foreach because we are going to delete from the hash.
 6713:         foreach my $key (keys(%$param_hash)) {
 6714:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6715:         }
 6716:     }
 6717:     return \%returnhash;
 6718: }
 6719: 
 6720: # ------------------------------------------------------ critical inc interface
 6721: 
 6722: sub cinc {
 6723:     return &inc(@_,'critical');
 6724: }
 6725: 
 6726: # --------------------------------------------------------------- inc interface
 6727: 
 6728: sub inc {
 6729:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6730:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6731:     if (!$uname) { $uname=$env{'user.name'}; }
 6732:     my $uhome=&homeserver($uname,$udomain);
 6733:     my $items='';
 6734:     if (! ref($store)) {
 6735:         # got a single value, so use that instead
 6736:         $items = &escape($store).'=&';
 6737:     } elsif (ref($store) eq 'SCALAR') {
 6738:         $items = &escape($$store).'=&';        
 6739:     } elsif (ref($store) eq 'ARRAY') {
 6740:         $items = join('=&',map {&escape($_);} @{$store});
 6741:     } elsif (ref($store) eq 'HASH') {
 6742:         while (my($key,$value) = each(%{$store})) {
 6743:             $items.= &escape($key).'='.&escape($value).'&';
 6744:         }
 6745:     }
 6746:     $items=~s/\&$//;
 6747:     if ($critical) {
 6748: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6749:     } else {
 6750: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6751:     }
 6752: }
 6753: 
 6754: # --------------------------------------------------------------- put interface
 6755: 
 6756: sub put {
 6757:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6758:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6759:    if (!$uname) { $uname=$env{'user.name'}; }
 6760:    my $uhome=&homeserver($uname,$udomain);
 6761:    my $items='';
 6762:    foreach my $item (keys(%$storehash)) {
 6763:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6764:    }
 6765:    $items=~s/\&$//;
 6766:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6767: }
 6768: 
 6769: # ------------------------------------------------------------ newput interface
 6770: 
 6771: sub newput {
 6772:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6773:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6774:    if (!$uname) { $uname=$env{'user.name'}; }
 6775:    my $uhome=&homeserver($uname,$udomain);
 6776:    my $items='';
 6777:    foreach my $key (keys(%$storehash)) {
 6778:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6779:    }
 6780:    $items=~s/\&$//;
 6781:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6782: }
 6783: 
 6784: # ---------------------------------------------------------  putstore interface
 6785: 
 6786: sub putstore {
 6787:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6788:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6789:    if (!$uname) { $uname=$env{'user.name'}; }
 6790:    my $uhome=&homeserver($uname,$udomain);
 6791:    my $items='';
 6792:    foreach my $key (keys(%$storehash)) {
 6793:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6794:    }
 6795:    $items=~s/\&$//;
 6796:    my $esc_symb=&escape($symb);
 6797:    my $esc_v=&escape($version);
 6798:    my $reply =
 6799:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6800: 	      $uhome);
 6801:    if (($tolog) && ($reply eq 'ok')) {
 6802:        my $namevalue='';
 6803:        foreach my $key (keys(%{$storehash})) {
 6804:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6805:        }
 6806:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6807:                      '&host='.&escape($perlvar{'lonHostID'}).
 6808:                      '&version='.$esc_v.
 6809:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6810:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6811:    }
 6812:    if ($reply eq 'unknown_cmd') {
 6813:        # gfall back to way things use to be done
 6814:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6815: 			    $uname);
 6816:    }
 6817:    return $reply;
 6818: }
 6819: 
 6820: sub old_putstore {
 6821:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6822:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6823:     if (!$uname) { $uname=$env{'user.name'}; }
 6824:     my $uhome=&homeserver($uname,$udomain);
 6825:     my %newstorehash;
 6826:     foreach my $item (keys(%$storehash)) {
 6827: 	my $key = $version.':'.&escape($symb).':'.$item;
 6828: 	$newstorehash{$key} = $storehash->{$item};
 6829:     }
 6830:     my $items='';
 6831:     my %allitems = ();
 6832:     foreach my $item (keys(%newstorehash)) {
 6833: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6834: 	    my $key = $1.':keys:'.$2;
 6835: 	    $allitems{$key} .= $3.':';
 6836: 	}
 6837: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6838:     }
 6839:     foreach my $item (keys(%allitems)) {
 6840: 	$allitems{$item} =~ s/\:$//;
 6841: 	$items.= $item.'='.$allitems{$item}.'&';
 6842:     }
 6843:     $items=~s/\&$//;
 6844:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6845: }
 6846: 
 6847: # ------------------------------------------------------ critical put interface
 6848: 
 6849: sub cput {
 6850:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6851:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6852:    if (!$uname) { $uname=$env{'user.name'}; }
 6853:    my $uhome=&homeserver($uname,$udomain);
 6854:    my $items='';
 6855:    foreach my $item (keys(%$storehash)) {
 6856:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6857:    }
 6858:    $items=~s/\&$//;
 6859:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6860: }
 6861: 
 6862: # -------------------------------------------------------------- eget interface
 6863: 
 6864: sub eget {
 6865:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6866:    my $items='';
 6867:    foreach my $item (@$storearr) {
 6868:        $items.=&escape($item).'&';
 6869:    }
 6870:    $items=~s/\&$//;
 6871:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6872:    if (!$uname) { $uname=$env{'user.name'}; }
 6873:    my $uhome=&homeserver($uname,$udomain);
 6874:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6875:    my @pairs=split(/\&/,$rep);
 6876:    my %returnhash=();
 6877:    my $i=0;
 6878:    foreach my $item (@$storearr) {
 6879:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6880:       $i++;
 6881:    }
 6882:    return %returnhash;
 6883: }
 6884: 
 6885: # ------------------------------------------------------------ tmpput interface
 6886: sub tmpput {
 6887:     my ($storehash,$server,$context)=@_;
 6888:     my $items='';
 6889:     foreach my $item (keys(%$storehash)) {
 6890: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6891:     }
 6892:     $items=~s/\&$//;
 6893:     if (defined($context)) {
 6894:         $items .= ':'.&escape($context);
 6895:     }
 6896:     return &reply("tmpput:$items",$server);
 6897: }
 6898: 
 6899: # ------------------------------------------------------------ tmpget interface
 6900: sub tmpget {
 6901:     my ($token,$server)=@_;
 6902:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6903:     my $rep=&reply("tmpget:$token",$server);
 6904:     my %returnhash;
 6905:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6906:         return %returnhash;
 6907:     }
 6908:     foreach my $item (split(/\&/,$rep)) {
 6909: 	my ($key,$value)=split(/=/,$item);
 6910: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6911:     }
 6912:     return %returnhash;
 6913: }
 6914: 
 6915: # ------------------------------------------------------------ tmpdel interface
 6916: sub tmpdel {
 6917:     my ($token,$server)=@_;
 6918:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6919:     return &reply("tmpdel:$token",$server);
 6920: }
 6921: 
 6922: # ------------------------------------------------------------ get_timebased_id 
 6923: 
 6924: sub get_timebased_id {
 6925:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6926:         $maxtries) = @_;
 6927:     my ($newid,$error,$dellock);
 6928:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6929:         return ('','ok','invalid call to get suffix');
 6930:     }
 6931: 
 6932: # set defaults for any optional args for which values were not supplied
 6933:     if ($who eq '') {
 6934:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6935:     }
 6936:     if (!$locktries) {
 6937:         $locktries = 3;
 6938:     }
 6939:     if (!$maxtries) {
 6940:         $maxtries = 10;
 6941:     }
 6942:     
 6943:     if (($cdom eq '') || ($cnum eq '')) {
 6944:         if ($env{'request.course.id'}) {
 6945:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6946:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6947:         }
 6948:         if (($cdom eq '') || ($cnum eq '')) {
 6949:             return ('','ok','call to get suffix not in course context');
 6950:         }
 6951:     }
 6952: 
 6953: # construct locking item
 6954:     my $lockhash = {
 6955:                       $prefix."\0".'locked_'.$keyid => $who,
 6956:                    };
 6957:     my $tries = 0;
 6958: 
 6959: # attempt to get lock on nohist_$namespace file
 6960:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6961:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6962:         $tries ++;
 6963:         sleep 1;
 6964:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6965:     }
 6966: 
 6967: # attempt to get unique identifier, based on current timestamp
 6968:     if ($gotlock eq 'ok') {
 6969:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6970:         my $id = time;
 6971:         $newid = $id;
 6972:         if ($idtype eq 'addcode') {
 6973:             $newid .= &sixnum_code();
 6974:         }
 6975:         my $idtries = 0;
 6976:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6977:             if ($idtype eq 'concat') {
 6978:                 $newid = $id.$idtries;
 6979:             } elsif ($idtype eq 'addcode') {
 6980:                 $newid = $newid.&sixnum_code();
 6981:             } else {
 6982:                 $newid ++;
 6983:             }
 6984:             $idtries ++;
 6985:         }
 6986:         if (!exists($inuse{$prefix."\0".$newid})) {
 6987:             my %new_item =  (
 6988:                               $prefix."\0".$newid => $who,
 6989:                             );
 6990:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6991:                                                  $cdom,$cnum);
 6992:             if ($putresult ne 'ok') {
 6993:                 undef($newid);
 6994:                 $error = 'error saving new item: '.$putresult;
 6995:             }
 6996:         } else {
 6997:              undef($newid);
 6998:              $error = ('error: no unique suffix available for the new item ');
 6999:         }
 7000: #  remove lock
 7001:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7002:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7003:     } else {
 7004:         $error = "error: could not obtain lockfile\n";
 7005:         $dellock = 'ok';
 7006:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7007:             $dellock = 'nolock';
 7008:         }
 7009:     }
 7010:     return ($newid,$dellock,$error);
 7011: }
 7012: 
 7013: sub sixnum_code {
 7014:     my $code;
 7015:     for (0..6) {
 7016:         $code .= int( rand(9) );
 7017:     }
 7018:     return $code;
 7019: }
 7020: 
 7021: # -------------------------------------------------- portfolio access checking
 7022: 
 7023: sub portfolio_access {
 7024:     my ($requrl,$clientip) = @_;
 7025:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7026:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7027:     if ($result) {
 7028:         my %setters;
 7029:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7030:             my ($startblock,$endblock) =
 7031:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7032:             if ($startblock && $endblock) {
 7033:                 return 'B';
 7034:             }
 7035:         } else {
 7036:             my ($startblock,$endblock) =
 7037:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7038:             if ($startblock && $endblock) {
 7039:                 return 'B';
 7040:             }
 7041:         }
 7042:     }
 7043:     if ($result eq 'ok') {
 7044:        return 'F';
 7045:     } elsif ($result =~ /^[^:]+:guest_/) {
 7046:        return 'A';
 7047:     }
 7048:     return '';
 7049: }
 7050: 
 7051: sub get_portfolio_access {
 7052:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7053: 
 7054:     if (!ref($access_hash)) {
 7055: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7056: 	my %access_controls = &get_access_controls($current_perms,$group,
 7057: 						   $file_name);
 7058: 	$access_hash = $access_controls{$file_name};
 7059:     }
 7060: 
 7061:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7062:     my $now = time;
 7063:     if (ref($access_hash) eq 'HASH') {
 7064:         foreach my $key (keys(%{$access_hash})) {
 7065:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7066:             if ($start > $now) {
 7067:                 next;
 7068:             }
 7069:             if ($end && $end<$now) {
 7070:                 next;
 7071:             }
 7072:             if ($scope eq 'public') {
 7073:                 $public = $key;
 7074:                 last;
 7075:             } elsif ($scope eq 'guest') {
 7076:                 $guest = $key;
 7077:             } elsif ($scope eq 'domains') {
 7078:                 push(@domains,$key);
 7079:             } elsif ($scope eq 'users') {
 7080:                 push(@users,$key);
 7081:             } elsif ($scope eq 'course') {
 7082:                 push(@courses,$key);
 7083:             } elsif ($scope eq 'group') {
 7084:                 push(@groups,$key);
 7085:             } elsif ($scope eq 'ip') {
 7086:                 push(@ips,$key);
 7087:             }
 7088:         }
 7089:         if ($public) {
 7090:             return 'ok';
 7091:         } elsif (@ips > 0) {
 7092:             my $allowed;
 7093:             foreach my $ipkey (@ips) {
 7094:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7095:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7096:                         $allowed = 1;
 7097:                         last; 
 7098:                     }
 7099:                 }
 7100:             }
 7101:             if ($allowed) {
 7102:                 return 'ok';
 7103:             }
 7104:         }
 7105:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7106:             if ($guest) {
 7107:                 return $guest;
 7108:             }
 7109:         } else {
 7110:             if (@domains > 0) {
 7111:                 foreach my $domkey (@domains) {
 7112:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7113:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7114:                             return 'ok';
 7115:                         }
 7116:                     }
 7117:                 }
 7118:             }
 7119:             if (@users > 0) {
 7120:                 foreach my $userkey (@users) {
 7121:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7122:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7123:                             if (ref($item) eq 'HASH') {
 7124:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7125:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7126:                                     return 'ok';
 7127:                                 }
 7128:                             }
 7129:                         }
 7130:                     } 
 7131:                 }
 7132:             }
 7133:             my %roleshash;
 7134:             my @courses_and_groups = @courses;
 7135:             push(@courses_and_groups,@groups); 
 7136:             if (@courses_and_groups > 0) {
 7137:                 my (%allgroups,%allroles); 
 7138:                 my ($start,$end,$role,$sec,$group);
 7139:                 foreach my $envkey (%env) {
 7140:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7141:                         my $cid = $2.'_'.$3; 
 7142:                         if ($1 eq 'gr') {
 7143:                             $group = $4;
 7144:                             $allgroups{$cid}{$group} = $env{$envkey};
 7145:                         } else {
 7146:                             if ($4 eq '') {
 7147:                                 $sec = 'none';
 7148:                             } else {
 7149:                                 $sec = $4;
 7150:                             }
 7151:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7152:                         }
 7153:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7154:                         my $cid = $2.'_'.$3;
 7155:                         if ($4 eq '') {
 7156:                             $sec = 'none';
 7157:                         } else {
 7158:                             $sec = $4;
 7159:                         }
 7160:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7161:                     }
 7162:                 }
 7163:                 if (keys(%allroles) == 0) {
 7164:                     return;
 7165:                 }
 7166:                 foreach my $key (@courses_and_groups) {
 7167:                     my %content = %{$$access_hash{$key}};
 7168:                     my $cnum = $content{'number'};
 7169:                     my $cdom = $content{'domain'};
 7170:                     my $cid = $cdom.'_'.$cnum;
 7171:                     if (!exists($allroles{$cid})) {
 7172:                         next;
 7173:                     }    
 7174:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7175:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7176:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7177:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7178:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7179:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7180:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7181:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7182:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7183:                                         if (grep/^all$/,@sections) {
 7184:                                             return 'ok';
 7185:                                         } else {
 7186:                                             if (grep/^$sec$/,@sections) {
 7187:                                                 return 'ok';
 7188:                                             }
 7189:                                         }
 7190:                                     }
 7191:                                 }
 7192:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7193:                                     if (grep/^none$/,@groups) {
 7194:                                         return 'ok';
 7195:                                     }
 7196:                                 } else {
 7197:                                     if (grep/^all$/,@groups) {
 7198:                                         return 'ok';
 7199:                                     } 
 7200:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7201:                                         if (grep/^$group$/,@groups) {
 7202:                                             return 'ok';
 7203:                                         }
 7204:                                     }
 7205:                                 } 
 7206:                             }
 7207:                         }
 7208:                     }
 7209:                 }
 7210:             }
 7211:             if ($guest) {
 7212:                 return $guest;
 7213:             }
 7214:         }
 7215:     }
 7216:     return;
 7217: }
 7218: 
 7219: sub course_group_datechecker {
 7220:     my ($dates,$now,$status) = @_;
 7221:     my ($start,$end) = split(/\./,$dates);
 7222:     if (!$start && !$end) {
 7223:         return 'ok';
 7224:     }
 7225:     if (grep/^active$/,@{$status}) {
 7226:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7227:             return 'ok';
 7228:         }
 7229:     }
 7230:     if (grep/^previous$/,@{$status}) {
 7231:         if ($end > $now ) {
 7232:             return 'ok';
 7233:         }
 7234:     }
 7235:     if (grep/^future$/,@{$status}) {
 7236:         if ($start > $now) {
 7237:             return 'ok';
 7238:         }
 7239:     }
 7240:     return; 
 7241: }
 7242: 
 7243: sub parse_portfolio_url {
 7244:     my ($url) = @_;
 7245: 
 7246:     my ($type,$udom,$unum,$group,$file_name);
 7247:     
 7248:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7249: 	$type = 1;
 7250:         $udom = $1;
 7251:         $unum = $2;
 7252:         $file_name = $3;
 7253:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7254: 	$type = 2;
 7255:         $udom = $1;
 7256:         $unum = $2;
 7257:         $group = $3;
 7258:         $file_name = $3.'/'.$4;
 7259:     }
 7260:     if (wantarray) {
 7261: 	return ($type,$udom,$unum,$file_name,$group);
 7262:     }
 7263:     return $type;
 7264: }
 7265: 
 7266: sub is_portfolio_url {
 7267:     my ($url) = @_;
 7268:     return scalar(&parse_portfolio_url($url));
 7269: }
 7270: 
 7271: sub is_portfolio_file {
 7272:     my ($file) = @_;
 7273:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7274:         return 1;
 7275:     }
 7276:     return;
 7277: }
 7278: 
 7279: sub usertools_access {
 7280:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7281:     my ($access,%tools);
 7282:     if ($context eq '') {
 7283:         $context = 'tools';
 7284:     }
 7285:     if ($context eq 'requestcourses') {
 7286:         %tools = (
 7287:                       official   => 1,
 7288:                       unofficial => 1,
 7289:                       community  => 1,
 7290:                       textbook   => 1,
 7291:                       placement  => 1,
 7292:                       lti        => 1,
 7293:                  );
 7294:     } elsif ($context eq 'requestauthor') {
 7295:         %tools = (
 7296:                       requestauthor => 1,
 7297:                  );
 7298:     } else {
 7299:         %tools = (
 7300:                       aboutme   => 1,
 7301:                       blog      => 1,
 7302:                       webdav    => 1,
 7303:                       portfolio => 1,
 7304:                  );
 7305:     }
 7306:     return if (!defined($tools{$tool}));
 7307: 
 7308:     if (($udom eq '') || ($uname eq '')) {
 7309:         $udom = $env{'user.domain'};
 7310:         $uname = $env{'user.name'};
 7311:     }
 7312: 
 7313:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7314:         if ($action ne 'reload') {
 7315:             if ($context eq 'requestcourses') {
 7316:                 return $env{'environment.canrequest.'.$tool};
 7317:             } elsif ($context eq 'requestauthor') {
 7318:                 return $env{'environment.canrequest.author'};
 7319:             } else {
 7320:                 return $env{'environment.availabletools.'.$tool};
 7321:             }
 7322:         }
 7323:     }
 7324: 
 7325:     my ($toolstatus,$inststatus,$envkey);
 7326:     if ($context eq 'requestauthor') {
 7327:         $envkey = $context; 
 7328:     } else {
 7329:         $envkey = $context.'.'.$tool;
 7330:     }
 7331: 
 7332:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7333:          ($action ne 'reload')) {
 7334:         $toolstatus = $env{'environment.'.$envkey};
 7335:         $inststatus = $env{'environment.inststatus'};
 7336:     } else {
 7337:         if (ref($userenvref) eq 'HASH') {
 7338:             $toolstatus = $userenvref->{$envkey};
 7339:             $inststatus = $userenvref->{'inststatus'};
 7340:         } else {
 7341:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7342:             $toolstatus = $userenv{$envkey};
 7343:             $inststatus = $userenv{'inststatus'};
 7344:         }
 7345:     }
 7346: 
 7347:     if ($toolstatus ne '') {
 7348:         if ($toolstatus) {
 7349:             $access = 1;
 7350:         } else {
 7351:             $access = 0;
 7352:         }
 7353:         return $access;
 7354:     }
 7355: 
 7356:     my ($is_adv,%domdef);
 7357:     if (ref($is_advref) eq 'HASH') {
 7358:         $is_adv = $is_advref->{'is_adv'};
 7359:     } else {
 7360:         $is_adv = &is_advanced_user($udom,$uname);
 7361:     }
 7362:     if (ref($domdefref) eq 'HASH') {
 7363:         %domdef = %{$domdefref};
 7364:     } else {
 7365:         %domdef = &get_domain_defaults($udom);
 7366:     }
 7367:     if (ref($domdef{$tool}) eq 'HASH') {
 7368:         if ($is_adv) {
 7369:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7370:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7371:                     $access = 1;
 7372:                 } else {
 7373:                     $access = 0;
 7374:                 }
 7375:                 return $access;
 7376:             }
 7377:         }
 7378:         if ($inststatus ne '') {
 7379:             my ($hasaccess,$hasnoaccess);
 7380:             foreach my $affiliation (split(/:/,$inststatus)) {
 7381:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7382:                     if ($domdef{$tool}{$affiliation}) {
 7383:                         $hasaccess = 1;
 7384:                     } else {
 7385:                         $hasnoaccess = 1;
 7386:                     }
 7387:                 }
 7388:             }
 7389:             if ($hasaccess || $hasnoaccess) {
 7390:                 if ($hasaccess) {
 7391:                     $access = 1;
 7392:                 } elsif ($hasnoaccess) {
 7393:                     $access = 0; 
 7394:                 }
 7395:                 return $access;
 7396:             }
 7397:         } else {
 7398:             if ($domdef{$tool}{'default'} ne '') {
 7399:                 if ($domdef{$tool}{'default'}) {
 7400:                     $access = 1;
 7401:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7402:                     $access = 0;
 7403:                 }
 7404:                 return $access;
 7405:             }
 7406:         }
 7407:     } else {
 7408:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7409:             $access = 1;
 7410:         } else {
 7411:             $access = 0;
 7412:         }
 7413:         return $access;
 7414:     }
 7415: }
 7416: 
 7417: sub is_course_owner {
 7418:     my ($cdom,$cnum,$udom,$uname) = @_;
 7419:     if (($udom eq '') || ($uname eq '')) {
 7420:         $udom = $env{'user.domain'};
 7421:         $uname = $env{'user.name'};
 7422:     }
 7423:     unless (($udom eq '') || ($uname eq '')) {
 7424:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7425:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7426:                 return 1;
 7427:             } else {
 7428:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7429:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7430:                     return 1;
 7431:                 }
 7432:             }
 7433:         }
 7434:     }
 7435:     return;
 7436: }
 7437: 
 7438: sub is_advanced_user {
 7439:     my ($udom,$uname) = @_;
 7440:     if ($udom ne '' && $uname ne '') {
 7441:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7442:             if (wantarray) {
 7443:                 return ($env{'user.adv'},$env{'user.author'});
 7444:             } else {
 7445:                 return $env{'user.adv'};
 7446:             }
 7447:         }
 7448:     }
 7449:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7450:     my %allroles;
 7451:     my ($is_adv,$is_author);
 7452:     foreach my $role (keys(%roleshash)) {
 7453:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7454:         my $area = '/'.$tdomain.'/'.$trest;
 7455:         if ($sec ne '') {
 7456:             $area .= '/'.$sec;
 7457:         }
 7458:         if (($area ne '') && ($trole ne '')) {
 7459:             my $spec=$trole.'.'.$area;
 7460:             if ($trole =~ /^cr\//) {
 7461:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7462:             } elsif ($trole ne 'gr') {
 7463:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7464:             }
 7465:             if ($trole eq 'au') {
 7466:                 $is_author = 1;
 7467:             }
 7468:         }
 7469:     }
 7470:     foreach my $role (keys(%allroles)) {
 7471:         last if ($is_adv);
 7472:         foreach my $item (split(/:/,$allroles{$role})) {
 7473:             if ($item ne '') {
 7474:                 my ($privilege,$restrictions)=split(/&/,$item);
 7475:                 if ($privilege eq 'adv') {
 7476:                     $is_adv = 1;
 7477:                     last;
 7478:                 }
 7479:             }
 7480:         }
 7481:     }
 7482:     if (wantarray) {
 7483:         return ($is_adv,$is_author);
 7484:     }
 7485:     return $is_adv;
 7486: }
 7487: 
 7488: sub check_can_request {
 7489:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7490:     my $canreq = 0;
 7491:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7492:         $uname = $env{'user.name'};
 7493:         $udom = $env{'user.domain'};
 7494:     }
 7495:     my ($types,$typename) = &Apache::loncommon::course_types();
 7496:     my @options = ('approval','validate','autolimit');
 7497:     my $optregex = join('|',@options);
 7498:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7499:         foreach my $type (@{$types}) {
 7500:             if (&usertools_access($uname,$udom,$type,undef,
 7501:                                   'requestcourses')) {
 7502:                 $canreq ++;
 7503:                 if (ref($request_domains) eq 'HASH') {
 7504:                     push(@{$request_domains->{$type}},$udom);
 7505:                 }
 7506:                 if ($dom eq $udom) {
 7507:                     $can_request->{$type} = 1;
 7508:                 }
 7509:             }
 7510:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7511:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7512:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7513:                 if (@curr > 0) {
 7514:                     foreach my $item (@curr) {
 7515:                         if (ref($request_domains) eq 'HASH') {
 7516:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7517:                             if ($otherdom ne '') {
 7518:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7519:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7520:                                         push(@{$request_domains->{$type}},$otherdom);
 7521:                                     }
 7522:                                 } else {
 7523:                                     push(@{$request_domains->{$type}},$otherdom);
 7524:                                 }
 7525:                             }
 7526:                         }
 7527:                     }
 7528:                     unless ($dom eq $env{'user.domain'}) {
 7529:                         $canreq ++;
 7530:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7531:                             $can_request->{$type} = 1;
 7532:                         }
 7533:                     }
 7534:                 }
 7535:             }
 7536:         }
 7537:     }
 7538:     return $canreq;
 7539: }
 7540: 
 7541: # ---------------------------------------------- Custom access rule evaluation
 7542: 
 7543: sub customaccess {
 7544:     my ($priv,$uri)=@_;
 7545:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7546:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7547:     $udom = &LONCAPA::clean_domain($udom);
 7548:     $ucrs = &LONCAPA::clean_username($ucrs);
 7549:     my $access=0;
 7550:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7551: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7552: 	if ($type eq 'user') {
 7553: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7554: 		my ($tdom,$tuname)=split(m{/},$scope);
 7555: 		if ($tdom) {
 7556: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7557: 		}
 7558: 		if ($tuname) {
 7559: 		    if ($tuname ne $env{'user.name'}) { next; }
 7560: 		}
 7561: 		$access=($effect eq 'allow');
 7562: 		last;
 7563: 	    }
 7564: 	} else {
 7565: 	    if ($role) {
 7566: 		if ($role ne $urole) { next; }
 7567: 	    }
 7568: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7569: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7570: 		if ($tdom) {
 7571: 		    if ($tdom ne $udom) { next; }
 7572: 		}
 7573: 		if ($tcrs) {
 7574: 		    if ($tcrs ne $ucrs) { next; }
 7575: 		}
 7576: 		if ($tsec) {
 7577: 		    if ($tsec ne $usec) { next; }
 7578: 		}
 7579: 		$access=($effect eq 'allow');
 7580: 		last;
 7581: 	    }
 7582: 	    if ($realm eq '' && $role eq '') {
 7583: 		$access=($effect eq 'allow');
 7584: 	    }
 7585: 	}
 7586:     }
 7587:     return $access;
 7588: }
 7589: 
 7590: # ------------------------------------------------- Check for a user privilege
 7591: 
 7592: sub allowed {
 7593:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7594:     my $ver_orguri=$uri;
 7595:     $uri=&deversion($uri);
 7596:     my $orguri=$uri;
 7597:     $uri=&declutter($uri);
 7598: 
 7599:     if ($priv eq 'evb') {
 7600: # Evade communication block restrictions for specified role in a course
 7601:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7602:             return $1;
 7603:         } else {
 7604:             return;
 7605:         }
 7606:     }
 7607: 
 7608:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7609: # Free bre access to adm and meta resources
 7610:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7611: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7612: 	&& ($priv eq 'bre')) {
 7613: 	return 'F';
 7614:     }
 7615: 
 7616: # Free bre access to user's own portfolio contents
 7617:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7618:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7619: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7620:         my %setters;
 7621:         my ($startblock,$endblock) = 
 7622:             &Apache::loncommon::blockcheck(\%setters,'port');
 7623:         if ($startblock && $endblock) {
 7624:             return 'B';
 7625:         } else {
 7626:             return 'F';
 7627:         }
 7628:     }
 7629: 
 7630: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7631:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7632:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7633:         if (exists($env{'request.course.id'})) {
 7634:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7635:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7636:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7637:                 my $courseprivid=$env{'request.course.id'};
 7638:                 $courseprivid=~s/\_/\//;
 7639:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7640:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7641:                     return $1; 
 7642:                 } else {
 7643:                     if ($env{'request.course.sec'}) {
 7644:                         $courseprivid.='/'.$env{'request.course.sec'};
 7645:                     }
 7646:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7647:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7648:                         return $2;
 7649:                     }
 7650:                 }
 7651:             }
 7652:         }
 7653:     }
 7654: 
 7655: # Free bre to public access
 7656: 
 7657:     if ($priv eq 'bre') {
 7658:         my $copyright;
 7659:         unless ($uri =~ /ext\.tool/) {
 7660:             $copyright=&metadata($uri,'copyright');
 7661:         }
 7662: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7663:            return 'F'; 
 7664:         }
 7665:         if ($copyright eq 'priv') {
 7666:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7667: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7668: 		return '';
 7669:             }
 7670:         }
 7671:         if ($copyright eq 'domain') {
 7672:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7673: 	    unless (($env{'user.domain'} eq $1) ||
 7674:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7675: 		return '';
 7676:             }
 7677:         }
 7678:         if ($env{'request.role'}=~ /li\.\//) {
 7679:             # Library role, so allow browsing of resources in this domain.
 7680:             return 'F';
 7681:         }
 7682:         if ($copyright eq 'custom') {
 7683: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7684:         }
 7685:     }
 7686:     # Domain coordinator is trying to create a course
 7687:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7688:         # uri is the requested domain in this case.
 7689:         # comparison to 'request.role.domain' shows if the user has selected
 7690:         # a role of dc for the domain in question.
 7691:         return 'F' if ($uri eq $env{'request.role.domain'});
 7692:     }
 7693: 
 7694:     my $thisallowed='';
 7695:     my $statecond=0;
 7696:     my $courseprivid='';
 7697: 
 7698:     my $ownaccess;
 7699:     # Community Coordinator or Assistant Co-author browsing resource space.
 7700:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7701:         if ($uri eq '') {
 7702:             $ownaccess = 1;
 7703:         } else {
 7704:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7705:                 my $udom = $env{'user.domain'};
 7706:                 my $uname = $env{'user.name'};
 7707:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7708:                     $ownaccess = 1;
 7709:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7710:                     unless ($uri =~ m{\.\./}) {
 7711:                         $ownaccess = 1;
 7712:                     }
 7713:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7714:                     my $now = time;
 7715:                     if ($uri =~ m{^([^/]+)/?$}) {
 7716:                         my $adom = $1;
 7717:                         foreach my $key (keys(%env)) {
 7718:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7719:                                 my ($start,$end) = split('.',$env{$key});
 7720:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7721:                                     $ownaccess = 1;
 7722:                                     last;
 7723:                                 }
 7724:                             }
 7725:                         }
 7726:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7727:                         my $adom = $1;
 7728:                         my $aname = $2;
 7729:                         foreach my $role ('ca','aa') { 
 7730:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7731:                                 my ($start,$end) =
 7732:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7733:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7734:                                     $ownaccess = 1;
 7735:                                     last;
 7736:                                 }
 7737:                             }
 7738:                         }
 7739:                     }
 7740:                 }
 7741:             }
 7742:         }
 7743:     }
 7744: 
 7745: # Course
 7746: 
 7747:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7748:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7749:             $thisallowed.=$1;
 7750:         }
 7751:     }
 7752: 
 7753: # Domain
 7754: 
 7755:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7756:        =~/\Q$priv\E\&([^\:]*)/) {
 7757:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7758:             $thisallowed.=$1;
 7759:         }
 7760:     }
 7761: 
 7762: # User who is not author or co-author might still be able to edit
 7763: # resource of an author in the domain (e.g., if Domain Coordinator).
 7764:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7765:         (&allowed('mdc',$env{'request.course.id'}))) {
 7766:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7767:             $thisallowed.=$1;
 7768:         }
 7769:     }
 7770: 
 7771: # Course: uri itself is a course
 7772:     my $courseuri=$uri;
 7773:     $courseuri=~s/\_(\d)/\/$1/;
 7774:     $courseuri=~s/^([^\/])/\/$1/;
 7775: 
 7776:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7777:        =~/\Q$priv\E\&([^\:]*)/) {
 7778:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7779:             $thisallowed.=$1;
 7780:         }
 7781:     }
 7782: 
 7783: # URI is an uploaded document for this course, default permissions don't matter
 7784: # not allowing 'edit' access (editupload) to uploaded course docs
 7785:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7786: 	$thisallowed='';
 7787:         my ($match)=&is_on_map($uri);
 7788:         if ($match) {
 7789:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7790:                   =~/\Q$priv\E\&([^\:]*)/) {
 7791:                 my $value = $1;
 7792:                 if ($noblockcheck) {
 7793:                     $thisallowed.=$value;
 7794:                 } else {
 7795:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7796:                     if (@blockers > 0) {
 7797:                         $thisallowed = 'B';
 7798:                     } else {
 7799:                         $thisallowed.=$value;
 7800:                     }
 7801:                 }
 7802:             }
 7803:         } else {
 7804:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7805:             if ($refuri) {
 7806:                 if ($refuri =~ m|^/adm/|) {
 7807:                     $thisallowed='F';
 7808:                 } else {
 7809:                     $refuri=&declutter($refuri);
 7810:                     my ($match) = &is_on_map($refuri);
 7811:                     if ($match) {
 7812:                         if ($noblockcheck) {
 7813:                             $thisallowed='F';
 7814:                         } else {
 7815:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7816:                             if (@blockers > 0) {
 7817:                                 $thisallowed = 'B';
 7818:                             } else {
 7819:                                 $thisallowed='F';
 7820:                             }
 7821:                         }
 7822:                     }
 7823:                 }
 7824:             }
 7825:         }
 7826:     }
 7827: 
 7828:     if ($priv eq 'bre'
 7829: 	&& $thisallowed ne 'F' 
 7830: 	&& $thisallowed ne '2'
 7831: 	&& &is_portfolio_url($uri)) {
 7832: 	$thisallowed = &portfolio_access($uri,$clientip);
 7833:     }
 7834: 
 7835: # Full access at system, domain or course-wide level? Exit.
 7836:     if ($thisallowed=~/F/) {
 7837: 	return 'F';
 7838:     }
 7839: 
 7840: # If this is generating or modifying users, exit with special codes
 7841: 
 7842:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7843: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7844: 	    my ($audom,$auname)=split('/',$uri);
 7845: # no author name given, so this just checks on the general right to make a co-author in this domain
 7846: 	    unless ($auname) { return $thisallowed; }
 7847: # an author name is given, so we are about to actually make a co-author for a certain account
 7848: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7849: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7850: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7851: 	}
 7852: 	return $thisallowed;
 7853:     }
 7854: #
 7855: # Gathered so far: system, domain and course wide privileges
 7856: #
 7857: # Course: See if uri or referer is an individual resource that is part of 
 7858: # the course
 7859: 
 7860:     if ($env{'request.course.id'}) {
 7861: 
 7862:        $courseprivid=$env{'request.course.id'};
 7863:        if ($env{'request.course.sec'}) {
 7864:           $courseprivid.='/'.$env{'request.course.sec'};
 7865:        }
 7866:        $courseprivid=~s/\_/\//;
 7867:        my $checkreferer=1;
 7868:        my ($match,$cond)=&is_on_map($uri);
 7869:        if ($match) {
 7870:            $statecond=$cond;
 7871:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7872:                =~/\Q$priv\E\&([^\:]*)/) {
 7873:                my $value = $1;
 7874:                if ($priv eq 'bre') {
 7875:                    if ($noblockcheck) {
 7876:                        $thisallowed.=$value;
 7877:                    } else {
 7878:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7879:                        if (@blockers > 0) {
 7880:                            $thisallowed = 'B';
 7881:                        } else {
 7882:                            $thisallowed.=$value;
 7883:                        }
 7884:                    }
 7885:                } else {
 7886:                    $thisallowed.=$value;
 7887:                }
 7888:                $checkreferer=0;
 7889:            }
 7890:        }
 7891:        
 7892:        if ($checkreferer) {
 7893: 	  my $refuri=$env{'httpref.'.$orguri};
 7894:             unless ($refuri) {
 7895:                 foreach my $key (keys(%env)) {
 7896: 		    if ($key=~/^httpref\..*\*/) {
 7897: 			my $pattern=$key;
 7898:                         $pattern=~s/^httpref\.\/res\///;
 7899:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7900:                         $pattern=~s/\//\\\//g;
 7901:                         if ($orguri=~/$pattern/) {
 7902: 			    $refuri=$env{$key};
 7903:                         }
 7904:                     }
 7905:                 }
 7906:             }
 7907: 
 7908:          if ($refuri) { 
 7909: 	  $refuri=&declutter($refuri);
 7910:           my ($match,$cond)=&is_on_map($refuri);
 7911:             if ($match) {
 7912:               my $refstatecond=$cond;
 7913:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7914:                   =~/\Q$priv\E\&([^\:]*)/) {
 7915:                   my $value = $1;
 7916:                   if ($priv eq 'bre') {
 7917:                       if ($noblockcheck) {
 7918:                           $thisallowed.=$value;
 7919:                       } else {
 7920:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7921:                           if (@blockers > 0) {
 7922:                               $thisallowed = 'B';
 7923:                           } else {
 7924:                               $thisallowed.=$value;
 7925:                           }
 7926:                       }
 7927:                   } else {
 7928:                       $thisallowed.=$value;
 7929:                   }
 7930:                   $uri=$refuri;
 7931:                   $statecond=$refstatecond;
 7932:               }
 7933:           }
 7934:         }
 7935:        }
 7936:    }
 7937: 
 7938: #
 7939: # Gathered now: all privileges that could apply, and condition number
 7940: # 
 7941: #
 7942: # Full or no access?
 7943: #
 7944: 
 7945:     if ($thisallowed=~/F/) {
 7946: 	return 'F';
 7947:     }
 7948: 
 7949:     unless ($thisallowed) {
 7950:         return '';
 7951:     }
 7952: 
 7953: # Restrictions exist, deal with them
 7954: #
 7955: #   C:according to course preferences
 7956: #   R:according to resource settings
 7957: #   L:unless locked
 7958: #   X:according to user session state
 7959: #
 7960: 
 7961: # Possibly locked functionality, check all courses
 7962: # Locks might take effect only after 10 minutes cache expiration for other
 7963: # courses, and 2 minutes for current course
 7964: 
 7965:     my $envkey;
 7966:     if ($thisallowed=~/L/) {
 7967:         foreach $envkey (keys(%env)) {
 7968:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7969:                my $courseid=$2;
 7970:                my $roleid=$1.'.'.$2;
 7971:                $courseid=~s/^\///;
 7972:                my $expiretime=600;
 7973:                if ($env{'request.role'} eq $roleid) {
 7974: 		  $expiretime=120;
 7975:                }
 7976: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7977:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7978:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7979: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7980:                }
 7981:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7982:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7983: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7984:                        &log($env{'user.domain'},$env{'user.name'},
 7985:                             $env{'user.home'},
 7986:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7987:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7988:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7989: 		       return '';
 7990:                    }
 7991:                }
 7992:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7993:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7994: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7995:                        &log($env{'user.domain'},$env{'user.name'},
 7996:                             $env{'user.home'},
 7997:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7998:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7999:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8000: 		       return '';
 8001:                    }
 8002:                }
 8003: 	   }
 8004:        }
 8005:     }
 8006:    
 8007: #
 8008: # Rest of the restrictions depend on selected course
 8009: #
 8010: 
 8011:     unless ($env{'request.course.id'}) {
 8012: 	if ($thisallowed eq 'A') {
 8013: 	    return 'A';
 8014:         } elsif ($thisallowed eq 'B') {
 8015:             return 'B';
 8016: 	} else {
 8017: 	    return '1';
 8018: 	}
 8019:     }
 8020: 
 8021: #
 8022: # Now user is definitely in a course
 8023: #
 8024: 
 8025: 
 8026: # Course preferences
 8027: 
 8028:    if ($thisallowed=~/C/) {
 8029:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8030:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8031:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8032: 	   =~/\Q$rolecode\E/) {
 8033: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8034: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8035: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8036: 			$env{'request.course.id'});
 8037: 	   }
 8038:            return '';
 8039:        }
 8040: 
 8041:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8042: 	   =~/\Q$unamedom\E/) {
 8043: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8044: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8045: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8046: 			$env{'request.course.id'});
 8047: 	   }
 8048:            return '';
 8049:        }
 8050:    }
 8051: 
 8052: # Resource preferences
 8053: 
 8054:    if ($thisallowed=~/R/) {
 8055:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8056:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8057: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8058: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8059: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8060: 	   }
 8061: 	   return '';
 8062:        }
 8063:    }
 8064: 
 8065: # Restricted by state or randomout?
 8066: 
 8067:    if ($thisallowed=~/X/) {
 8068:       if ($env{'acc.randomout'}) {
 8069: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8070:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8071:             return ''; 
 8072:          }
 8073:       }
 8074:       if (&condval($statecond)) {
 8075: 	 return '2';
 8076:       } else {
 8077:          return '';
 8078:       }
 8079:    }
 8080: 
 8081:     if ($thisallowed eq 'A') {
 8082: 	return 'A';
 8083:     } elsif ($thisallowed eq 'B') {
 8084:         return 'B';
 8085:     }
 8086:    return 'F';
 8087: }
 8088: 
 8089: # ------------------------------------------- Check construction space access
 8090: 
 8091: sub constructaccess {
 8092:     my ($url,$setpriv)=@_;
 8093: 
 8094: # We do not allow editing of previous versions of files
 8095:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8096: 
 8097: # Get username and domain from URL
 8098:     my ($ownername,$ownerdomain,$ownerhome);
 8099: 
 8100:     ($ownerdomain,$ownername) =
 8101:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8102: 
 8103: # The URL does not really point to any authorspace, forget it
 8104:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8105: 
 8106: # Now we need to see if the user has access to the authorspace of
 8107: # $ownername at $ownerdomain
 8108: 
 8109:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8110: # Real author for this?
 8111:        $ownerhome = $env{'user.home'};
 8112:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8113:           return ($ownername,$ownerdomain,$ownerhome);
 8114:        }
 8115:     } else {
 8116: # Co-author for this?
 8117:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8118:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8119:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8120:             return ($ownername,$ownerdomain,$ownerhome);
 8121:         }
 8122:         if ($env{'request.course.id'}) {
 8123:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8124:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8125:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8126:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8127:                     return ($ownername,$ownerdomain,$ownerhome);
 8128:                 }
 8129:             }
 8130:         }
 8131:     }
 8132: 
 8133: # We don't have any access right now. If we are not possibly going to do anything about this,
 8134: # we might as well leave
 8135:    unless ($setpriv) { return ''; }
 8136: 
 8137: # Backdoor access?
 8138:     my $allowed=&allowed('eco',$ownerdomain);
 8139: # Nope
 8140:     unless ($allowed) { return ''; }
 8141: # Looks like we may have access, but could be locked by the owner of the construction space
 8142:     if ($allowed eq 'U') {
 8143:         my %blocked=&get('environment',['domcoord.author'],
 8144:                          $ownerdomain,$ownername);
 8145: # Is blocked by owner
 8146:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8147:     }
 8148:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8149: # Grant temporary access
 8150:         my $then=$env{'user.login.time'};
 8151:         my $update=$env{'user.update.time'};
 8152:         if (!$update) { $update = $then; }
 8153:         my $refresh=$env{'user.refresh.time'};
 8154:         if (!$refresh) { $refresh = $update; }
 8155:         my $now = time;
 8156:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8157:                            $now,'ca','constructaccess');
 8158:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8159:         return($ownername,$ownerdomain,$ownerhome);
 8160:     }
 8161: # No business here
 8162:     return '';
 8163: }
 8164: 
 8165: # ----------------------------------------------------------- Content Blocking
 8166: 
 8167: {
 8168: # Caches for faster Course Contents display where content blocking
 8169: # is in operation (i.e., interval param set) for timed quiz.
 8170: #
 8171: # User for whom data are being temporarily cached.
 8172: my $cacheduser='';
 8173: # Cached blockers for this user (a hash of blocking items). 
 8174: my %cachedblockers=();
 8175: # When the data were last cached.
 8176: my $cachedlast='';
 8177: 
 8178: sub load_all_blockers {
 8179:     my ($uname,$udom,$blocks)=@_;
 8180:     if (($uname ne '') && ($udom ne '')) { 
 8181:         if (($cacheduser eq $uname.':'.$udom) &&
 8182:             (abs($cachedlast-time)<5)) {
 8183:             return;
 8184:         }
 8185:     }
 8186:     $cachedlast=time;
 8187:     $cacheduser=$uname.':'.$udom;
 8188:     %cachedblockers = &get_commblock_resources($blocks);
 8189: }
 8190: 
 8191: sub get_comm_blocks {
 8192:     my ($cdom,$cnum) = @_;
 8193:     if ($cdom eq '' || $cnum eq '') {
 8194:         return unless ($env{'request.course.id'});
 8195:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8196:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8197:     }
 8198:     my %commblocks;
 8199:     my $hashid=$cdom.'_'.$cnum;
 8200:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8201:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8202:         %commblocks = %{$blocksref};
 8203:     } else {
 8204:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8205:         my $cachetime = 600;
 8206:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8207:     }
 8208:     return %commblocks;
 8209: }
 8210: 
 8211: sub get_commblock_resources {
 8212:     my ($blocks) = @_;
 8213:     my %blockers = ();
 8214:     return %blockers unless ($env{'request.course.id'});
 8215:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8216:     my %commblocks;
 8217:     if (ref($blocks) eq 'HASH') {
 8218:         %commblocks = %{$blocks};
 8219:     } else {
 8220:         %commblocks = &get_comm_blocks();
 8221:     }
 8222:     return %blockers unless (keys(%commblocks) > 0); 
 8223:     my $navmap = Apache::lonnavmaps::navmap->new();
 8224:     return %blockers unless (ref($navmap));
 8225:     my $now = time;
 8226:     foreach my $block (keys(%commblocks)) {
 8227:         if ($block =~ /^(\d+)____(\d+)$/) {
 8228:             my ($start,$end) = ($1,$2);
 8229:             if ($start <= $now && $end >= $now) {
 8230:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8231:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8232:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8233:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8234:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8235:                             }
 8236:                         }
 8237:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8238:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8239:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8240:                             }
 8241:                         }
 8242:                     }
 8243:                 }
 8244:             }
 8245:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8246:             my $item = $1;
 8247:             my @to_test;
 8248:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8249:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8250:                     my @interval;
 8251:                     my $type = 'map';
 8252:                     if ($item eq 'course') {
 8253:                         $type = 'course';
 8254:                         @interval=&EXT("resource.0.interval");
 8255:                     } else {
 8256:                         if ($item =~ /___\d+___/) {
 8257:                             $type = 'resource';
 8258:                             @interval=&EXT("resource.0.interval",$item);
 8259:                             if (ref($navmap)) {                        
 8260:                                 my $res = $navmap->getBySymb($item); 
 8261:                                 push(@to_test,$res);
 8262:                             }
 8263:                         } else {
 8264:                             my $mapsymb = &symbread($item,1);
 8265:                             if ($mapsymb) {
 8266:                                 if (ref($navmap)) {
 8267:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8268:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8269:                                     foreach my $res (@to_test) {
 8270:                                         my $symb = $res->symb();
 8271:                                         next if ($symb eq $mapsymb);
 8272:                                         if ($symb ne '') {
 8273:                                             @interval=&EXT("resource.0.interval",$symb);
 8274:                                             if ($interval[1] eq 'map') {
 8275:                                                 last;
 8276:                                             }
 8277:                                         }
 8278:                                     }
 8279:                                 }
 8280:                             }
 8281:                         }
 8282:                     }
 8283:                     if ($interval[0] =~ /^(\d+)/) {
 8284:                         my $timelimit = $1; 
 8285:                         my $first_access;
 8286:                         if ($type eq 'resource') {
 8287:                             $first_access=&get_first_access($interval[1],$item);
 8288:                         } elsif ($type eq 'map') {
 8289:                             $first_access=&get_first_access($interval[1],undef,$item);
 8290:                         } else {
 8291:                             $first_access=&get_first_access($interval[1]);
 8292:                         }
 8293:                         if ($first_access) {
 8294:                             my $timesup = $first_access+$timelimit;
 8295:                             if ($timesup > $now) {
 8296:                                 my $activeblock;
 8297:                                 foreach my $res (@to_test) {
 8298:                                     if ($res->answerable()) {
 8299:                                         $activeblock = 1;
 8300:                                         last;
 8301:                                     }
 8302:                                 }
 8303:                                 if ($activeblock) {
 8304:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8305:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8306:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8307:                                          }
 8308:                                     }
 8309:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8310:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8311:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8312:                                         }
 8313:                                     }
 8314:                                 }
 8315:                             }
 8316:                         }
 8317:                     }
 8318:                 }
 8319:             }
 8320:         }
 8321:     }
 8322:     return %blockers;
 8323: }
 8324: 
 8325: sub has_comm_blocking {
 8326:     my ($priv,$symb,$uri,$blocks) = @_;
 8327:     my @blockers;
 8328:     return unless ($env{'request.course.id'});
 8329:     return unless ($priv eq 'bre');
 8330:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8331:     return if ($env{'request.state'} eq 'construct');
 8332:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8333:     return unless (keys(%cachedblockers) > 0);
 8334:     my (%possibles,@symbs);
 8335:     if (!$symb) {
 8336:         $symb = &symbread($uri,1,1,1,\%possibles);
 8337:     }
 8338:     if ($symb) {
 8339:         @symbs = ($symb);
 8340:     } elsif (keys(%possibles)) { 
 8341:         @symbs = keys(%possibles);
 8342:     }
 8343:     my $noblock;
 8344:     foreach my $symb (@symbs) {
 8345:         last if ($noblock);
 8346:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8347:         foreach my $block (keys(%cachedblockers)) {
 8348:             if ($block =~ /^firstaccess____(.+)$/) {
 8349:                 my $item = $1;
 8350:                 if (($item eq $map) || ($item eq $symb)) {
 8351:                     $noblock = 1;
 8352:                     last;
 8353:                 }
 8354:             }
 8355:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8356:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8357:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8358:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8359:                             push(@blockers,$block);
 8360:                         }
 8361:                     }
 8362:                 }
 8363:             }
 8364:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8365:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8366:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8367:                         push(@blockers,$block);
 8368:                     }
 8369:                 }
 8370:             }
 8371:         }
 8372:     }
 8373:     return if ($noblock);
 8374:     return @blockers;
 8375: }
 8376: }
 8377: 
 8378: # -------------------------------- Deversion and split uri into path an filename   
 8379: 
 8380: #
 8381: #   Removes the version from a URI and
 8382: #   splits it in to its filename and path to the filename.
 8383: #   Seems like File::Basename could have done this more clearly.
 8384: #   Parameters:
 8385: #      $uri   - input URI
 8386: #   Returns:
 8387: #     Two element list consisting of 
 8388: #     $pathname  - the URI up to and excluding the trailing /
 8389: #     $filename  - The part of the URI following the last /
 8390: #  NOTE:
 8391: #    Another realization of this is simply:
 8392: #    use File::Basename;
 8393: #    ...
 8394: #    $uri = shift;
 8395: #    $filename = basename($uri);
 8396: #    $path     = dirname($uri);
 8397: #    return ($filename, $path);
 8398: #
 8399: #     The implementation below is probably faster however.
 8400: #
 8401: sub split_uri_for_cond {
 8402:     my $uri=&deversion(&declutter(shift));
 8403:     my @uriparts=split(/\//,$uri);
 8404:     my $filename=pop(@uriparts);
 8405:     my $pathname=join('/',@uriparts);
 8406:     return ($pathname,$filename);
 8407: }
 8408: # --------------------------------------------------- Is a resource on the map?
 8409: 
 8410: sub is_on_map {
 8411:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8412:     #Trying to find the conditional for the file
 8413:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8414: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8415:     if ($match) {
 8416: 	return (1,$1);
 8417:     } else {
 8418: 	return (0,0);
 8419:     }
 8420: }
 8421: 
 8422: # --------------------------------------------------------- Get symb from alias
 8423: 
 8424: sub get_symb_from_alias {
 8425:     my $symb=shift;
 8426:     my ($map,$resid,$url)=&decode_symb($symb);
 8427: # Already is a symb
 8428:     if ($url) { return $symb; }
 8429: # Must be an alias
 8430:     my $aliassymb='';
 8431:     my %bighash;
 8432:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8433:                             &GDBM_READER(),0640)) {
 8434:         my $rid=$bighash{'mapalias_'.$symb};
 8435: 	if ($rid) {
 8436: 	    my ($mapid,$resid)=split(/\./,$rid);
 8437: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8438: 				    $resid,$bighash{'src_'.$rid});
 8439: 	}
 8440:         untie %bighash;
 8441:     }
 8442:     return $aliassymb;
 8443: }
 8444: 
 8445: # ----------------------------------------------------------------- Define Role
 8446: 
 8447: sub definerole {
 8448:   if (allowed('mcr','/')) {
 8449:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8450:     foreach my $role (split(':',$sysrole)) {
 8451: 	my ($crole,$cqual)=split(/\&/,$role);
 8452:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8453:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8454: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8455:                return "refused:s:$crole&$cqual"; 
 8456:             }
 8457:         }
 8458:     }
 8459:     foreach my $role (split(':',$domrole)) {
 8460: 	my ($crole,$cqual)=split(/\&/,$role);
 8461:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8462:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8463: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8464:                return "refused:d:$crole&$cqual"; 
 8465:             }
 8466:         }
 8467:     }
 8468:     foreach my $role (split(':',$courole)) {
 8469: 	my ($crole,$cqual)=split(/\&/,$role);
 8470:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8471:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8472: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8473:                return "refused:c:$crole&$cqual"; 
 8474:             }
 8475:         }
 8476:     }
 8477:     my $uhome;
 8478:     if (($uname ne '') && ($udom ne '')) {
 8479:         $uhome = &homeserver($uname,$udom);
 8480:         return $uhome if ($uhome eq 'no_host');
 8481:     } else {
 8482:         $uname = $env{'user.name'};
 8483:         $udom = $env{'user.domain'};
 8484:         $uhome = $env{'user.home'};
 8485:     }
 8486:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8487:                 "$udom:$uname:rolesdef_$rolename=".
 8488:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8489:     return reply($command,$uhome);
 8490:   } else {
 8491:     return 'refused';
 8492:   }
 8493: }
 8494: 
 8495: # ---------------- Make a metadata query against the network of library servers
 8496: 
 8497: sub metadata_query {
 8498:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8499:     my %rhash;
 8500:     my %libserv = &all_library();
 8501:     my @server_list = (defined($server_array) ? @$server_array
 8502:                                               : keys(%libserv) );
 8503:     for my $server (@server_list) {
 8504:         my $domains = ''; 
 8505:         if (ref($domains_hash) eq 'HASH') {
 8506:             $domains = $domains_hash->{$server}; 
 8507:         }
 8508: 	unless ($custom or $customshow) {
 8509: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8510: 	    $rhash{$server}=$reply;
 8511: 	}
 8512: 	else {
 8513: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8514: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8515: 			     $server);
 8516: 	    $rhash{$server}=$reply;
 8517: 	}
 8518:     }
 8519:     return \%rhash;
 8520: }
 8521: 
 8522: # ----------------------------------------- Send log queries and wait for reply
 8523: 
 8524: sub log_query {
 8525:     my ($uname,$udom,$query,%filters)=@_;
 8526:     my $uhome=&homeserver($uname,$udom);
 8527:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8528:     my $uhost=&hostname($uhome);
 8529:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8530:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8531:                        $uhome);
 8532:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8533:     return get_query_reply($queryid);
 8534: }
 8535: 
 8536: # -------------------------- Update MySQL table for portfolio file
 8537: 
 8538: sub update_portfolio_table {
 8539:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8540:     if ($group ne '') {
 8541:         $file_name =~s /^\Q$group\E//;
 8542:     }
 8543:     my $homeserver = &homeserver($uname,$udom);
 8544:     my $queryid=
 8545:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8546:                ':'.&escape($file_name).':'.$action,$homeserver);
 8547:     my $reply = &get_query_reply($queryid);
 8548:     return $reply;
 8549: }
 8550: 
 8551: # -------------------------- Update MySQL allusers table
 8552: 
 8553: sub update_allusers_table {
 8554:     my ($uname,$udom,$names) = @_;
 8555:     my $homeserver = &homeserver($uname,$udom);
 8556:     my $queryid=
 8557:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8558:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8559:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8560:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8561:                'generation='.&escape($names->{'generation'}).'%%'.
 8562:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8563:                'id='.&escape($names->{'id'}),$homeserver);
 8564:     return;
 8565: }
 8566: 
 8567: # ------- Request retrieval of institutional classlists for course(s)
 8568: 
 8569: sub fetch_enrollment_query {
 8570:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8571:     my ($homeserver,$sleep,$loopmax);
 8572:     my $maxtries = 1;
 8573:     if ($context eq 'automated') {
 8574:         $homeserver = $perlvar{'lonHostID'};
 8575:         $sleep = 2;
 8576:         $loopmax = 100;
 8577:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8578:     } else {
 8579:         $homeserver = &homeserver($cnum,$dom);
 8580:     }
 8581:     my $host=&hostname($homeserver);
 8582:     my $cmd = '';
 8583:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8584:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8585:     }
 8586:     $cmd =~ s/%%$//;
 8587:     $cmd = &escape($cmd);
 8588:     my $query = 'fetchenrollment';
 8589:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8590:     unless ($queryid=~/^\Q$host\E\_/) { 
 8591:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8592:         return 'error: '.$queryid;
 8593:     }
 8594:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8595:     my $tries = 1;
 8596:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8597:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8598:         $tries ++;
 8599:     }
 8600:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8601:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8602:     } else {
 8603:         my @responses = split(/:/,$reply);
 8604:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8605:             foreach my $line (@responses) {
 8606:                 my ($key,$value) = split(/=/,$line,2);
 8607:                 $$replyref{$key} = $value;
 8608:             }
 8609:         } else {
 8610:             my $pathname = LONCAPA::tempdir();
 8611:             foreach my $line (@responses) {
 8612:                 my ($key,$value) = split(/=/,$line);
 8613:                 $$replyref{$key} = $value;
 8614:                 if ($value > 0) {
 8615:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8616:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8617:                         my $destname = $pathname.'/'.$filename;
 8618:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8619:                         if ($xml_classlist =~ /^error/) {
 8620:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8621:                         } else {
 8622:                             if ( open(FILE,">",$destname) ) {
 8623:                                 print FILE &unescape($xml_classlist);
 8624:                                 close(FILE);
 8625:                             } else {
 8626:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8627:                             }
 8628:                         }
 8629:                     }
 8630:                 }
 8631:             }
 8632:         }
 8633:         return 'ok';
 8634:     }
 8635:     return 'error';
 8636: }
 8637: 
 8638: sub get_query_reply {
 8639:     my ($queryid,$sleep,$loopmax) = @_;;
 8640:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8641:         $sleep = 0.2;
 8642:     }
 8643:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8644:         $loopmax = 100;
 8645:     }
 8646:     my $replyfile=LONCAPA::tempdir().$queryid;
 8647:     my $reply='';
 8648:     for (1..$loopmax) {
 8649: 	sleep($sleep);
 8650:         if (-e $replyfile.'.end') {
 8651: 	    if (open(my $fh,"<",$replyfile)) {
 8652: 		$reply = join('',<$fh>);
 8653: 		close($fh);
 8654: 	   } else { return 'error: reply_file_error'; }
 8655:            return &unescape($reply);
 8656: 	}
 8657:     }
 8658:     return 'timeout:'.$queryid;
 8659: }
 8660: 
 8661: sub courselog_query {
 8662: #
 8663: # possible filters:
 8664: # url: url or symb
 8665: # username
 8666: # domain
 8667: # action: view, submit, grade
 8668: # start: timestamp
 8669: # end: timestamp
 8670: #
 8671:     my (%filters)=@_;
 8672:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8673:     if ($filters{'url'}) {
 8674: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8675:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8676:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8677:     }
 8678:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8679:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8680:     return &log_query($cname,$cdom,'courselog',%filters);
 8681: }
 8682: 
 8683: sub userlog_query {
 8684: #
 8685: # possible filters:
 8686: # action: log check role
 8687: # start: timestamp
 8688: # end: timestamp
 8689: #
 8690:     my ($uname,$udom,%filters)=@_;
 8691:     return &log_query($uname,$udom,'userlog',%filters);
 8692: }
 8693: 
 8694: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8695: 
 8696: sub auto_run {
 8697:     my ($cnum,$cdom) = @_;
 8698:     my $response = 0;
 8699:     my $settings;
 8700:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8701:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8702:         $settings = $domconfig{'autoenroll'};
 8703:         if ($settings->{'run'} eq '1') {
 8704:             $response = 1;
 8705:         }
 8706:     } else {
 8707:         my $homeserver;
 8708:         if (&is_course($cdom,$cnum)) {
 8709:             $homeserver = &homeserver($cnum,$cdom);
 8710:         } else {
 8711:             $homeserver = &domain($cdom,'primary');
 8712:         }
 8713:         if ($homeserver ne 'no_host') {
 8714:             $response = &reply('autorun:'.$cdom,$homeserver);
 8715:         }
 8716:     }
 8717:     return $response;
 8718: }
 8719: 
 8720: sub auto_get_sections {
 8721:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8722:     my $homeserver;
 8723:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8724:         $homeserver = &homeserver($cnum,$cdom);
 8725:     }
 8726:     if (!defined($homeserver)) { 
 8727:         if ($cdom =~ /^$match_domain$/) {
 8728:             $homeserver = &domain($cdom,'primary');
 8729:         }
 8730:     }
 8731:     my @secs;
 8732:     if (defined($homeserver)) {
 8733:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8734:         unless ($response eq 'refused') {
 8735:             @secs = split(/:/,$response);
 8736:         }
 8737:     }
 8738:     return @secs;
 8739: }
 8740: 
 8741: sub auto_new_course {
 8742:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8743:     my $homeserver = &homeserver($cnum,$cdom);
 8744:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8745:     return $response;
 8746: }
 8747: 
 8748: sub auto_validate_courseID {
 8749:     my ($cnum,$cdom,$inst_course_id) = @_;
 8750:     my $homeserver = &homeserver($cnum,$cdom);
 8751:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8752:     return $response;
 8753: }
 8754: 
 8755: sub auto_validate_instcode {
 8756:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8757:     my ($homeserver,$response);
 8758:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8759:         $homeserver = &homeserver($cnum,$cdom);
 8760:     }
 8761:     if (!defined($homeserver)) {
 8762:         if ($cdom =~ /^$match_domain$/) {
 8763:             $homeserver = &domain($cdom,'primary');
 8764:         }
 8765:     }
 8766:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8767:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8768:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8769:     return ($outcome,$description,$defaultcredits);
 8770: }
 8771: 
 8772: sub auto_create_password {
 8773:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8774:     my ($homeserver,$response);
 8775:     my $create_passwd = 0;
 8776:     my $authchk = '';
 8777:     if ($udom =~ /^$match_domain$/) {
 8778:         $homeserver = &domain($udom,'primary');
 8779:     }
 8780:     if ($homeserver eq '') {
 8781:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8782:             $homeserver = &homeserver($cnum,$cdom);
 8783:         }
 8784:     }
 8785:     if ($homeserver eq '') {
 8786:         $authchk = 'nodomain';
 8787:     } else {
 8788:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8789:         if ($response eq 'refused') {
 8790:             $authchk = 'refused';
 8791:         } else {
 8792:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8793:         }
 8794:     }
 8795:     return ($authparam,$create_passwd,$authchk);
 8796: }
 8797: 
 8798: sub auto_photo_permission {
 8799:     my ($cnum,$cdom,$students) = @_;
 8800:     my $homeserver = &homeserver($cnum,$cdom);
 8801:     my ($outcome,$perm_reqd,$conditions) = 
 8802: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8803:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8804: 	return (undef,undef);
 8805:     }
 8806:     return ($outcome,$perm_reqd,$conditions);
 8807: }
 8808: 
 8809: sub auto_checkphotos {
 8810:     my ($uname,$udom,$pid) = @_;
 8811:     my $homeserver = &homeserver($uname,$udom);
 8812:     my ($result,$resulttype);
 8813:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8814: 				   &escape($uname).':'.&escape($pid),
 8815: 				   $homeserver));
 8816:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8817: 	return (undef,undef);
 8818:     }
 8819:     if ($outcome) {
 8820:         ($result,$resulttype) = split(/:/,$outcome);
 8821:     } 
 8822:     return ($result,$resulttype);
 8823: }
 8824: 
 8825: sub auto_photochoice {
 8826:     my ($cnum,$cdom) = @_;
 8827:     my $homeserver = &homeserver($cnum,$cdom);
 8828:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8829: 						       &escape($cdom),
 8830: 						       $homeserver)));
 8831:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8832: 	return (undef,undef);
 8833:     }
 8834:     return ($update,$comment);
 8835: }
 8836: 
 8837: sub auto_photoupdate {
 8838:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8839:     my $homeserver = &homeserver($cnum,$dom);
 8840:     my $host=&hostname($homeserver);
 8841:     my $cmd = '';
 8842:     my $maxtries = 1;
 8843:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8844:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8845:     }
 8846:     $cmd =~ s/%%$//;
 8847:     $cmd = &escape($cmd);
 8848:     my $query = 'institutionalphotos';
 8849:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8850:     unless ($queryid=~/^\Q$host\E\_/) {
 8851:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8852:         return 'error: '.$queryid;
 8853:     }
 8854:     my $reply = &get_query_reply($queryid);
 8855:     my $tries = 1;
 8856:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8857:         $reply = &get_query_reply($queryid);
 8858:         $tries ++;
 8859:     }
 8860:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8861:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8862:     } else {
 8863:         my @responses = split(/:/,$reply);
 8864:         my $outcome = shift(@responses); 
 8865:         foreach my $item (@responses) {
 8866:             my ($key,$value) = split(/=/,$item);
 8867:             $$photo{$key} = $value;
 8868:         }
 8869:         return $outcome;
 8870:     }
 8871:     return 'error';
 8872: }
 8873: 
 8874: sub auto_instcode_format {
 8875:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8876: 	$cat_order) = @_;
 8877:     my $courses = '';
 8878:     my @homeservers;
 8879:     if ($caller eq 'global') {
 8880: 	my %servers = &get_servers($codedom,'library');
 8881: 	foreach my $tryserver (keys(%servers)) {
 8882: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8883: 		push(@homeservers,$tryserver);
 8884: 	    }
 8885:         }
 8886:     } elsif ($caller eq 'requests') {
 8887:         if ($codedom =~ /^$match_domain$/) {
 8888:             my $chome = &domain($codedom,'primary');
 8889:             unless ($chome eq 'no_host') {
 8890:                 push(@homeservers,$chome);
 8891:             }
 8892:         }
 8893:     } else {
 8894:         push(@homeservers,&homeserver($caller,$codedom));
 8895:     }
 8896:     foreach my $code (keys(%{$instcodes})) {
 8897:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8898:     }
 8899:     chop($courses);
 8900:     my $ok_response = 0;
 8901:     my $response;
 8902:     while (@homeservers > 0 && $ok_response == 0) {
 8903:         my $server = shift(@homeservers); 
 8904:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8905:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8906:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8907: 		split(/:/,$response);
 8908:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8909:             push(@{$codetitles},&str2array($codetitles_str));
 8910:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8911:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8912:             $ok_response = 1;
 8913:         }
 8914:     }
 8915:     if ($ok_response) {
 8916:         return 'ok';
 8917:     } else {
 8918:         return $response;
 8919:     }
 8920: }
 8921: 
 8922: sub auto_instcode_defaults {
 8923:     my ($domain,$returnhash,$code_order) = @_;
 8924:     my @homeservers;
 8925: 
 8926:     my %servers = &get_servers($domain,'library');
 8927:     foreach my $tryserver (keys(%servers)) {
 8928: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8929: 	    push(@homeservers,$tryserver);
 8930: 	}
 8931:     }
 8932: 
 8933:     my $response;
 8934:     foreach my $server (@homeservers) {
 8935:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8936:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8937: 	
 8938: 	foreach my $pair (split(/\&/,$response)) {
 8939: 	    my ($name,$value)=split(/\=/,$pair);
 8940: 	    if ($name eq 'code_order') {
 8941: 		@{$code_order} = split(/\&/,&unescape($value));
 8942: 	    } else {
 8943: 		$returnhash->{&unescape($name)}=&unescape($value);
 8944: 	    }
 8945: 	}
 8946: 	return 'ok';
 8947:     }
 8948: 
 8949:     return $response;
 8950: }
 8951: 
 8952: sub auto_possible_instcodes {
 8953:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8954:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8955:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8956:         return;
 8957:     }
 8958:     my (@homeservers,$uhome);
 8959:     if (defined(&domain($domain,'primary'))) {
 8960:         $uhome=&domain($domain,'primary');
 8961:         push(@homeservers,&domain($domain,'primary'));
 8962:     } else {
 8963:         my %servers = &get_servers($domain,'library');
 8964:         foreach my $tryserver (keys(%servers)) {
 8965:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8966:                 push(@homeservers,$tryserver);
 8967:             }
 8968:         }
 8969:     }
 8970:     my $response;
 8971:     foreach my $server (@homeservers) {
 8972:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8973:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8974:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8975:             split(':',$response);
 8976:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8977:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8978:         foreach my $item (split('&',$cat_title)) {   
 8979:             my ($name,$value)=split('=',$item);
 8980:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8981:         }
 8982:         foreach my $item (split('&',$cat_order)) {
 8983:             my ($name,$value)=split('=',$item);
 8984:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8985:         }
 8986:         return 'ok';
 8987:     }
 8988:     return $response;
 8989: }
 8990: 
 8991: sub auto_courserequest_checks {
 8992:     my ($dom) = @_;
 8993:     my ($homeserver,%validations);
 8994:     if ($dom =~ /^$match_domain$/) {
 8995:         $homeserver = &domain($dom,'primary');
 8996:     }
 8997:     unless ($homeserver eq 'no_host') {
 8998:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8999:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9000:             my @items = split(/&/,$response);
 9001:             foreach my $item (@items) {
 9002:                 my ($key,$value) = split('=',$item);
 9003:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9004:             }
 9005:         }
 9006:     }
 9007:     return %validations; 
 9008: }
 9009: 
 9010: sub auto_courserequest_validation {
 9011:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9012:     my ($homeserver,$response);
 9013:     if ($dom =~ /^$match_domain$/) {
 9014:         $homeserver = &domain($dom,'primary');
 9015:     }
 9016:     unless ($homeserver eq 'no_host') {
 9017:         my $customdata;
 9018:         if (ref($custominfo) eq 'HASH') {
 9019:             $customdata = &freeze_escape($custominfo);
 9020:         }
 9021:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9022:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9023:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9024:                                     $customdata,$homeserver));
 9025:     }
 9026:     return $response;
 9027: }
 9028: 
 9029: sub auto_validate_class_sec {
 9030:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9031:     my $homeserver = &homeserver($cnum,$cdom);
 9032:     my $ownerlist;
 9033:     if (ref($owners) eq 'ARRAY') {
 9034:         $ownerlist = join(',',@{$owners});
 9035:     } else {
 9036:         $ownerlist = $owners;
 9037:     }
 9038:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9039:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9040:     return $response;
 9041: }
 9042: 
 9043: sub auto_validate_instclasses {
 9044:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9045:     my ($homeserver,%validations);
 9046:     $homeserver = &homeserver($cnum,$cdom);
 9047:     unless ($homeserver eq 'no_host') {
 9048:         my $ownerlist;
 9049:         if (ref($owners) eq 'ARRAY') {
 9050:             $ownerlist = join(',',@{$owners});
 9051:         } else {
 9052:             $ownerlist = $owners;
 9053:         }
 9054:         if (ref($classesref) eq 'HASH') {
 9055:             my $classes = &freeze_escape($classesref);
 9056:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9057:                                 ':'.$cdom.':'.$classes,$homeserver);
 9058:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9059:                 my @items = split(/&/,$response);
 9060:                 foreach my $item (@items) {
 9061:                     my ($key,$value) = split('=',$item);
 9062:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9063:                 }
 9064:             }
 9065:         }
 9066:     }
 9067:     return %validations;
 9068: }
 9069: 
 9070: sub auto_crsreq_update {
 9071:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9072:         $code,$accessstart,$accessend,$inbound) = @_;
 9073:     my ($homeserver,%crsreqresponse);
 9074:     if ($cdom =~ /^$match_domain$/) {
 9075:         $homeserver = &domain($cdom,'primary');
 9076:     }
 9077:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9078:         my $info;
 9079:         if (ref($inbound) eq 'HASH') {
 9080:             $info = &freeze_escape($inbound);
 9081:         }
 9082:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9083:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9084:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9085:                             &escape($title).':'.&escape($code).':'.
 9086:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9087:                             $homeserver);
 9088:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9089:             my @items = split(/&/,$response);
 9090:             foreach my $item (@items) {
 9091:                 my ($key,$value) = split('=',$item);
 9092:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9093:             }
 9094:         }
 9095:     }
 9096:     return \%crsreqresponse;
 9097: }
 9098: 
 9099: sub auto_export_grades {
 9100:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9101:     my ($homeserver,%exportresponse);
 9102:     if ($cdom =~ /^$match_domain$/) {
 9103:         $homeserver = &domain($cdom,'primary');
 9104:     }
 9105:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9106:         my $info;
 9107:         if (ref($inforef) eq 'HASH') {
 9108:             $info = &freeze_escape($inforef);
 9109:         }
 9110:         if (ref($gradesref) eq 'HASH') {
 9111:             my $grades = &freeze_escape($gradesref);
 9112:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9113:                                 $info.':'.$grades,$homeserver);
 9114:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9115:                 my @items = split(/&/,$response);
 9116:                 foreach my $item (@items) {
 9117:                     my ($key,$value) = split('=',$item);
 9118:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9119:                 }
 9120:             }
 9121:         }
 9122:     }
 9123:     return \%exportresponse;
 9124: }
 9125: 
 9126: sub check_instcode_cloning {
 9127:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9128:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9129:         return;
 9130:     }
 9131:     my $canclone;
 9132:     if (@{$code_order} > 0) {
 9133:         my $instcoderegexp ='^';
 9134:         my @clonecodes = split(/\&/,$cloner);
 9135:         foreach my $item (@{$code_order}) {
 9136:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9137:                 foreach my $pair (@clonecodes) {
 9138:                     my ($key,$val) = split(/\=/,$pair,2);
 9139:                     $val = &unescape($val);
 9140:                     if ($key eq $item) {
 9141:                         $instcoderegexp .= '('.$val.')';
 9142:                         last;
 9143:                     }
 9144:                 }
 9145:             } else {
 9146:                 $instcoderegexp .= $codedefaults->{$item};
 9147:             }
 9148:         }
 9149:         $instcoderegexp .= '$';
 9150:         my (@from,@to);
 9151:         eval {
 9152:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9153:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9154:         };
 9155:         if ((@from > 0) && (@to > 0)) {
 9156:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9157:             if (!@diffs) {
 9158:                 $canclone = 1;
 9159:             }
 9160:         }
 9161:     }
 9162:     return $canclone;
 9163: }
 9164: 
 9165: sub default_instcode_cloning {
 9166:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9167:     my (%codedefaults,@code_order,$canclone);
 9168:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9169:         %codedefaults = %{$codedefaultsref};
 9170:         @code_order = @{$codeorderref};
 9171:     } elsif ($clonedom) {
 9172:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9173:     }
 9174:     if (($domdefclone) && (@code_order)) {
 9175:         my @clonecodes = split(/\+/,$domdefclone);
 9176:         my $instcoderegexp ='^';
 9177:         foreach my $item (@code_order) {
 9178:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9179:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9180:             } else {
 9181:                 $instcoderegexp .= $codedefaults{$item};
 9182:             }
 9183:         }
 9184:         $instcoderegexp .= '$';
 9185:         my (@from,@to);
 9186:         eval {
 9187:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9188:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9189:         };
 9190:         if ((@from > 0) && (@to > 0)) {
 9191:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9192:             if (!@diffs) {
 9193:                 $canclone = 1;
 9194:             }
 9195:         }
 9196:     }
 9197:     return $canclone;
 9198: }
 9199: 
 9200: # ------------------------------------------------------- Course Group routines
 9201: 
 9202: sub get_coursegroups {
 9203:     my ($cdom,$cnum,$group,$namespace) = @_;
 9204:     return(&dump($namespace,$cdom,$cnum,$group));
 9205: }
 9206: 
 9207: sub modify_coursegroup {
 9208:     my ($cdom,$cnum,$groupsettings) = @_;
 9209:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9210: }
 9211: 
 9212: sub toggle_coursegroup_status {
 9213:     my ($cdom,$cnum,$group,$action) = @_;
 9214:     my ($from_namespace,$to_namespace);
 9215:     if ($action eq 'delete') {
 9216:         $from_namespace = 'coursegroups';
 9217:         $to_namespace = 'deleted_groups';
 9218:     } else {
 9219:         $from_namespace = 'deleted_groups';
 9220:         $to_namespace = 'coursegroups';
 9221:     }
 9222:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9223:     if (my $tmp = &error(%curr_group)) {
 9224:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9225:         return ('read error',$tmp);
 9226:     } else {
 9227:         my %savedsettings = %curr_group; 
 9228:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9229:         my $deloutcome;
 9230:         if ($result eq 'ok') {
 9231:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9232:         } else {
 9233:             return ('write error',$result);
 9234:         }
 9235:         if ($deloutcome eq 'ok') {
 9236:             return 'ok';
 9237:         } else {
 9238:             return ('delete error',$deloutcome);
 9239:         }
 9240:     }
 9241: }
 9242: 
 9243: sub modify_group_roles {
 9244:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9245:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9246:     my $role = 'gr/'.&escape($userprivs);
 9247:     my ($uname,$udom) = split(/:/,$user);
 9248:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9249:     if ($result eq 'ok') {
 9250:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9251:     }
 9252:     return $result;
 9253: }
 9254: 
 9255: sub modify_coursegroup_membership {
 9256:     my ($cdom,$cnum,$membership) = @_;
 9257:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9258:     return $result;
 9259: }
 9260: 
 9261: sub get_active_groups {
 9262:     my ($udom,$uname,$cdom,$cnum) = @_;
 9263:     my $now = time;
 9264:     my %groups = ();
 9265:     foreach my $key (keys(%env)) {
 9266:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9267:             my ($start,$end) = split(/\./,$env{$key});
 9268:             if (($end!=0) && ($end<$now)) { next; }
 9269:             if (($start!=0) && ($start>$now)) { next; }
 9270:             if ($1 eq $cdom && $2 eq $cnum) {
 9271:                 $groups{$3} = $env{$key} ;
 9272:             }
 9273:         }
 9274:     }
 9275:     return %groups;
 9276: }
 9277: 
 9278: sub get_group_membership {
 9279:     my ($cdom,$cnum,$group) = @_;
 9280:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9281: }
 9282: 
 9283: sub get_users_groups {
 9284:     my ($udom,$uname,$courseid) = @_;
 9285:     my @usersgroups;
 9286:     my $cachetime=1800;
 9287: 
 9288:     my $hashid="$udom:$uname:$courseid";
 9289:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9290:     if (defined($cached)) {
 9291:         @usersgroups = split(/:/,$grouplist);
 9292:     } else {  
 9293:         $grouplist = '';
 9294:         my $courseurl = &courseid_to_courseurl($courseid);
 9295:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9296:         my $access_end = $env{'course.'.$courseid.
 9297:                               '.default_enrollment_end_date'};
 9298:         my $now = time;
 9299:         foreach my $key (keys(%roleshash)) {
 9300:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9301:                 my $group = $1;
 9302:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9303:                     my $start = $2;
 9304:                     my $end = $1;
 9305:                     if ($start == -1) { next; } # deleted from group
 9306:                     if (($start!=0) && ($start>$now)) { next; }
 9307:                     if (($end!=0) && ($end<$now)) {
 9308:                         if ($access_end && $access_end < $now) {
 9309:                             if ($access_end - $end < 86400) {
 9310:                                 push(@usersgroups,$group);
 9311:                             }
 9312:                         }
 9313:                         next;
 9314:                     }
 9315:                     push(@usersgroups,$group);
 9316:                 }
 9317:             }
 9318:         }
 9319:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9320:         $grouplist = join(':',@usersgroups);
 9321:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9322:     }
 9323:     return @usersgroups;
 9324: }
 9325: 
 9326: sub devalidate_getgroups_cache {
 9327:     my ($udom,$uname,$cdom,$cnum)=@_;
 9328:     my $courseid = $cdom.'_'.$cnum;
 9329: 
 9330:     my $hashid="$udom:$uname:$courseid";
 9331:     &devalidate_cache_new('getgroups',$hashid);
 9332: }
 9333: 
 9334: # ------------------------------------------------------------------ Plain Text
 9335: 
 9336: sub plaintext {
 9337:     my ($short,$type,$cid,$forcedefault) = @_;
 9338:     if ($short =~ m{^cr/}) {
 9339: 	return (split('/',$short))[-1];
 9340:     }
 9341:     if (!defined($cid)) {
 9342:         $cid = $env{'request.course.id'};
 9343:     }
 9344:     my %rolenames = (
 9345:                       Course    => 'std',
 9346:                       Community => 'alt1',
 9347:                       Placement => 'std',
 9348:                     );
 9349:     if ($cid ne '') {
 9350:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9351:             unless ($forcedefault) {
 9352:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9353:                 &Apache::lonlocal::mt_escape(\$roletext);
 9354:                 return &Apache::lonlocal::mt($roletext);
 9355:             }
 9356:         }
 9357:     }
 9358:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9359:         (defined($rolenames{$type})) && 
 9360:         (defined($prp{$short}{$rolenames{$type}}))) {
 9361:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9362:     } elsif ($cid ne '') {
 9363:         my $crstype = $env{'course.'.$cid.'.type'};
 9364:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9365:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9366:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9367:         }
 9368:     }
 9369:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9370: }
 9371: 
 9372: # ----------------------------------------------------------------- Assign Role
 9373: 
 9374: sub assignrole {
 9375:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9376:         $context)=@_;
 9377:     my $mrole;
 9378:     if ($role =~ /^cr\//) {
 9379:         my $cwosec=$url;
 9380:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9381: 	unless (&allowed('ccr',$cwosec)) {
 9382:            my $refused = 1;
 9383:            if ($context eq 'requestcourses') {
 9384:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9385:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9386:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9387:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9388:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9389:                            if ($crsenv{'internal.courseowner'} eq
 9390:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9391:                                $refused = '';
 9392:                            }
 9393:                        }
 9394:                    }
 9395:                }
 9396:            }
 9397:            if ($refused) {
 9398:                &logthis('Refused custom assignrole: '.
 9399:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9400:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9401:                return 'refused';
 9402:            }
 9403:         }
 9404:         $mrole='cr';
 9405:     } elsif ($role =~ /^gr\//) {
 9406:         my $cwogrp=$url;
 9407:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9408:         unless (&allowed('mdg',$cwogrp)) {
 9409:             &logthis('Refused group assignrole: '.
 9410:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9411:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9412:             return 'refused';
 9413:         }
 9414:         $mrole='gr';
 9415:     } else {
 9416:         my $cwosec=$url;
 9417:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9418:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9419:             my $refused;
 9420:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9421:                 if (!(&allowed('c'.$role,$url))) {
 9422:                     $refused = 1;
 9423:                 }
 9424:             } else {
 9425:                 $refused = 1;
 9426:             }
 9427:             if ($refused) {
 9428:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9429:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9430:                     my %crsenv;
 9431:                     if ($role eq 'cc' || $role eq 'co') {
 9432:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9433:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9434:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9435:                                 if ($crsenv{'internal.courseowner'} eq 
 9436:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9437:                                     $refused = '';
 9438:                                 }
 9439:                             }
 9440:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9441:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9442:                                 if ($crsenv{'internal.courseowner'} eq 
 9443:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9444:                                     $refused = '';
 9445:                                 }
 9446:                             }
 9447:                         }
 9448:                     }
 9449:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9450:                     if ($role eq 'st') {
 9451:                         $refused = '';
 9452:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9453:                         $refused = '';
 9454:                     }
 9455:                 } elsif ($context eq 'requestcourses') {
 9456:                     my @possroles = ('st','ta','ep','in','cc','co');
 9457:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9458:                         my $wrongcc;
 9459:                         if ($cnum =~ /^$match_community$/) {
 9460:                             $wrongcc = 1 if ($role eq 'cc');
 9461:                         } else {
 9462:                             $wrongcc = 1 if ($role eq 'co');
 9463:                         }
 9464:                         unless ($wrongcc) {
 9465:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9466:                             if ($crsenv{'internal.courseowner'} eq 
 9467:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9468:                                 $refused = '';
 9469:                             }
 9470:                         }
 9471:                     }
 9472:                 } elsif ($context eq 'requestauthor') {
 9473:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9474:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9475:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9476:                             $refused = '';
 9477:                         } else {
 9478:                             my %domdefaults = &get_domain_defaults($udom);
 9479:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9480:                                 my $checkbystatus;
 9481:                                 if ($env{'user.adv'}) { 
 9482:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9483:                                     if ($disposition eq 'automatic') {
 9484:                                         $refused = '';
 9485:                                     } elsif ($disposition eq '') {
 9486:                                         $checkbystatus = 1;
 9487:                                     } 
 9488:                                 } else {
 9489:                                     $checkbystatus = 1;
 9490:                                 }
 9491:                                 if ($checkbystatus) {
 9492:                                     if ($env{'environment.inststatus'}) {
 9493:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9494:                                         foreach my $type (@inststatuses) {
 9495:                                             if (($type ne '') &&
 9496:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9497:                                                 $refused = '';
 9498:                                             }
 9499:                                         }
 9500:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9501:                                         $refused = '';
 9502:                                     }
 9503:                                 }
 9504:                             }
 9505:                         }
 9506:                     }
 9507:                 }
 9508:                 if ($refused) {
 9509:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9510:                              ' '.$role.' '.$end.' '.$start.' by '.
 9511: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9512:                     return 'refused';
 9513:                 }
 9514:             }
 9515:         } elsif ($role eq 'au') {
 9516:             if ($url ne '/'.$udom.'/') {
 9517:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9518:                          ' to assign author role for '.$uname.':'.$udom.
 9519:                          ' in domain: '.$url.' refused (wrong domain).');
 9520:                 return 'refused';
 9521:             }
 9522:         }
 9523:         $mrole=$role;
 9524:     }
 9525:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9526:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9527:     if ($end) { $command.='_'.$end; }
 9528:     if ($start) {
 9529: 	if ($end) { 
 9530:            $command.='_'.$start; 
 9531:         } else {
 9532:            $command.='_0_'.$start;
 9533:         }
 9534:     }
 9535:     my $origstart = $start;
 9536:     my $origend = $end;
 9537:     my $delflag;
 9538: # actually delete
 9539:     if ($deleteflag) {
 9540: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9541: # modify command to delete the role
 9542:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9543:                 "$udom:$uname:$url".'_'."$mrole";
 9544: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9545: # set start and finish to negative values for userrolelog
 9546:            $start=-1;
 9547:            $end=-1;
 9548:            $delflag = 1;
 9549:         }
 9550:     }
 9551: # send command
 9552:     my $answer=&reply($command,&homeserver($uname,$udom));
 9553: # log new user role if status is ok
 9554:     if ($answer eq 'ok') {
 9555: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9556:         if (($role eq 'cc') || ($role eq 'in') ||
 9557:             ($role eq 'ep') || ($role eq 'ad') ||
 9558:             ($role eq 'ta') || ($role eq 'st') ||
 9559:             ($role=~/^cr/) || ($role eq 'gr') ||
 9560:             ($role eq 'co')) {
 9561: # for course roles, perform group memberships changes triggered by role change.
 9562:             unless ($role =~ /^gr/) {
 9563:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9564:                                                  $origstart,$selfenroll,$context);
 9565:             }
 9566:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9567:                            $selfenroll,$context);
 9568:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9569:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9570:                  ($role eq 'da')) {
 9571:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9572:                            $context);
 9573:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9574:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9575:                              $context); 
 9576:         }
 9577:         if ($role eq 'cc') {
 9578:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9579:         }
 9580:     }
 9581:     return $answer;
 9582: }
 9583: 
 9584: sub autoupdate_coowners {
 9585:     my ($url,$end,$start,$uname,$udom) = @_;
 9586:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9587:     if (($cdom ne '') && ($cnum ne '')) {
 9588:         my $now = time;
 9589:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9590:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9591:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9592:             my $instcode = $coursehash{'internal.coursecode'};
 9593:             if ($instcode ne '') {
 9594:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9595:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9596:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9597:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9598:                         if ($result eq 'valid') {
 9599:                             if ($coursehash{'internal.co-owners'}) {
 9600:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9601:                                     push(@newcoowners,$coowner);
 9602:                                 }
 9603:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9604:                                     push(@newcoowners,$uname.':'.$udom);
 9605:                                 }
 9606:                                 @newcoowners = sort(@newcoowners);
 9607:                             } else {
 9608:                                 push(@newcoowners,$uname.':'.$udom);
 9609:                             }
 9610:                         } else {
 9611:                             if ($coursehash{'internal.co-owners'}) {
 9612:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9613:                                     unless ($coowner eq $uname.':'.$udom) {
 9614:                                         push(@newcoowners,$coowner);
 9615:                                     }
 9616:                                 }
 9617:                                 unless (@newcoowners > 0) {
 9618:                                     $delcoowners = 1;
 9619:                                     $coowners = '';
 9620:                                 }
 9621:                             }
 9622:                         }
 9623:                         if (@newcoowners || $delcoowners) {
 9624:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9625:                                             $delcoowners,@newcoowners);
 9626:                         }
 9627:                     }
 9628:                 }
 9629:             }
 9630:         }
 9631:     }
 9632: }
 9633: 
 9634: sub store_coowners {
 9635:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9636:     my $cid = $cdom.'_'.$cnum;
 9637:     my ($coowners,$delresult,$putresult);
 9638:     if (@newcoowners) {
 9639:         $coowners = join(',',@newcoowners);
 9640:         my %coownershash = (
 9641:                             'internal.co-owners' => $coowners,
 9642:                            );
 9643:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9644:         if ($putresult eq 'ok') {
 9645:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9646:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9647:             }
 9648:         }
 9649:     }
 9650:     if ($delcoowners) {
 9651:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9652:         if ($delresult eq 'ok') {
 9653:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9654:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9655:             }
 9656:         }
 9657:     }
 9658:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9659:         my %crsinfo =
 9660:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9661:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9662:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9663:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9664:         }
 9665:     }
 9666: }
 9667: 
 9668: # -------------------------------------------------- Modify user authentication
 9669: # Overrides without validation
 9670: 
 9671: sub modifyuserauth {
 9672:     my ($udom,$uname,$umode,$upass)=@_;
 9673:     my $uhome=&homeserver($uname,$udom);
 9674:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9675:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9676:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9677:              ' in domain '.$env{'request.role.domain'});  
 9678:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9679: 		     &escape($upass),$uhome);
 9680:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9681:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9682:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9683:     &log($udom,,$uname,$uhome,
 9684:         'Authentication changed by '.$env{'user.domain'}.', '.
 9685:                                      $env{'user.name'}.', '.$umode.
 9686:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9687:     unless ($reply eq 'ok') {
 9688:         &logthis('Authentication mode error: '.$reply);
 9689: 	return 'error: '.$reply;
 9690:     }   
 9691:     return 'ok';
 9692: }
 9693: 
 9694: # --------------------------------------------------------------- Modify a user
 9695: 
 9696: sub modifyuser {
 9697:     my ($udom,    $uname, $uid,
 9698:         $umode,   $upass, $first,
 9699:         $middle,  $last,  $gene,
 9700:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9701:     $udom= &LONCAPA::clean_domain($udom);
 9702:     $uname=&LONCAPA::clean_username($uname);
 9703:     my $showcandelete = 'none';
 9704:     if (ref($candelete) eq 'ARRAY') {
 9705:         if (@{$candelete} > 0) {
 9706:             $showcandelete = join(', ',@{$candelete});
 9707:         }
 9708:     }
 9709:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9710:              $umode.', '.$first.', '.$middle.', '.
 9711: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9712:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9713:                                      ' desiredhome not specified'). 
 9714:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9715:              ' in domain '.$env{'request.role.domain'});
 9716:     my $uhome=&homeserver($uname,$udom,'true');
 9717:     my $newuser;
 9718:     if ($uhome eq 'no_host') {
 9719:         $newuser = 1;
 9720:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9721:                 ($umode eq 'lti')) {
 9722:             return 'error: more information needed to create new user';
 9723:         }
 9724:     }
 9725: # ----------------------------------------------------------------- Create User
 9726:     if (($uhome eq 'no_host') && 
 9727: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9728:         my $unhome='';
 9729:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9730:             $unhome = $desiredhome;
 9731: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9732: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9733:         } else { # load balancing routine for determining $unhome
 9734:             my $loadm=10000000;
 9735: 	    my %servers = &get_servers($udom,'library');
 9736: 	    foreach my $tryserver (keys(%servers)) {
 9737: 		my $answer=reply('load',$tryserver);
 9738: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9739: 		    $loadm=$answer;
 9740: 		    $unhome=$tryserver;
 9741: 		}
 9742: 	    }
 9743:         }
 9744:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9745: 	    return 'error: unable to find a home server for '.$uname.
 9746:                    ' in domain '.$udom;
 9747:         }
 9748:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9749:                          &escape($upass),$unhome);
 9750: 	unless ($reply eq 'ok') {
 9751:             return 'error: '.$reply;
 9752:         }   
 9753:         $uhome=&homeserver($uname,$udom,'true');
 9754:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9755: 	    return 'error: unable verify users home machine.';
 9756:         }
 9757:     }   # End of creation of new user
 9758: # ---------------------------------------------------------------------- Add ID
 9759:     if ($uid) {
 9760:        $uid=~tr/A-Z/a-z/;
 9761:        my %uidhash=&idrget($udom,$uname);
 9762:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9763:          && (!$forceid)) {
 9764: 	  unless ($uid eq $uidhash{$uname}) {
 9765: 	      return 'error: user id "'.$uid.'" does not match '.
 9766:                   'current user id "'.$uidhash{$uname}.'".';
 9767:           }
 9768:        } else {
 9769: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9770:        }
 9771:     }
 9772: # -------------------------------------------------------------- Add names, etc
 9773:     my @tmp=&get('environment',
 9774: 		   ['firstname','middlename','lastname','generation','id',
 9775:                     'permanentemail','inststatus'],
 9776: 		   $udom,$uname);
 9777:     my (%names,%oldnames);
 9778:     if ($tmp[0] =~ m/^error:.*/) { 
 9779:         %names=(); 
 9780:     } else {
 9781:         %names = @tmp;
 9782:         %oldnames = %names;
 9783:     }
 9784: #
 9785: # If name, email and/or uid are blank (e.g., because an uploaded file
 9786: # of users did not contain them), do not overwrite existing values
 9787: # unless field is in $candelete array ref.  
 9788: #
 9789: 
 9790:     my @fields = ('firstname','middlename','lastname','generation',
 9791:                   'permanentemail','id');
 9792:     my %newvalues;
 9793:     if (ref($candelete) eq 'ARRAY') {
 9794:         foreach my $field (@fields) {
 9795:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9796:                 if ($field eq 'firstname') {
 9797:                     $names{$field} = $first;
 9798:                 } elsif ($field eq 'middlename') {
 9799:                     $names{$field} = $middle;
 9800:                 } elsif ($field eq 'lastname') {
 9801:                     $names{$field} = $last;
 9802:                 } elsif ($field eq 'generation') { 
 9803:                     $names{$field} = $gene;
 9804:                 } elsif ($field eq 'permanentemail') {
 9805:                     $names{$field} = $email;
 9806:                 } elsif ($field eq 'id') {
 9807:                     $names{$field}  = $uid;
 9808:                 }
 9809:             }
 9810:         }
 9811:     }
 9812:     if ($first)  { $names{'firstname'}  = $first; }
 9813:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9814:     if ($last)   { $names{'lastname'}   = $last; }
 9815:     if (defined($gene))   { $names{'generation'} = $gene; }
 9816:     if ($email) {
 9817:        $email=~s/[^\w\@\.\-\,]//gs;
 9818:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9819:     }
 9820:     if ($uid) { $names{'id'}  = $uid; }
 9821:     if (defined($inststatus)) {
 9822:         $names{'inststatus'} = '';
 9823:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9824:         if (ref($usertypes) eq 'HASH') {
 9825:             my @okstatuses; 
 9826:             foreach my $item (split(/:/,$inststatus)) {
 9827:                 if (defined($usertypes->{$item})) {
 9828:                     push(@okstatuses,$item);  
 9829:                 }
 9830:             }
 9831:             if (@okstatuses) {
 9832:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9833:             }
 9834:         }
 9835:     }
 9836:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9837:                  $umode.', '.$first.', '.$middle.', '.
 9838:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9839:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9840:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9841:     } else {
 9842:         $logmsg .= ' during self creation';
 9843:     }
 9844:     my $changed;
 9845:     if ($newuser) {
 9846:         $changed = 1;
 9847:     } else {
 9848:         foreach my $field (@fields) {
 9849:             if ($names{$field} ne $oldnames{$field}) {
 9850:                 $changed = 1;
 9851:                 last;
 9852:             }
 9853:         }
 9854:     }
 9855:     unless ($changed) {
 9856:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9857:         &logthis($logmsg);
 9858:         return 'ok';
 9859:     }
 9860:     my $reply = &put('environment', \%names, $udom,$uname);
 9861:     if ($reply ne 'ok') { 
 9862:         return 'error: '.$reply;
 9863:     }
 9864:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9865:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9866:     }
 9867:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9868:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9869:     $logmsg = 'Success modifying user '.$logmsg;
 9870:     &logthis($logmsg);
 9871:     return 'ok';
 9872: }
 9873: 
 9874: # -------------------------------------------------------------- Modify student
 9875: 
 9876: sub modifystudent {
 9877:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9878:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9879:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9880:     if (!$cid) {
 9881: 	unless ($cid=$env{'request.course.id'}) {
 9882: 	    return 'not_in_class';
 9883: 	}
 9884:     }
 9885: # --------------------------------------------------------------- Make the user
 9886:     my $reply=&modifyuser
 9887: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9888:          $desiredhome,$email,$inststatus);
 9889:     unless ($reply eq 'ok') { return $reply; }
 9890:     # This will cause &modify_student_enrollment to get the uid from the
 9891:     # student's environment
 9892:     $uid = undef if (!$forceid);
 9893:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9894:                                         $gene,$usec,$end,$start,$type,$locktype,
 9895:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9896:     return $reply;
 9897: }
 9898: 
 9899: sub modify_student_enrollment {
 9900:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9901:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9902:     my ($cdom,$cnum,$chome);
 9903:     if (!$cid) {
 9904: 	unless ($cid=$env{'request.course.id'}) {
 9905: 	    return 'not_in_class';
 9906: 	}
 9907: 	$cdom=$env{'course.'.$cid.'.domain'};
 9908: 	$cnum=$env{'course.'.$cid.'.num'};
 9909:     } else {
 9910: 	($cdom,$cnum)=split(/_/,$cid);
 9911:     }
 9912:     $chome=$env{'course.'.$cid.'.home'};
 9913:     if (!$chome) {
 9914: 	$chome=&homeserver($cnum,$cdom);
 9915:     }
 9916:     if (!$chome) { return 'unknown_course'; }
 9917:     # Make sure the user exists
 9918:     my $uhome=&homeserver($uname,$udom);
 9919:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9920: 	return 'error: no such user';
 9921:     }
 9922:     # Get student data if we were not given enough information
 9923:     if (!defined($first)  || $first  eq '' || 
 9924:         !defined($last)   || $last   eq '' || 
 9925:         !defined($uid)    || $uid    eq '' || 
 9926:         !defined($middle) || $middle eq '' || 
 9927:         !defined($gene)   || $gene   eq '') {
 9928:         # They did not supply us with enough data to enroll the student, so
 9929:         # we need to pick up more information.
 9930:         my %tmp = &get('environment',
 9931:                        ['firstname','middlename','lastname', 'generation','id']
 9932:                        ,$udom,$uname);
 9933: 
 9934:         #foreach my $key (keys(%tmp)) {
 9935:         #    &logthis("key $key = ".$tmp{$key});
 9936:         #}
 9937:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9938:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9939:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9940:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9941:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9942:     }
 9943:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9944:     my $user = "$uname:$udom";
 9945:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9946:     my $reply=cput('classlist',
 9947: 		   {$user => 
 9948: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9949: 		   $cdom,$cnum);
 9950:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9951:         &devalidate_getsection_cache($udom,$uname,$cid);
 9952:     } else { 
 9953: 	return 'error: '.$reply;
 9954:     }
 9955:     # Add student role to user
 9956:     my $uurl='/'.$cid;
 9957:     $uurl=~s/\_/\//g;
 9958:     if ($usec) {
 9959: 	$uurl.='/'.$usec;
 9960:     }
 9961:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9962:                              $selfenroll,$context);
 9963:     if ($result ne 'ok') {
 9964:         if ($old_entry{$user} ne '') {
 9965:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9966:         } else {
 9967:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9968:         }
 9969:     }
 9970:     return $result; 
 9971: }
 9972: 
 9973: sub format_name {
 9974:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9975:     my $name;
 9976:     if ($first ne 'lastname') {
 9977: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9978:     } else {
 9979: 	if ($lastname=~/\S/) {
 9980: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9981: 	    $name=~s/\s+,/,/;
 9982: 	} else {
 9983: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9984: 	}
 9985:     }
 9986:     $name=~s/^\s+//;
 9987:     $name=~s/\s+$//;
 9988:     $name=~s/\s+/ /g;
 9989:     return $name;
 9990: }
 9991: 
 9992: # ------------------------------------------------- Write to course preferences
 9993: 
 9994: sub writecoursepref {
 9995:     my ($courseid,%prefs)=@_;
 9996:     $courseid=~s/^\///;
 9997:     $courseid=~s/\_/\//g;
 9998:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9999:     my $chome=homeserver($cnum,$cdomain);
10000:     if (($chome eq '') || ($chome eq 'no_host')) { 
10001: 	return 'error: no such course';
10002:     }
10003:     my $cstring='';
10004:     foreach my $pref (keys(%prefs)) {
10005: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10006:     }
10007:     $cstring=~s/\&$//;
10008:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10009: }
10010: 
10011: # ---------------------------------------------------------- Make/modify course
10012: 
10013: sub createcourse {
10014:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10015:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10016:     $url=&declutter($url);
10017:     my $cid='';
10018:     if ($context eq 'requestcourses') {
10019:         my $can_create = 0;
10020:         my ($ownername,$ownerdom) = split(':',$course_owner);
10021:         if ($udom eq $ownerdom) {
10022:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10023:                                   $context)) {
10024:                 $can_create = 1;
10025:             }
10026:         } else {
10027:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10028:                                            $category);
10029:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10030:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10031:                 if (@curr > 0) {
10032:                     my @options = qw(approval validate autolimit);
10033:                     my $optregex = join('|',@options);
10034:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10035:                         $can_create = 1;
10036:                     }
10037:                 }
10038:             }
10039:         }
10040:         if ($can_create) {
10041:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10042:                 unless (&allowed('ccc',$udom)) {
10043:                     return 'refused'; 
10044:                 }
10045:             }
10046:         } else {
10047:             return 'refused';
10048:         }
10049:     } elsif (!&allowed('ccc',$udom)) {
10050:         return 'refused';
10051:     }
10052: # --------------------------------------------------------------- Get Unique ID
10053:     my $uname;
10054:     if ($cnum =~ /^$match_courseid$/) {
10055:         my $chome=&homeserver($cnum,$udom,'true');
10056:         if (($chome eq '') || ($chome eq 'no_host')) {
10057:             $uname = $cnum;
10058:         } else {
10059:             $uname = &generate_coursenum($udom,$crstype);
10060:         }
10061:     } else {
10062:         $uname = &generate_coursenum($udom,$crstype);
10063:     }
10064:     return $uname if ($uname =~ /^error/);
10065: # -------------------------------------------------- Check supplied server name
10066:     if (!defined($course_server)) {
10067:         if (defined(&domain($udom,'primary'))) {
10068:             $course_server = &domain($udom,'primary');
10069:         } else {
10070:             $course_server = $env{'user.home'}; 
10071:         }
10072:     }
10073:     my %host_servers =
10074:         &Apache::lonnet::get_servers($udom,'library');
10075:     unless ($host_servers{$course_server}) {
10076:         return 'error: invalid home server for course: '.$course_server;
10077:     }
10078: # ------------------------------------------------------------- Make the course
10079:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10080:                       $course_server);
10081:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10082:     my $uhome=&homeserver($uname,$udom,'true');
10083:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10084: 	return 'error: no such course';
10085:     }
10086: # ----------------------------------------------------------------- Course made
10087: # log existence
10088:     my $now = time;
10089:     my $newcourse = {
10090:                     $udom.'_'.$uname => {
10091:                                      description => $description,
10092:                                      inst_code   => $inst_code,
10093:                                      owner       => $course_owner,
10094:                                      type        => $crstype,
10095:                                      creator     => $env{'user.name'}.':'.
10096:                                                     $env{'user.domain'},
10097:                                      created     => $now,
10098:                                      context     => $context,
10099:                                                 },
10100:                     };
10101:     &courseidput($udom,$newcourse,$uhome,'notime');
10102: # set toplevel url
10103:     my $topurl=$url;
10104:     unless ($nonstandard) {
10105: # ------------------------------------------ For standard courses, make top url
10106:         my $mapurl=&clutter($url);
10107:         if ($mapurl eq '/res/') { $mapurl=''; }
10108:         $env{'form.initmap'}=(<<ENDINITMAP);
10109: <map>
10110: <resource id="1" type="start"></resource>
10111: <resource id="2" src="$mapurl"></resource>
10112: <resource id="3" type="finish"></resource>
10113: <link index="1" from="1" to="2"></link>
10114: <link index="2" from="2" to="3"></link>
10115: </map>
10116: ENDINITMAP
10117:         $topurl=&declutter(
10118:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10119:                           );
10120:     }
10121: # ----------------------------------------------------------- Write preferences
10122:     &writecoursepref($udom.'_'.$uname,
10123:                      ('description'              => $description,
10124:                       'url'                      => $topurl,
10125:                       'internal.creator'         => $env{'user.name'}.':'.
10126:                                                     $env{'user.domain'},
10127:                       'internal.created'         => $now,
10128:                       'internal.creationcontext' => $context)
10129:                     );
10130:     return '/'.$udom.'/'.$uname;
10131: }
10132: 
10133: # ------------------------------------------------------------------- Create ID
10134: sub generate_coursenum {
10135:     my ($udom,$crstype) = @_;
10136:     my $domdesc = &domain($udom);
10137:     return 'error: invalid domain' if ($domdesc eq '');
10138:     my $first;
10139:     if ($crstype eq 'Community') {
10140:         $first = '0';
10141:     } else {
10142:         $first = int(1+rand(9)); 
10143:     } 
10144:     my $uname=$first.
10145:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10146:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10147:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10148: # ----------------------------------------------- Make sure that does not exist
10149:     my $uhome=&homeserver($uname,$udom,'true');
10150:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10151:         if ($crstype eq 'Community') {
10152:             $first = '0';
10153:         } else {
10154:             $first = int(1+rand(9));
10155:         }
10156:         $uname=$first.
10157:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10158:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10159:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10160:         $uhome=&homeserver($uname,$udom,'true');
10161:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10162:             return 'error: unable to generate unique course-ID';
10163:         }
10164:     }
10165:     return $uname;
10166: }
10167: 
10168: sub is_course {
10169:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10170:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10171: 
10172:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10173:     my $uhome=&homeserver($cnum,$cdom);
10174:     my $iscourse;
10175:     if (grep { $_ eq $uhome } current_machine_ids()) {
10176:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10177:     } else {
10178:         my $hashid = $cdom.':'.$cnum;
10179:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10180:         unless (defined($cached)) {
10181:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10182:                                         $cnum,undef,undef,'.');
10183:             $iscourse = 0;
10184:             if (exists($courses{$cdom.'_'.$cnum})) {
10185:                 $iscourse = 1;
10186:             }
10187:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10188:         }
10189:     }
10190:     return unless ($iscourse);
10191:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10192: }
10193: 
10194: sub store_userdata {
10195:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10196:     my $result;
10197:     if ($datakey ne '') {
10198:         if (ref($storehash) eq 'HASH') {
10199:             if ($udom eq '' || $uname eq '') {
10200:                 $udom = $env{'user.domain'};
10201:                 $uname = $env{'user.name'};
10202:             }
10203:             my $uhome=&homeserver($uname,$udom);
10204:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10205:                 $result = 'error: no_host';
10206:             } else {
10207:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10208:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10209: 
10210:                 my $namevalue='';
10211:                 foreach my $key (keys(%{$storehash})) {
10212:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10213:                 }
10214:                 $namevalue=~s/\&$//;
10215:                 unless ($namespace eq 'courserequests') {
10216:                     $datakey = &escape($datakey);
10217:                 }
10218:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10219:                                   $namevalue,$uhome);
10220:             }
10221:         } else {
10222:             $result = 'error: data to store was not a hash reference'; 
10223:         }
10224:     } else {
10225:         $result= 'error: invalid requestkey'; 
10226:     }
10227:     return $result;
10228: }
10229: 
10230: # ---------------------------------------------------------- Assign Custom Role
10231: 
10232: sub assigncustomrole {
10233:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10234:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10235:                        $end,$start,$deleteflag,$selfenroll,$context);
10236: }
10237: 
10238: # ----------------------------------------------------------------- Revoke Role
10239: 
10240: sub revokerole {
10241:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10242:     my $now=time;
10243:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10244: }
10245: 
10246: # ---------------------------------------------------------- Revoke Custom Role
10247: 
10248: sub revokecustomrole {
10249:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10250:     my $now=time;
10251:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10252:            $deleteflag,$selfenroll,$context);
10253: }
10254: 
10255: # ------------------------------------------------------------ Disk usage
10256: sub diskusage {
10257:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10258:     $directorypath =~ s/\/$//;
10259:     my $listing=&reply('du2:'.&escape($directorypath).':'
10260:                        .&escape($getpropath).':'.&escape($uname).':'
10261:                        .&escape($udom),homeserver($uname,$udom));
10262:     if ($listing eq 'unknown_cmd') {
10263:         if ($getpropath) {
10264:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10265:         }
10266:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10267:     }
10268:     return $listing;
10269: }
10270: 
10271: sub is_locked {
10272:     my ($file_name, $domain, $user, $which) = @_;
10273:     my @check;
10274:     my $is_locked;
10275:     push (@check,$file_name);
10276:     my %locked = &get('file_permissions',\@check,
10277: 		      $env{'user.domain'},$env{'user.name'});
10278:     my ($tmp)=keys(%locked);
10279:     if ($tmp=~/^error:/) { undef(%locked); }
10280:     
10281:     if (ref($locked{$file_name}) eq 'ARRAY') {
10282:         $is_locked = 'false';
10283:         foreach my $entry (@{$locked{$file_name}}) {
10284:            if (ref($entry) eq 'ARRAY') {
10285:                $is_locked = 'true';
10286:                if (ref($which) eq 'ARRAY') {
10287:                    push(@{$which},$entry);
10288:                } else {
10289:                    last;
10290:                }
10291:            }
10292:        }
10293:     } else {
10294:         $is_locked = 'false';
10295:     }
10296:     return $is_locked;
10297: }
10298: 
10299: sub declutter_portfile {
10300:     my ($file) = @_;
10301:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10302:     return $file;
10303: }
10304: 
10305: # ------------------------------------------------------------- Mark as Read Only
10306: 
10307: sub mark_as_readonly {
10308:     my ($domain,$user,$files,$what) = @_;
10309:     my %current_permissions = &dump('file_permissions',$domain,$user);
10310:     my ($tmp)=keys(%current_permissions);
10311:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10312:     foreach my $file (@{$files}) {
10313: 	$file = &declutter_portfile($file);
10314:         push(@{$current_permissions{$file}},$what);
10315:     }
10316:     &put('file_permissions',\%current_permissions,$domain,$user);
10317:     return;
10318: }
10319: 
10320: # ------------------------------------------------------------Save Selected Files
10321: 
10322: sub save_selected_files {
10323:     my ($user, $path, @files) = @_;
10324:     my $filename = $user."savedfiles";
10325:     my @other_files = &files_not_in_path($user, $path);
10326:     open (OUT,'>',LONCAPA::tempdir().$filename);
10327:     foreach my $file (@files) {
10328:         print (OUT $env{'form.currentpath'}.$file."\n");
10329:     }
10330:     foreach my $file (@other_files) {
10331:         print (OUT $file."\n");
10332:     }
10333:     close (OUT);
10334:     return 'ok';
10335: }
10336: 
10337: sub clear_selected_files {
10338:     my ($user) = @_;
10339:     my $filename = $user."savedfiles";
10340:     open (OUT,'>',LONCAPA::tempdir().$filename);
10341:     print (OUT undef);
10342:     close (OUT);
10343:     return ("ok");    
10344: }
10345: 
10346: sub files_in_path {
10347:     my ($user, $path) = @_;
10348:     my $filename = $user."savedfiles";
10349:     my %return_files;
10350:     open (IN,'<',LONCAPA::tempdir().$filename);
10351:     while (my $line_in = <IN>) {
10352:         chomp ($line_in);
10353:         my @paths_and_file = split (m!/!, $line_in);
10354:         my $file_part = pop (@paths_and_file);
10355:         my $path_part = join ('/', @paths_and_file);
10356:         $path_part.='/';
10357:         my $path_and_file = $path_part.$file_part;
10358:         if ($path_part eq $path) {
10359:             $return_files{$file_part}= 'selected';
10360:         }
10361:     }
10362:     close (IN);
10363:     return (\%return_files);
10364: }
10365: 
10366: # called in portfolio select mode, to show files selected NOT in current directory
10367: sub files_not_in_path {
10368:     my ($user, $path) = @_;
10369:     my $filename = $user."savedfiles";
10370:     my @return_files;
10371:     my $path_part;
10372:     open(IN, '<',LONCAPA::tempdir().$filename);
10373:     while (my $line = <IN>) {
10374:         #ok, I know it's clunky, but I want it to work
10375:         my @paths_and_file = split(m|/|, $line);
10376:         my $file_part = pop(@paths_and_file);
10377:         chomp($file_part);
10378:         my $path_part = join('/', @paths_and_file);
10379:         $path_part .= '/';
10380:         my $path_and_file = $path_part.$file_part;
10381:         if ($path_part ne $path) {
10382:             push(@return_files, ($path_and_file));
10383:         }
10384:     }
10385:     close(OUT);
10386:     return (@return_files);
10387: }
10388: 
10389: #------------------------------Submitted/Handedback Portfolio Files Versioning
10390:  
10391: sub portfiles_versioning {
10392:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10393:     my $portfolio_root = '/userfiles/portfolio';
10394:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10395:     foreach my $file (@{$portfiles}) {
10396:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10397:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10398:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10399:         my $getpropath = 1;
10400:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10401:                                              $stu_name,$getpropath);
10402:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10403:         my $new_answer = 
10404:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10405:         if ($new_answer ne 'problem getting file') {
10406:             push(@{$versioned_portfiles}, $directory.$new_answer);
10407:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10408:                               [$symb,$env{'request.course.id'},'graded']);
10409:         }
10410:     }
10411: }
10412: 
10413: sub get_next_version {
10414:     my ($answer_name, $answer_ext, $dir_list) = @_;
10415:     my $version;
10416:     if (ref($dir_list) eq 'ARRAY') {
10417:         foreach my $row (@{$dir_list}) {
10418:             my ($file) = split(/\&/,$row,2);
10419:             my ($file_name,$file_version,$file_ext) =
10420:                 &file_name_version_ext($file);
10421:             if (($file_name eq $answer_name) &&
10422:                 ($file_ext eq $answer_ext)) {
10423:                      # gets here if filename and extension match,
10424:                      # regardless of version
10425:                 if ($file_version ne '') {
10426:                     # a versioned file is found  so save it for later
10427:                     if ($file_version > $version) {
10428:                         $version = $file_version;
10429:                     }
10430:                 }
10431:             }
10432:         }
10433:     }
10434:     $version ++;
10435:     return($version);
10436: }
10437: 
10438: sub version_selected_portfile {
10439:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10440:     my ($answer_name,$answer_ver,$answer_ext) =
10441:         &file_name_version_ext($file_name);
10442:     my $new_answer;
10443:     $env{'form.copy'} =
10444:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10445:     if($env{'form.copy'} eq '-1') {
10446:         $new_answer = 'problem getting file';
10447:     } else {
10448:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10449:         my $copy_result = 
10450:             &finishuserfileupload($stu_name,$domain,'copy',
10451:                                   '/portfolio'.$directory.$new_answer);
10452:     }
10453:     undef($env{'form.copy'});
10454:     return ($new_answer);
10455: }
10456: 
10457: sub file_name_version_ext {
10458:     my ($file)=@_;
10459:     my @file_parts = split(/\./, $file);
10460:     my ($name,$version,$ext);
10461:     if (@file_parts > 1) {
10462:         $ext=pop(@file_parts);
10463:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10464:             $version=pop(@file_parts);
10465:         }
10466:         $name=join('.',@file_parts);
10467:     } else {
10468:         $name=join('.',@file_parts);
10469:     }
10470:     return($name,$version,$ext);
10471: }
10472: 
10473: #----------------------------------------------Get portfolio file permissions
10474: 
10475: sub get_portfile_permissions {
10476:     my ($domain,$user) = @_;
10477:     my %current_permissions = &dump('file_permissions',$domain,$user);
10478:     my ($tmp)=keys(%current_permissions);
10479:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10480:     return \%current_permissions;
10481: }
10482: 
10483: #---------------------------------------------Get portfolio file access controls
10484: 
10485: sub get_access_controls {
10486:     my ($current_permissions,$group,$file) = @_;
10487:     my %access;
10488:     my $real_file = $file;
10489:     $file =~ s/\.meta$//;
10490:     if (defined($file)) {
10491:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10492:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10493:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10494:             }
10495:         }
10496:     } else {
10497:         foreach my $key (keys(%{$current_permissions})) {
10498:             if ($key =~ /\0accesscontrol$/) {
10499:                 if (defined($group)) {
10500:                     if ($key !~ m-^\Q$group\E/-) {
10501:                         next;
10502:                     }
10503:                 }
10504:                 my ($fullpath) = split(/\0/,$key);
10505:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10506:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10507:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10508:                     }
10509:                 }
10510:             }
10511:         }
10512:     }
10513:     return %access;
10514: }
10515: 
10516: sub modify_access_controls {
10517:     my ($file_name,$changes,$domain,$user)=@_;
10518:     my ($outcome,$deloutcome);
10519:     my %store_permissions;
10520:     my %new_values;
10521:     my %new_control;
10522:     my %translation;
10523:     my @deletions = ();
10524:     my $now = time;
10525:     if (exists($$changes{'activate'})) {
10526:         if (ref($$changes{'activate'}) eq 'HASH') {
10527:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10528:             my $numnew = scalar(@newitems);
10529:             for (my $i=0; $i<$numnew; $i++) {
10530:                 my $newkey = $newitems[$i];
10531:                 my $newid = &Apache::loncommon::get_cgi_id();
10532:                 if ($newkey =~ /^\d+:/) { 
10533:                     $newkey =~ s/^(\d+)/$newid/;
10534:                     $translation{$1} = $newid;
10535:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10536:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10537:                     $translation{$1} = $newid;
10538:                 }
10539:                 $new_values{$file_name."\0".$newkey} = 
10540:                                           $$changes{'activate'}{$newitems[$i]};
10541:                 $new_control{$newkey} = $now;
10542:             }
10543:         }
10544:     }
10545:     my %todelete;
10546:     my %changed_items;
10547:     foreach my $action ('delete','update') {
10548:         if (exists($$changes{$action})) {
10549:             if (ref($$changes{$action}) eq 'HASH') {
10550:                 foreach my $key (keys(%{$$changes{$action}})) {
10551:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10552:                     if ($action eq 'delete') { 
10553:                         $todelete{$itemnum} = 1;
10554:                     } else {
10555:                         $changed_items{$itemnum} = $key;
10556:                     }
10557:                 }
10558:             }
10559:         }
10560:     }
10561:     # get lock on access controls for file.
10562:     my $lockhash = {
10563:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10564:                                                        ':'.$env{'user.domain'},
10565:                    }; 
10566:     my $tries = 0;
10567:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10568:    
10569:     while (($gotlock ne 'ok') && $tries < 10) {
10570:         $tries ++;
10571:         sleep(0.1);
10572:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10573:     }
10574:     if ($gotlock eq 'ok') {
10575:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10576:         my ($tmp)=keys(%curr_permissions);
10577:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10578:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10579:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10580:             if (ref($curr_controls) eq 'HASH') {
10581:                 foreach my $control_item (keys(%{$curr_controls})) {
10582:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10583:                     if (defined($todelete{$itemnum})) {
10584:                         push(@deletions,$file_name."\0".$control_item);
10585:                     } else {
10586:                         if (defined($changed_items{$itemnum})) {
10587:                             $new_control{$changed_items{$itemnum}} = $now;
10588:                             push(@deletions,$file_name."\0".$control_item);
10589:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10590:                         } else {
10591:                             $new_control{$control_item} = $$curr_controls{$control_item};
10592:                         }
10593:                     }
10594:                 }
10595:             }
10596:         }
10597:         my ($group);
10598:         if (&is_course($domain,$user)) {
10599:             ($group,my $file) = split(/\//,$file_name,2);
10600:         }
10601:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10602:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10603:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10604:         #  remove lock
10605:         my @del_lock = ($file_name."\0".'locked_access_records');
10606:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10607:         my $sqlresult =
10608:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10609:                                     $group);
10610:     } else {
10611:         $outcome = "error: could not obtain lockfile\n";  
10612:     }
10613:     return ($outcome,$deloutcome,\%new_values,\%translation);
10614: }
10615: 
10616: sub make_public_indefinitely {
10617:     my (@requrl) = @_;
10618:     return &automated_portfile_access('public',\@requrl);
10619: }
10620: 
10621: sub automated_portfile_access {
10622:     my ($accesstype,$addsref,$delsref,$info) = @_;
10623:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10624:         return 'invalid';
10625:     }
10626:     my %urls;
10627:     if (ref($addsref) eq 'ARRAY') {
10628:         foreach my $requrl (@{$addsref}) {
10629:             if (&is_portfolio_url($requrl)) {
10630:                 unless (exists($urls{$requrl})) {
10631:                     $urls{$requrl} = 'add';
10632:                 }
10633:             }
10634:         }
10635:     }
10636:     if (ref($delsref) eq 'ARRAY') {
10637:         foreach my $requrl (@{$delsref}) { 
10638:             if (&is_portfolio_url($requrl)) {
10639:                 unless (exists($urls{$requrl})) {
10640:                     $urls{$requrl} = 'delete'; 
10641:                 }
10642:             }
10643:         }
10644:     }
10645:     unless (keys(%urls)) {
10646:         return 'invalid';
10647:     }
10648:     my $ip;
10649:     if ($accesstype eq 'ip') {
10650:         if (ref($info) eq 'HASH') {
10651:             if ($info->{'ip'} ne '') {
10652:                 $ip = $info->{'ip'};
10653:             }
10654:         }
10655:         if ($ip eq '') {
10656:             return 'invalid';
10657:         }
10658:     }
10659:     my $errors;
10660:     my $now = time;
10661:     my %current_perms;
10662:     foreach my $requrl (sort(keys(%urls))) {
10663:         my $action;
10664:         if ($urls{$requrl} eq 'add') {
10665:             $action = 'activate';
10666:         } else {
10667:             $action = 'none';
10668:         }
10669:         my $aclnum = 0;
10670:         my (undef,$udom,$unum,$file_name,$group) =
10671:             &parse_portfolio_url($requrl);
10672:         unless (exists($current_perms{$unum.':'.$udom})) {
10673:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10674:         }
10675:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10676:                                                    $group,$file_name);
10677:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10678:             my ($num,$scope,$end,$start) = 
10679:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10680:             if ($scope eq $accesstype) {
10681:                 if (($start <= $now) && ($end == 0)) {
10682:                     if ($accesstype eq 'ip') {
10683:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10684:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10685:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10686:                                     if ($urls{$requrl} eq 'add') {
10687:                                         $action = 'none';
10688:                                         last;
10689:                                     } else {
10690:                                         $action = 'delete';
10691:                                         $aclnum = $num;
10692:                                         last;
10693:                                     }
10694:                                 }
10695:                             }
10696:                         }
10697:                     } elsif ($accesstype eq 'public') {
10698:                         if ($urls{$requrl} eq 'add') {
10699:                             $action = 'none';
10700:                             last;
10701:                         } else {
10702:                             $action = 'delete';
10703:                             $aclnum = $num;
10704:                             last;
10705:                         }
10706:                     }
10707:                 } elsif ($accesstype eq 'public') {
10708:                     $action = 'update';
10709:                     $aclnum = $num;
10710:                     last;
10711:                 }
10712:             }
10713:         }
10714:         if ($action eq 'none') {
10715:             next;
10716:         } else {
10717:             my %changes;
10718:             my $newend = 0;
10719:             my $newstart = $now;
10720:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10721:             $changes{$action}{$newkey} = {
10722:                 type => $accesstype,
10723:                 time => {
10724:                     start => $newstart,
10725:                     end   => $newend,
10726:                 },
10727:             };
10728:             if ($accesstype eq 'ip') {
10729:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10730:             }
10731:             my ($outcome,$deloutcome,$new_values,$translation) =
10732:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10733:             unless ($outcome eq 'ok') {
10734:                 $errors .= $outcome.' ';
10735:             }
10736:         }
10737:     }
10738:     if ($errors) {
10739:         $errors =~ s/\s$//;
10740:         return $errors;
10741:     } else {
10742:         return 'ok';
10743:     }
10744: }
10745: 
10746: #------------------------------------------------------Get Marked as Read Only
10747: 
10748: sub get_marked_as_readonly {
10749:     my ($domain,$user,$what,$group) = @_;
10750:     my $current_permissions = &get_portfile_permissions($domain,$user);
10751:     my @readonly_files;
10752:     my $cmp1=$what;
10753:     if (ref($what)) { $cmp1=join('',@{$what}) };
10754:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10755:         if (defined($group)) {
10756:             if ($file_name !~ m-^\Q$group\E/-) {
10757:                 next;
10758:             }
10759:         }
10760:         if (ref($value) eq "ARRAY"){
10761:             foreach my $stored_what (@{$value}) {
10762:                 my $cmp2=$stored_what;
10763:                 if (ref($stored_what) eq 'ARRAY') {
10764:                     $cmp2=join('',@{$stored_what});
10765:                 }
10766:                 if ($cmp1 eq $cmp2) {
10767:                     push(@readonly_files, $file_name);
10768:                     last;
10769:                 } elsif (!defined($what)) {
10770:                     push(@readonly_files, $file_name);
10771:                     last;
10772:                 }
10773:             }
10774:         }
10775:     }
10776:     return @readonly_files;
10777: }
10778: #-----------------------------------------------------------Get Marked as Read Only Hash
10779: 
10780: sub get_marked_as_readonly_hash {
10781:     my ($current_permissions,$group,$what) = @_;
10782:     my %readonly_files;
10783:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10784:         if (defined($group)) {
10785:             if ($file_name !~ m-^\Q$group\E/-) {
10786:                 next;
10787:             }
10788:         }
10789:         if (ref($value) eq "ARRAY"){
10790:             foreach my $stored_what (@{$value}) {
10791:                 if (ref($stored_what) eq 'ARRAY') {
10792:                     foreach my $lock_descriptor(@{$stored_what}) {
10793:                         if ($lock_descriptor eq 'graded') {
10794:                             $readonly_files{$file_name} = 'graded';
10795:                         } elsif ($lock_descriptor eq 'handback') {
10796:                             $readonly_files{$file_name} = 'handback';
10797:                         } else {
10798:                             if (!exists($readonly_files{$file_name})) {
10799:                                 $readonly_files{$file_name} = 'locked';
10800:                             }
10801:                         }
10802:                     }
10803:                 } 
10804:             }
10805:         } 
10806:     }
10807:     return %readonly_files;
10808: }
10809: # ------------------------------------------------------------ Unmark as Read Only
10810: 
10811: sub unmark_as_readonly {
10812:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10813:     # for portfolio submissions, $what contains [$symb,$crsid] 
10814:     my ($domain,$user,$what,$file_name,$group) = @_;
10815:     $file_name = &declutter_portfile($file_name);
10816:     my $symb_crs = $what;
10817:     if (ref($what)) { $symb_crs=join('',@$what); }
10818:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10819:     my ($tmp)=keys(%current_permissions);
10820:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10821:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10822:     foreach my $file (@readonly_files) {
10823: 	my $clean_file = &declutter_portfile($file);
10824: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10825: 	my $current_locks = $current_permissions{$file};
10826:         my @new_locks;
10827:         my @del_keys;
10828:         if (ref($current_locks) eq "ARRAY"){
10829:             foreach my $locker (@{$current_locks}) {
10830:                 my $compare=$locker;
10831:                 if (ref($locker) eq 'ARRAY') {
10832:                     $compare=join('',@{$locker});
10833:                     if ($compare ne $symb_crs) {
10834:                         push(@new_locks, $locker);
10835:                     }
10836:                 }
10837:             }
10838:             if (scalar(@new_locks) > 0) {
10839:                 $current_permissions{$file} = \@new_locks;
10840:             } else {
10841:                 push(@del_keys, $file);
10842:                 &del('file_permissions',\@del_keys, $domain, $user);
10843:                 delete($current_permissions{$file});
10844:             }
10845:         }
10846:     }
10847:     &put('file_permissions',\%current_permissions,$domain,$user);
10848:     return;
10849: }
10850: 
10851: # ------------------------------------------------------------ Directory lister
10852: 
10853: sub dirlist {
10854:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10855:     $uri=~s/^\///;
10856:     $uri=~s/\/$//;
10857:     my ($udom, $uname);
10858:     if ($getuserdir) {
10859:         $udom = $userdomain;
10860:         $uname = $username;
10861:     } else {
10862:         (undef,$udom,$uname)=split(/\//,$uri);
10863:         if(defined($userdomain)) {
10864:             $udom = $userdomain;
10865:         }
10866:         if(defined($username)) {
10867:             $uname = $username;
10868:         }
10869:     }
10870:     my ($dirRoot,$listing,@listing_results);
10871: 
10872:     $dirRoot = $perlvar{'lonDocRoot'};
10873:     if (defined($getpropath)) {
10874:         $dirRoot = &propath($udom,$uname);
10875:         $dirRoot =~ s/\/$//;
10876:     } elsif (defined($getuserdir)) {
10877:         my $subdir=$uname.'__';
10878:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10879:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10880:                    ."/$udom/$subdir/$uname";
10881:     } elsif (defined($alternateRoot)) {
10882:         $dirRoot = $alternateRoot;
10883:     }
10884: 
10885:     if($udom) {
10886:         if($uname) {
10887:             my $uhome = &homeserver($uname,$udom);
10888:             if ($uhome eq 'no_host') {
10889:                 return ([],'no_host');
10890:             }
10891:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10892:                               .$getuserdir.':'.&escape($dirRoot)
10893:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10894:             if ($listing eq 'unknown_cmd') {
10895:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10896:             } else {
10897:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10898:             }
10899:             if ($listing eq 'unknown_cmd') {
10900:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10901:                 @listing_results = split(/:/,$listing);
10902:             } else {
10903:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10904:             }
10905:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10906:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10907:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10908:                 return ([],$listing);
10909:             } else {
10910:                 return (\@listing_results);
10911:             }
10912:         } elsif(!$alternateRoot) {
10913:             my (%allusers,%listerror);
10914: 	    my %servers = &get_servers($udom,'library');
10915:  	    foreach my $tryserver (keys(%servers)) {
10916:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10917:                                   &escape($udom),$tryserver);
10918:                 if ($listing eq 'unknown_cmd') {
10919: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10920: 				      $udom, $tryserver);
10921:                 } else {
10922:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10923:                 }
10924: 		if ($listing eq 'unknown_cmd') {
10925: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10926: 				      $udom, $tryserver);
10927: 		    @listing_results = split(/:/,$listing);
10928: 		} else {
10929: 		    @listing_results =
10930: 			map { &unescape($_); } split(/:/,$listing);
10931: 		}
10932:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10933:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10934:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10935:                     $listerror{$tryserver} = $listing;
10936:                 } else {
10937: 		    foreach my $line (@listing_results) {
10938: 			my ($entry) = split(/&/,$line,2);
10939: 			$allusers{$entry} = 1;
10940: 		    }
10941: 		}
10942:             }
10943:             my @alluserslist=();
10944:             foreach my $user (sort(keys(%allusers))) {
10945:                 push(@alluserslist,$user.'&user');
10946:             }
10947: 
10948:             if (!%listerror) {
10949:                 # no errors
10950:                 return (\@alluserslist);
10951:             } elsif (scalar(keys(%servers)) == 1) {
10952:                 # one library server, one error 
10953:                 my ($key) = keys(%listerror);
10954:                 return (\@alluserslist, $listerror{$key});
10955:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10956:                 # con_lost indicates that we might miss data from at least one
10957:                 # library server
10958:                 return (\@alluserslist, 'con_lost');
10959:             } else {
10960:                 # multiple library servers and no con_lost -> data should be
10961:                 # complete. 
10962:                 return (\@alluserslist);
10963:             }
10964: 
10965:         } else {
10966:             return ([],'missing username');
10967:         }
10968:     } elsif(!defined($getpropath)) {
10969:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10970:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10971:         return (\@all_domains);
10972:     } else {
10973:         return ([],'missing domain');
10974:     }
10975: }
10976: 
10977: # --------------------------------------------- GetFileTimestamp
10978: # This function utilizes dirlist and returns the date stamp for
10979: # when it was last modified.  It will also return an error of -1
10980: # if an error occurs
10981: 
10982: sub GetFileTimestamp {
10983:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10984:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10985:     $studentName   = &LONCAPA::clean_username($studentName);
10986:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10987:                                     undef,$getuserdir);
10988:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10989:         return -1;
10990:     }
10991:     if (ref($fileref) eq 'ARRAY') {
10992:         my @stats = split('&',$fileref->[0]);
10993:         # @stats contains first the filename, then the stat output
10994:         return $stats[10]; # so this is 10 instead of 9.
10995:     } else {
10996:         return -1;
10997:     }
10998: }
10999: 
11000: sub stat_file {
11001:     my ($uri) = @_;
11002:     $uri = &clutter_with_no_wrapper($uri);
11003: 
11004:     my ($udom,$uname,$file);
11005:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11006: 	($udom,$uname,$file) =
11007: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11008: 	$file = 'userfiles/'.$file;
11009:     }
11010:     if ($uri =~ m-^/res/-) {
11011: 	($udom,$uname) = 
11012: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11013: 	$file = $uri;
11014:     }
11015: 
11016:     if (!$udom || !$uname || !$file) {
11017: 	# unable to handle the uri
11018: 	return ();
11019:     }
11020:     my $getpropath;
11021:     if ($file =~ /^userfiles\//) {
11022:         $getpropath = 1;
11023:     }
11024:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11025:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11026:         return ();
11027:     } else {
11028:         if (ref($listref) eq 'ARRAY') {
11029:             my @stats = split('&',$listref->[0]);
11030: 	    shift(@stats); #filename is first
11031: 	    return @stats;
11032:         }
11033:     }
11034:     return ();
11035: }
11036: 
11037: # --------------------------------------------------------- recursedirs
11038: # Recursive function to traverse either a specific user's Authoring Space
11039: # or corresponding Published Resource Space, and populate the hash ref:
11040: # $dirhashref with URLs of all directories, and if $filehashref hash
11041: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11042: # or .rights files in resource space, and .meta, .save, .log, and .bak
11043: # files in Authoring Space.
11044: #
11045: # Inputs:
11046: #
11047: # $is_home - true if current server is home server for user's space
11048: # $context - either: priv, or res respectively for Authoring or Resource Space.
11049: # $docroot - Document root (i.e., /home/httpd/html
11050: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11051: # $relpath - Current path (relative to top level).
11052: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11053: # $filehashref - reference to hash to populate with URLs of files (Optional)
11054: #
11055: # Returns: nothing
11056: #
11057: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11058: #
11059: # Currently used by interface/londocs.pm to create linked select boxes for
11060: # directory and filename to import a Course "Author" resource into a course, and
11061: # also to create linked select boxes for Authoring Space and Directory to choose
11062: # save location for creation of a new "standard" problem from the Course Editor.
11063: #
11064: 
11065: sub recursedirs {
11066:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11067:     return unless (ref($dirhashref) eq 'HASH');
11068:     my $currpath = $docroot.$toppath;
11069:     if ($relpath) {
11070:         $currpath .= "/$relpath";
11071:     }
11072:     my $savefile;
11073:     if (ref($filehashref)) {
11074:         $savefile = 1;
11075:     }
11076:     if ($is_home) {
11077:         if (opendir(my $dirh,$currpath)) {
11078:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11079:                 next if ($item eq '');
11080:                 if (-d "$currpath/$item") {
11081:                     my $newpath;
11082:                     if ($relpath) {
11083:                         $newpath = "$relpath/$item";
11084:                     } else {
11085:                         $newpath = $item;
11086:                     }
11087:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11088:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11089:                 } elsif ($savefile) {
11090:                     if ($context eq 'priv') {
11091:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11092:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11093:                         }
11094:                     } else {
11095:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11096:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11097:                         }
11098:                     }
11099:                 }
11100:             }
11101:             closedir($dirh);
11102:         }
11103:     } else {
11104:         my ($dirlistref,$listerror) =
11105:             &dirlist($toppath.$relpath);
11106:         my @dir_lines;
11107:         my $dirptr=16384;
11108:         if (ref($dirlistref) eq 'ARRAY') {
11109:             foreach my $dir_line (sort
11110:                               {
11111:                                   my ($afile)=split('&',$a,2);
11112:                                   my ($bfile)=split('&',$b,2);
11113:                                   return (lc($afile) cmp lc($bfile));
11114:                               } (@{$dirlistref})) {
11115:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11116:                     split(/\&/,$dir_line,16);
11117:                 $item =~ s/\s+$//;
11118:                 next if (($item =~ /^\.\.?$/) || ($obs));
11119:                 if ($dirptr&$testdir) {
11120:                     my $newpath;
11121:                     if ($relpath) {
11122:                         $newpath = "$relpath/$item";
11123:                     } else {
11124:                         $relpath = '/';
11125:                         $newpath = $item;
11126:                     }
11127:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11128:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11129:                 } elsif ($savefile) {
11130:                     if ($context eq 'priv') {
11131:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11132:                             $filehashref->{$relpath}{$item} = 1;
11133:                         }
11134:                     } else {
11135:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11136:                             $filehashref->{$relpath}{$item} = 1;
11137:                         }
11138:                     }
11139:                 }
11140:             }
11141:         }
11142:     }
11143:     return;
11144: }
11145: 
11146: # -------------------------------------------------------- Value of a Condition
11147: 
11148: # gets the value of a specific preevaluated condition
11149: #    stored in the string  $env{user.state.<cid>}
11150: # or looks up a condition reference in the bighash and if if hasn't
11151: # already been evaluated recurses into docondval to get the value of
11152: # the condition, then memoizing it to 
11153: #   $env{user.state.<cid>.<condition>}
11154: sub directcondval {
11155:     my $number=shift;
11156:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11157: 	&Apache::lonuserstate::evalstate();
11158:     }
11159:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11160: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11161:     } elsif ($number =~ /^_/) {
11162: 	my $sub_condition;
11163: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11164: 		&GDBM_READER(),0640)) {
11165: 	    $sub_condition=$bighash{'conditions'.$number};
11166: 	    untie(%bighash);
11167: 	}
11168: 	my $value = &docondval($sub_condition);
11169: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11170: 	return $value;
11171:     }
11172:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11173:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11174:     } else {
11175:        return 2;
11176:     }
11177: }
11178: 
11179: # get the collection of conditions for this resource
11180: sub condval {
11181:     my $condidx=shift;
11182:     my $allpathcond='';
11183:     foreach my $cond (split(/\|/,$condidx)) {
11184: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11185: 	    $allpathcond.=
11186: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11187: 	}
11188:     }
11189:     $allpathcond=~s/\|$//;
11190:     return &docondval($allpathcond);
11191: }
11192: 
11193: #evaluates an expression of conditions
11194: sub docondval {
11195:     my ($allpathcond) = @_;
11196:     my $result=0;
11197:     if ($env{'request.course.id'}
11198: 	&& defined($allpathcond)) {
11199: 	my $operand='|';
11200: 	my @stack;
11201: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11202: 	    if ($chunk eq '(') {
11203: 		push @stack,($operand,$result);
11204: 	    } elsif ($chunk eq ')') {
11205: 		my $before=pop @stack;
11206: 		if (pop @stack eq '&') {
11207: 		    $result=$result>$before?$before:$result;
11208: 		} else {
11209: 		    $result=$result>$before?$result:$before;
11210: 		}
11211: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11212: 		$operand=$chunk;
11213: 	    } else {
11214: 		my $new=directcondval($chunk);
11215: 		if ($operand eq '&') {
11216: 		    $result=$result>$new?$new:$result;
11217: 		} else {
11218: 		    $result=$result>$new?$result:$new;
11219: 		}
11220: 	    }
11221: 	}
11222:     }
11223:     return $result;
11224: }
11225: 
11226: # ---------------------------------------------------- Devalidate courseresdata
11227: 
11228: sub devalidatecourseresdata {
11229:     my ($coursenum,$coursedomain)=@_;
11230:     my $hashid=$coursenum.':'.$coursedomain;
11231:     &devalidate_cache_new('courseres',$hashid);
11232: }
11233: 
11234: 
11235: # --------------------------------------------------- Course Resourcedata Query
11236: #
11237: #  Parameters:
11238: #      $coursenum    - Number of the course.
11239: #      $coursedomain - Domain at which the course was created.
11240: #  Returns:
11241: #     A hash of the course parameters along (I think) with timestamps
11242: #     and version info.
11243: 
11244: sub get_courseresdata {
11245:     my ($coursenum,$coursedomain)=@_;
11246:     my $coursehom=&homeserver($coursenum,$coursedomain);
11247:     my $hashid=$coursenum.':'.$coursedomain;
11248:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11249:     my %dumpreply;
11250:     unless (defined($cached)) {
11251: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11252: 	$result=\%dumpreply;
11253: 	my ($tmp) = keys(%dumpreply);
11254: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11255: 	    &do_cache_new('courseres',$hashid,$result,600);
11256: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11257: 	    return $tmp;
11258: 	} elsif ($tmp =~ /^(error)/) {
11259: 	    $result=undef;
11260: 	    &do_cache_new('courseres',$hashid,$result,600);
11261: 	}
11262:     }
11263:     return $result;
11264: }
11265: 
11266: sub devalidateuserresdata {
11267:     my ($uname,$udom)=@_;
11268:     my $hashid="$udom:$uname";
11269:     &devalidate_cache_new('userres',$hashid);
11270: }
11271: 
11272: sub get_userresdata {
11273:     my ($uname,$udom)=@_;
11274:     #most student don\'t have any data set, check if there is some data
11275:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11276: 
11277:     my $hashid="$udom:$uname";
11278:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11279:     if (!defined($cached)) {
11280: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11281: 	$result=\%resourcedata;
11282: 	&do_cache_new('userres',$hashid,$result,600);
11283:     }
11284:     my ($tmp)=keys(%$result);
11285:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11286: 	return $result;
11287:     }
11288:     #error 2 occurs when the .db doesn't exist
11289:     if ($tmp!~/error: 2 /) {
11290:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11291: 	    &logthis("<font color=\"blue\">WARNING:".
11292: 		     " Trying to get resource data for ".
11293: 		     $uname." at ".$udom.": ".
11294: 		     $tmp."</font>");
11295:         }
11296:     } elsif ($tmp=~/error: 2 /) {
11297: 	#&EXT_cache_set($udom,$uname);
11298: 	&do_cache_new('userres',$hashid,undef,600);
11299: 	undef($tmp); # not really an error so don't send it back
11300:     }
11301:     return $tmp;
11302: }
11303: #----------------------------------------------- resdata - return resource data
11304: #  Purpose:
11305: #    Return resource data for either users or for a course.
11306: #  Parameters:
11307: #     $name      - Course/user name.
11308: #     $domain    - Name of the domain the user/course is registered on.
11309: #     $type      - Type of thing $name is (must be 'course' or 'user')
11310: #     $mapp      - decluttered URL of enclosing map  
11311: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11312: #     $recurseup - Ref to array of map URLs, starting with map containing
11313: #                  $mapp up through hierarchy of nested maps to top level map.  
11314: #     $courseid  - CourseID (first part of param identifier).
11315: #     $modifier  - Middle part of param identifier.
11316: #     $what      - Last part of param identifier.
11317: #     @which     - Array of names of resources desired.
11318: #  Returns:
11319: #     The value of the first reasource in @which that is found in the
11320: #     resource hash.
11321: #  Exceptional Conditions:
11322: #     If the $type passed in is not valid (not the string 'course' or 
11323: #     'user', an undefined  reference is returned.
11324: #     If none of the resources are found, an undef is returned
11325: sub resdata {
11326:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11327:         $modifier,$what,@which)=@_;
11328:     my $result;
11329:     if ($type eq 'course') {
11330: 	$result=&get_courseresdata($name,$domain);
11331:     } elsif ($type eq 'user') {
11332: 	$result=&get_userresdata($name,$domain);
11333:     }
11334:     if (!ref($result)) { return $result; }    
11335:     foreach my $item (@which) {
11336:         if ($item->[1] eq 'course') {
11337:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11338:                 unless ($$recursed) {
11339:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11340:                     $$recursed = 1;
11341:                 }
11342:                 foreach my $item (@${recurseup}) {
11343:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11344:                     last if (defined($result->{$norecursechk}));
11345:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11346:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11347:                 }
11348:             }
11349:         }
11350:         if (defined($result->{$item->[0]})) {
11351: 	    return [$result->{$item->[0]},$item->[1]];
11352: 	}
11353:     }
11354:     return undef;
11355: }
11356: 
11357: sub get_domain_lti {
11358:     my ($cdom,$context) = @_;
11359:     my ($name,%lti);
11360:     if ($context eq 'consumer') {
11361:         $name = 'ltitools';
11362:     } elsif ($context eq 'provider') {
11363:         $name = 'lti';
11364:     } else {
11365:         return %lti;
11366:     }
11367:     my ($result,$cached)=&is_cached_new($name,$cdom);
11368:     if (defined($cached)) {
11369:         if (ref($result) eq 'HASH') {
11370:             %lti = %{$result};
11371:         }
11372:     } else {
11373:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11374:         if (ref($domconfig{$name}) eq 'HASH') {
11375:             %lti = %{$domconfig{$name}};
11376:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11377:             if (ref($encdomconfig{$name}) eq 'HASH') {
11378:                 foreach my $id (keys(%lti)) {
11379:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11380:                         foreach my $item ('key','secret') {
11381:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11382:                         }
11383:                     }
11384:                 }
11385:             }
11386:         }
11387:         my $cachetime = 24*60*60;
11388:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11389:     }
11390:     return %lti;
11391: }
11392: 
11393: sub get_numsuppfiles {
11394:     my ($cnum,$cdom,$ignorecache)=@_;
11395:     my $hashid=$cnum.':'.$cdom;
11396:     my ($suppcount,$cached);
11397:     unless ($ignorecache) {
11398:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11399:     }
11400:     unless (defined($cached)) {
11401:         my $chome=&homeserver($cnum,$cdom);
11402:         unless ($chome eq 'no_host') {
11403:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11404:             my $suppmap = 'supplemental.sequence';
11405:             ($suppcount,$supptools,$errors) =
11406:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11407:                                                          $supptools,$errors);
11408:         }
11409:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11410:     }
11411:     return $suppcount;
11412: }
11413: 
11414: #
11415: # EXT resource caching routines
11416: #
11417: 
11418: {
11419: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11420: #
11421: # The course for which we cache
11422: my $cachedmapkey='';
11423: # The cached recursive maps for this course
11424: my %cachedmaps=();
11425: # When this was last done
11426: my $cachedmaptime='';
11427: 
11428: sub clear_EXT_cache_status {
11429:     &delenv('cache.EXT.');
11430: }
11431: 
11432: sub EXT_cache_status {
11433:     my ($target_domain,$target_user) = @_;
11434:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11435:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11436:         # We know already the user has no data
11437:         return 1;
11438:     } else {
11439:         return 0;
11440:     }
11441: }
11442: 
11443: sub EXT_cache_set {
11444:     my ($target_domain,$target_user) = @_;
11445:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11446:     #&appenv({$cachename => time});
11447: }
11448: 
11449: # --------------------------------------------------------- Value of a Variable
11450: sub EXT {
11451: 
11452:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11453:     unless ($varname) { return ''; }
11454:     #get real user name/domain, courseid and symb
11455:     my $courseid;
11456:     my $publicuser;
11457:     if ($symbparm) {
11458: 	$symbparm=&get_symb_from_alias($symbparm);
11459:     }
11460:     if (!($uname && $udom)) {
11461:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11462:       if (!$symbparm) {	$symbparm=$cursymb; }
11463:     } else {
11464: 	$courseid=$env{'request.course.id'};
11465:     }
11466:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11467:     my $rest;
11468:     if (defined($therest[0])) {
11469:        $rest=join('.',@therest);
11470:     } else {
11471:        $rest='';
11472:     }
11473: 
11474:     my $qualifierrest=$qualifier;
11475:     if ($rest) { $qualifierrest.='.'.$rest; }
11476:     my $spacequalifierrest=$space;
11477:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11478:     if ($realm eq 'user') {
11479: # --------------------------------------------------------------- user.resource
11480: 	if ($space eq 'resource') {
11481: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11482: 		  || defined($Apache::lonhomework::parsing_a_task))
11483: 		 &&
11484: 		 ($symbparm eq &symbread()) ) {	
11485: 		# if we are in the middle of processing the resource the
11486: 		# get the value we are planning on committing
11487:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11488:                     return $Apache::lonhomework::results{$qualifierrest};
11489:                 } else {
11490:                     return $Apache::lonhomework::history{$qualifierrest};
11491:                 }
11492: 	    } else {
11493: 		my %restored;
11494: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11495: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11496: 		} else {
11497: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11498: 		}
11499: 		return $restored{$qualifierrest};
11500: 	    }
11501: # ----------------------------------------------------------------- user.access
11502:         } elsif ($space eq 'access') {
11503: 	    # FIXME - not supporting calls for a specific user
11504:             return &allowed($qualifier,$rest);
11505: # ------------------------------------------ user.preferences, user.environment
11506:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11507: 	    if (($uname eq $env{'user.name'}) &&
11508: 		($udom eq $env{'user.domain'})) {
11509: 		return $env{join('.',('environment',$qualifierrest))};
11510: 	    } else {
11511: 		my %returnhash;
11512: 		if (!$publicuser) {
11513: 		    %returnhash=&userenvironment($udom,$uname,
11514: 						 $qualifierrest);
11515: 		}
11516: 		return $returnhash{$qualifierrest};
11517: 	    }
11518: # ----------------------------------------------------------------- user.course
11519:         } elsif ($space eq 'course') {
11520: 	    # FIXME - not supporting calls for a specific user
11521:             return $env{join('.',('request.course',$qualifier))};
11522: # ------------------------------------------------------------------- user.role
11523:         } elsif ($space eq 'role') {
11524: 	    # FIXME - not supporting calls for a specific user
11525:             my ($role,$where)=split(/\./,$env{'request.role'});
11526:             if ($qualifier eq 'value') {
11527: 		return $role;
11528:             } elsif ($qualifier eq 'extent') {
11529:                 return $where;
11530:             }
11531: # ----------------------------------------------------------------- user.domain
11532:         } elsif ($space eq 'domain') {
11533:             return $udom;
11534: # ------------------------------------------------------------------- user.name
11535:         } elsif ($space eq 'name') {
11536:             return $uname;
11537: # ---------------------------------------------------- Any other user namespace
11538:         } else {
11539: 	    my %reply;
11540: 	    if (!$publicuser) {
11541: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11542: 	    }
11543: 	    return $reply{$qualifierrest};
11544:         }
11545:     } elsif ($realm eq 'query') {
11546: # ---------------------------------------------- pull stuff out of query string
11547:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11548: 						[$spacequalifierrest]);
11549: 	return $env{'form.'.$spacequalifierrest}; 
11550:    } elsif ($realm eq 'request') {
11551: # ------------------------------------------------------------- request.browser
11552:         if ($space eq 'browser') {
11553:             return $env{'browser.'.$qualifier};
11554: # ------------------------------------------------------------ request.filename
11555:         } else {
11556:             return $env{'request.'.$spacequalifierrest};
11557:         }
11558:     } elsif ($realm eq 'course') {
11559: # ---------------------------------------------------------- course.description
11560:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11561:     } elsif ($realm eq 'resource') {
11562: 
11563: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11564: 	    if (!$symbparm) { $symbparm=&symbread(); }
11565: 	}
11566: 
11567:         if ($qualifier eq '') {
11568: 	    if ($space eq 'title') {
11569: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11570: 	        return &gettitle($symbparm);
11571: 	    }
11572: 	
11573: 	    if ($space eq 'map') {
11574: 	        my ($map) = &decode_symb($symbparm);
11575: 	        return &symbread($map);
11576: 	    }
11577:             if ($space eq 'maptitle') {
11578:                 my ($map) = &decode_symb($symbparm);
11579:                 return &gettitle($map);
11580:             }
11581: 	    if ($space eq 'filename') {
11582: 	        if ($symbparm) {
11583: 		    return &clutter((&decode_symb($symbparm))[2]);
11584: 	        }
11585: 	        return &hreflocation('',$env{'request.filename'});
11586: 	    }
11587: 
11588:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11589:                 if ($space eq 'visibleparts') {
11590:                     my $navmap = Apache::lonnavmaps::navmap->new();
11591:                     my $item;
11592:                     if (ref($navmap)) {
11593:                         my $res = $navmap->getBySymb($symbparm);
11594:                         my $parts = $res->parts();
11595:                         if (ref($parts) eq 'ARRAY') {
11596:                             $item = join(',',@{$parts});
11597:                         }
11598:                         undef($navmap);
11599:                     }
11600:                     return $item;
11601:                 }
11602:             }
11603:         }
11604: 
11605: 	my ($section, $group, @groups, @recurseup, $recursed);
11606: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11607:         if (($courseid eq '') && ($cid)) {
11608:             $courseid = $cid;
11609:         }
11610: 	if (($symbparm && $courseid) && 
11611: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11612: 
11613: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11614: 
11615: # ----------------------------------------------------- Cascading lookup scheme
11616: 	    my $symbp=$symbparm;
11617: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11618: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11619:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11620: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11621: 	    if (($env{'user.name'} eq $uname) &&
11622: 		($env{'user.domain'} eq $udom)) {
11623: 		$section=$env{'request.course.sec'};
11624:                 @groups = split(/:/,$env{'request.course.groups'});  
11625:                 @groups=&sort_course_groups($courseid,@groups); 
11626: 	    } else {
11627: 		if (! defined($usection)) {
11628: 		    $section=&getsection($udom,$uname,$courseid);
11629: 		} else {
11630: 		    $section = $usection;
11631: 		}
11632:                 @groups = &get_users_groups($udom,$uname,$courseid);
11633: 	    }
11634: 
11635: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11636: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11637:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11638: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11639: 
11640: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11641: 	    my $courselevelr=$courseid.'.'.$symbparm;
11642:             $courseleveli=$courseid.'.'.$recurseparm;
11643: 	    $courselevelm=$courseid.'.'.$mapparm;
11644: 
11645: # ----------------------------------------------------------- first, check user
11646: 
11647: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11648:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11649: 				       ([$courselevelr,'resource'],
11650: 					[$courselevelm,'map'     ],
11651:                                         [$courseleveli,'map'     ],
11652: 					[$courselevel, 'course'  ]));
11653: 	    if (defined($userreply)) { return &get_reply($userreply); }
11654: 
11655: # ------------------------------------------------ second, check some of course
11656:             my $coursereply;
11657:             if (@groups > 0) {
11658:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11659:                                        $recurseparm,$mapparm,$spacequalifierrest,
11660:                                        $mapp,\$recursed,\@recurseup);
11661:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11662:             }
11663: 
11664: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11665: 				  $env{'course.'.$courseid.'.domain'},
11666: 				  'course',$mapp,\$recursed,\@recurseup,
11667:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11668: 				  ([$seclevelr,   'resource'],
11669: 				   [$seclevelm,   'map'     ],
11670:                                    [$secleveli,   'map'     ],
11671: 				   [$seclevel,    'course'  ],
11672: 				   [$courselevelr,'resource']));
11673: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11674: 
11675: # ------------------------------------------------------ third, check map parms
11676: 	    my %parmhash=();
11677: 	    my $thisparm='';
11678: 	    if (tie(%parmhash,'GDBM_File',
11679: 		    $env{'request.course.fn'}.'_parms.db',
11680: 		    &GDBM_READER(),0640)) {
11681: 		$thisparm=$parmhash{$symbparm};
11682: 		untie(%parmhash);
11683: 	    }
11684: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11685: 	}
11686: # ------------------------------------------ fourth, look in resource metadata
11687:  
11688:         my $what = $spacequalifierrest;
11689: 	$what=~s/\./\_/;
11690: 	my $filename;
11691: 	if (!$symbparm) { $symbparm=&symbread(); }
11692: 	if ($symbparm) {
11693: 	    $filename=(&decode_symb($symbparm))[2];
11694: 	} else {
11695: 	    $filename=$env{'request.filename'};
11696: 	}
11697:         my $toolsymb;
11698:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11699:             $toolsymb = $symbparm;
11700:         }
11701: 	my $metadata=&metadata($filename,$what,$toolsymb);
11702: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11703: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11704: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11705: 
11706: # ----------------------------------------------- fifth, look in rest of course
11707: 	if ($symbparm && defined($courseid) && 
11708: 	    $courseid eq $env{'request.course.id'}) {
11709: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11710: 				     $env{'course.'.$courseid.'.domain'},
11711: 				     'course',$mapp,\$recursed,\@recurseup,
11712:                                      $courseid,'.',$spacequalifierrest,
11713: 				     ([$courselevelm,'map'   ],
11714:                                       [$courseleveli,'map'   ],
11715: 				      [$courselevel, 'course']));
11716: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11717: 	}
11718: # ------------------------------------------------------------------ Cascade up
11719: 	unless ($space eq '0') {
11720: 	    my @parts=split(/_/,$space);
11721: 	    my $id=pop(@parts);
11722: 	    my $part=join('_',@parts);
11723: 	    if ($part eq '') { $part='0'; }
11724: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11725: 				 $symbparm,$udom,$uname,$section,1);
11726: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11727: 	}
11728: 	if ($recurse) { return undef; }
11729: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11730: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11731: # ---------------------------------------------------- Any other user namespace
11732:     } elsif ($realm eq 'environment') {
11733: # ----------------------------------------------------------------- environment
11734: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11735: 	    return $env{'environment.'.$spacequalifierrest};
11736: 	} else {
11737: 	    if ($uname eq 'anonymous' && $udom eq '') {
11738: 		return '';
11739: 	    }
11740: 	    my %returnhash=&userenvironment($udom,$uname,
11741: 					    $spacequalifierrest);
11742: 	    return $returnhash{$spacequalifierrest};
11743: 	}
11744:     } elsif ($realm eq 'system') {
11745: # ----------------------------------------------------------------- system.time
11746: 	if ($space eq 'time') {
11747: 	    return time;
11748:         }
11749:     } elsif ($realm eq 'server') {
11750: # ----------------------------------------------------------------- system.time
11751: 	if ($space eq 'name') {
11752: 	    return $ENV{'SERVER_NAME'};
11753:         }
11754:     }
11755:     return '';
11756: }
11757: 
11758: sub get_reply {
11759:     my ($reply_value) = @_;
11760:     if (ref($reply_value) eq 'ARRAY') {
11761:         if (wantarray) {
11762: 	    return @$reply_value;
11763:         }
11764:         return $reply_value->[0];
11765:     } else {
11766:         return $reply_value;
11767:     }
11768: }
11769: 
11770: sub check_group_parms {
11771:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11772:         $recursed,$recurseupref) = @_;
11773:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11774:                   [$what,'course']);
11775:     my $coursereply;
11776:     foreach my $group (@{$groups}) {
11777:         my @groupitems = ();
11778:         foreach my $level (@levels) {
11779:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11780:              push(@groupitems,[$item,$level->[1]]);
11781:         }
11782:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11783:                                    $env{'course.'.$courseid.'.domain'},
11784:                                    'course',$mapp,$recursed,$recurseupref,
11785:                                    $courseid,'.['.$group.'].',$what,
11786:                                    @groupitems);
11787:         last if (defined($coursereply));
11788:     }
11789:     return $coursereply;
11790: }
11791: 
11792: sub get_map_hierarchy {
11793:     my ($mapname,$courseid) = @_;
11794:     my @recurseup = ();
11795:     if ($mapname) {
11796:         if (($cachedmapkey eq $courseid) &&
11797:             (abs($cachedmaptime-time)<5)) {
11798:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11799:                 return @{$cachedmaps{$mapname}};
11800:             }
11801:         }
11802:         my $navmap = Apache::lonnavmaps::navmap->new();
11803:         if (ref($navmap)) {
11804:             @recurseup = $navmap->recurseup_maps($mapname);
11805:             undef($navmap);
11806:             $cachedmaps{$mapname} = \@recurseup;
11807:             $cachedmaptime=time;
11808:             $cachedmapkey=$courseid;
11809:         }
11810:     }
11811:     return @recurseup;
11812: }
11813: 
11814: }
11815: 
11816: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11817:     my ($courseid,@groups) = @_;
11818:     @groups = sort(@groups);
11819:     return @groups;
11820: }
11821: 
11822: sub packages_tab_default {
11823:     my ($uri,$varname,$toolsymb)=@_;
11824:     my (undef,$part,$name)=split(/\./,$varname);
11825: 
11826:     my (@extension,@specifics,$do_default);
11827:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11828: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11829: 	if ($pack_type eq 'default') {
11830: 	    $do_default=1;
11831: 	} elsif ($pack_type eq 'extension') {
11832: 	    push(@extension,[$package,$pack_type,$pack_part]);
11833: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11834: 	    # only look at packages defaults for packages that this id is
11835: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11836: 	}
11837:     }
11838:     # first look for a package that matches the requested part id
11839:     foreach my $package (@specifics) {
11840: 	my (undef,$pack_type,$pack_part)=@{$package};
11841: 	next if ($pack_part ne $part);
11842: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11843: 	    return $packagetab{"$pack_type&$name&default"};
11844: 	}
11845:     }
11846:     # look for any possible matching non extension_ package
11847:     foreach my $package (@specifics) {
11848: 	my (undef,$pack_type,$pack_part)=@{$package};
11849: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11850: 	    return $packagetab{"$pack_type&$name&default"};
11851: 	}
11852: 	if ($pack_type eq 'part') { $pack_part='0'; }
11853: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11854: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11855: 	}
11856:     }
11857:     # look for any posible extension_ match
11858:     foreach my $package (@extension) {
11859: 	my ($package,$pack_type)=@{$package};
11860: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11861: 	    return $packagetab{"$pack_type&$name&default"};
11862: 	}
11863: 	if (defined($packagetab{$package."&$name&default"})) {
11864: 	    return $packagetab{$package."&$name&default"};
11865: 	}
11866:     }
11867:     # look for a global default setting
11868:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11869: 	return $packagetab{"default&$name&default"};
11870:     }
11871:     return undef;
11872: }
11873: 
11874: sub add_prefix_and_part {
11875:     my ($prefix,$part)=@_;
11876:     my $keyroot;
11877:     if (defined($prefix) && $prefix !~ /^__/) {
11878: 	# prefix that has a part already
11879: 	$keyroot=$prefix;
11880:     } elsif (defined($prefix)) {
11881: 	# prefix that is missing a part
11882: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11883:     } else {
11884: 	# no prefix at all
11885: 	if (defined($part)) { $keyroot='_'.$part; }
11886:     }
11887:     return $keyroot;
11888: }
11889: 
11890: # ---------------------------------------------------------------- Get metadata
11891: 
11892: my %metaentry;
11893: my %importedpartids;
11894: my %importedrespids;
11895: sub metadata {
11896:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11897:     $uri=&declutter($uri);
11898:     # if it is a non metadata possible uri return quickly
11899:     if (($uri eq '') || 
11900: 	(($uri =~ m|^/*adm/|) && 
11901: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11902:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11903: 	return undef;
11904:     }
11905:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11906: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11907: 	return undef;
11908:     }
11909:     my $filename=$uri;
11910:     $uri=~s/\.meta$//;
11911: #
11912: # Is the metadata already cached?
11913: # Look at timestamp of caching
11914: # Everything is cached by the main uri, libraries are never directly cached
11915: #
11916:     if (!defined($liburi)) {
11917: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11918: 	if (defined($cached)) { return $result->{':'.$what}; }
11919:     }
11920: 
11921: #
11922: # If the uri is for an external tool the file from
11923: # which metadata should be retrieved depends on whether
11924: # the tool had been configured to be gradable (set in the Course
11925: # Editor or Resource Editor).
11926: #
11927: # If a valid symb has been included as the third arg in the call
11928: # to &metadata() that can be used to retrieve the value of
11929: # parameter_0_gradable set for the resource, and included in the
11930: # uploaded map containing the tool. The value is retrieved via
11931: # &EXT(), if a valid symb is available.  Otherwise the value of
11932: # gradable in the exttool_$marker.db file for the tool instance
11933: # is retrieved via &get().
11934: #
11935: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11936: # hiddenresource and encrypturl (during course initialization)
11937: # the map-level parameter for resource.0.gradable included in the 
11938: # uploaded map containing the tool will not yet have been stored
11939: # in the user_course_parms.db file for the user's session, so in 
11940: # this case fall back to retrieving gradable status from the
11941: # exttool_$marker.db file.
11942: #
11943: # In order to avoid an infinite loop, &metadata() will return
11944: # before a call to &EXT(), if the uri is for an external tool
11945: # and the $what for which metadata is being requested is
11946: # parameter_0_gradable or 0_gradable.
11947: #
11948: 
11949:     if ($uri =~ /ext\.tool$/) {
11950:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11951:             return;
11952:         } else {
11953:             my ($checked,$use_passback);
11954:             if ($toolsymb ne '') {
11955:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11956:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11957:                     $checked = 1;
11958:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11959:                         $use_passback = 1;
11960:                     }
11961:                 }
11962:             }
11963:             unless ($checked) {
11964:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11965:                 $marker=~s/\D//g;
11966:                 if ($marker) {
11967:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11968:                     $use_passback = $toolsettings{'gradable'};
11969:                 }
11970:             }
11971:             if ($use_passback) {
11972:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11973:             } else {
11974:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11975:             }
11976:         }
11977:     }
11978: 
11979:     {
11980: # Imported parts would go here
11981:         my @origfiletagids=();
11982:         my $importedparts=0;
11983: 
11984: # Imported responseids would go here
11985:         my $importedresponses=0;
11986: #
11987: # Is this a recursive call for a library?
11988: #
11989: #	if (! exists($metacache{$uri})) {
11990: #	    $metacache{$uri}={};
11991: #	}
11992: 	my $cachetime = 60*60;
11993:         if ($liburi) {
11994: 	    $liburi=&declutter($liburi);
11995:             $filename=$liburi;
11996:         } else {
11997: 	    &devalidate_cache_new('meta',$uri);
11998: 	    undef(%metaentry);
11999: 	}
12000:         my %metathesekeys=();
12001:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12002: 	my $metastring;
12003: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12004: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12005: 	    $metastring = 
12006: 		&Apache::lonnet::ssi_body($which,
12007: 					  ('grade_target' => 'meta'));
12008: 	    $cachetime = 1; # only want this cached in the child not long term
12009: 	} elsif (($uri !~ m -^(editupload)/-) && 
12010:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12011: 	    my $file=&filelocation('',&clutter($filename));
12012: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12013: 	    $metastring=&getfile($file);
12014: 	}
12015:         my $parser=HTML::LCParser->new(\$metastring);
12016:         my $token;
12017:         undef %metathesekeys;
12018:         while ($token=$parser->get_token) {
12019: 	    if ($token->[0] eq 'S') {
12020: 		if (defined($token->[2]->{'package'})) {
12021: #
12022: # This is a package - get package info
12023: #
12024: 		    my $package=$token->[2]->{'package'};
12025: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12026: 		    if (defined($token->[2]->{'id'})) { 
12027: 			$keyroot.='_'.$token->[2]->{'id'}; 
12028: 		    }
12029: 		    if ($metaentry{':packages'}) {
12030: 			$metaentry{':packages'}.=','.$package.$keyroot;
12031: 		    } else {
12032: 			$metaentry{':packages'}=$package.$keyroot;
12033: 		    }
12034: 		    foreach my $pack_entry (keys(%packagetab)) {
12035: 			my $part=$keyroot;
12036: 			$part=~s/^\_//;
12037: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12038: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12039: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12040: 			    # ignore package.tab specified default values
12041:                             # here &package_tab_default() will fetch those
12042: 			    if ($subp eq 'default') { next; }
12043: 			    my $value=$packagetab{$pack_entry};
12044: 			    my $unikey;
12045: 			    if ($pack =~ /_0$/) {
12046: 				$unikey='parameter_0_'.$name;
12047: 				$part=0;
12048: 			    } else {
12049: 				$unikey='parameter'.$keyroot.'_'.$name;
12050: 			    }
12051: 			    if ($subp eq 'display') {
12052: 				$value.=' [Part: '.$part.']';
12053: 			    }
12054: 			    $metaentry{':'.$unikey.'.part'}=$part;
12055: 			    $metathesekeys{$unikey}=1;
12056: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12057: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12058: 			    }
12059: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12060: 				$metaentry{':'.$unikey}=
12061: 				    $metaentry{':'.$unikey.'.default'};
12062: 			    }
12063: 			}
12064: 		    }
12065: 		} else {
12066: #
12067: # This is not a package - some other kind of start tag
12068: #
12069: 		    my $entry=$token->[1];
12070: 		    my $unikey='';
12071: 
12072: 		    if ($entry eq 'import') {
12073: #
12074: # Importing a library here
12075: #
12076:                         my $location=$parser->get_text('/import');
12077:                         my $dir=$filename;
12078:                         $dir=~s|[^/]*$||;
12079:                         $location=&filelocation($dir,$location);
12080: 
12081:                         my $importid=$token->[2]->{'id'};
12082:                         my $importmode=$token->[2]->{'importmode'};
12083: #
12084: # Check metadata for imported file to
12085: # see if it contained response items
12086: #
12087:                         my ($origfile,@libfilekeys);
12088:                         my %currmetaentry = %metaentry;
12089:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12090:                                                            $depthcount+1));
12091:                         if (grep(/^responseorder$/,@libfilekeys)) {
12092:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12093:                                                              undef,$depthcount+1);
12094:                             if ($libresponseorder ne '') {
12095:                                 if ($#origfiletagids<0) {
12096:                                     undef(%importedrespids);
12097:                                     undef(%importedpartids);
12098:                                 }
12099:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12100:                                 if (@respids) {
12101:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12102:                                 }
12103:                                 if ($importedrespids{$importid} ne '') {
12104:                                     $importedresponses = 1;
12105: # We need to get the original file and the imported file to get the response order correct
12106: # Load and inspect original file
12107:                                     if ($#origfiletagids<0) {
12108:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12109:                                         $origfile=&getfile($origfilelocation);
12110:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12111:                                     }
12112:                                 }
12113:                             }
12114:                         }
12115: # Do not overwrite contents of %metaentry hash for resource itself with 
12116: # hash populated for imported library file
12117:                         %metaentry = %currmetaentry;
12118:                         undef(%currmetaentry);
12119:                         if ($importmode eq 'part') {
12120: # Import as part(s)
12121:                            $importedparts=1;
12122: # We need to get the original file and the imported file to get the part order correct
12123: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12124: # Load and inspect original file if we didn't do that already
12125:                            if ($#origfiletagids<0) {
12126:                                undef(%importedrespids);
12127:                                undef(%importedpartids);
12128:                                if ($origfile eq '') {
12129:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12130:                                    $origfile=&getfile($origfilelocation);
12131:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12132:                                }
12133:                            }
12134:                            my @impfilepartids;
12135: # If <partorder> tag is included in metadata for the imported file
12136: # get the parts in the imported file from that.
12137:                            if (grep(/^partorder$/,@libfilekeys)) {
12138:                                %currmetaentry = %metaentry;
12139:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12140:                                                             $depthcount+1);
12141:                                %metaentry = %currmetaentry;
12142:                                undef(%currmetaentry);
12143:                                if ($libpartorder ne '') {
12144:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12145:                                }
12146:                            } else {
12147: # If no <partorder> tag available, load and inspect imported file
12148:                                my $impfile=&getfile($location);
12149:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12150:                            }
12151:                            if ($#impfilepartids>=0) {
12152: # This problem had parts
12153:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12154:                            } else {
12155: # Importing by turning a single problem into a problem part
12156: # It gets the import-tags ID as part-ID
12157:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12158:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12159:                            }
12160:                         } else {
12161: # Import as problem or as normal import
12162:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12163:                             unless ($importmode eq 'problem') {
12164: # Normal import
12165:                                 if (defined($token->[2]->{'id'})) {
12166:                                     $unikey.='_'.$token->[2]->{'id'};
12167:                                 }
12168:                             }
12169: # Check metadata for imported file to
12170: # see if it contained parts
12171:                             if (grep(/^partorder$/,@libfilekeys)) {
12172:                                 %currmetaentry = %metaentry;
12173:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12174:                                                              $depthcount+1);
12175:                                 %metaentry = %currmetaentry;
12176:                                 undef(%currmetaentry);
12177:                                 if ($libpartorder ne '') {
12178:                                     $importedparts = 1;
12179:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12180:                                 }
12181:                             }
12182:                         }
12183: 			if ($depthcount<20) {
12184: 			    my $metadata = 
12185: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12186: 					  $depthcount+1);
12187: 			    foreach my $meta (split(',',$metadata)) {
12188: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12189: 				$metathesekeys{$meta}=1;
12190: 			    }
12191:                         }
12192: 		    } else {
12193: #
12194: # Not importing, some other kind of non-package, non-library start tag
12195: # 
12196:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12197:                         if (defined($token->[2]->{'id'})) {
12198:                             $unikey.='_'.$token->[2]->{'id'};
12199:                         }
12200: 			if (defined($token->[2]->{'name'})) { 
12201: 			    $unikey.='_'.$token->[2]->{'name'}; 
12202: 			}
12203: 			$metathesekeys{$unikey}=1;
12204: 			foreach my $param (@{$token->[3]}) {
12205: 			    $metaentry{':'.$unikey.'.'.$param} =
12206: 				$token->[2]->{$param};
12207: 			}
12208: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12209: 			my $default=$metaentry{':'.$unikey.'.default'};
12210: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12211: 		 # only ws inside the tag, and not in default, so use default
12212: 		 # as value
12213: 			    $metaentry{':'.$unikey}=$default;
12214: 			} elsif ( $internaltext =~ /\S/ ) {
12215: 		  # something interesting inside the tag
12216: 			    $metaentry{':'.$unikey}=$internaltext;
12217: 			} else {
12218: 		  # no interesting values, don't set a default
12219: 			}
12220: # end of not-a-package not-a-library import
12221: 		    }
12222: # end of not-a-package start tag
12223: 		}
12224: # the next is the end of "start tag"
12225: 	    }
12226: 	}
12227: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12228: 	$extension = lc($extension);
12229: 	if ($extension eq 'htm') { $extension='html'; }
12230: 
12231: 	foreach my $key (keys(%packagetab)) {
12232: 	    #no specific packages #how's our extension
12233: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12234: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12235: 					 \%metathesekeys);
12236: 	}
12237: 
12238: 	if (!exists($metaentry{':packages'})
12239: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12240: 	    foreach my $key (keys(%packagetab)) {
12241: 		#no specific packages well let's get default then
12242: 		if ($key!~/^default&/) { next; }
12243: 		&metadata_create_package_def($uri,$key,'default',
12244: 					     \%metathesekeys);
12245: 	    }
12246: 	}
12247: # are there custom rights to evaluate
12248: 	if ($metaentry{':copyright'} eq 'custom') {
12249: 
12250:     #
12251:     # Importing a rights file here
12252:     #
12253: 	    unless ($depthcount) {
12254: 		my $location=$metaentry{':customdistributionfile'};
12255: 		my $dir=$filename;
12256: 		$dir=~s|[^/]*$||;
12257: 		$location=&filelocation($dir,$location);
12258: 		my $rights_metadata =
12259: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12260: 			      $depthcount+1);
12261: 		foreach my $rights (split(',',$rights_metadata)) {
12262: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12263: 		    $metathesekeys{$rights}=1;
12264: 		}
12265: 	    }
12266: 	}
12267: 	# uniqifiy package listing
12268: 	my %seen;
12269: 	my @uniq_packages =
12270: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12271: 	$metaentry{':packages'} = join(',',@uniq_packages);
12272: 
12273:         if (($importedresponses) || ($importedparts)) {
12274:             if ($importedparts) {
12275: # We had imported parts and need to rebuild partorder
12276:                 $metaentry{':partorder'}='';
12277:                 $metathesekeys{'partorder'}=1;
12278:             }
12279:             if ($importedresponses) {
12280: # We had imported responses and need to rebuil responseorder
12281:                 $metaentry{':responseorder'}='';
12282:                 $metathesekeys{'responseorder'}=1;
12283:             }
12284:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12285:                 my $origid = $origfiletagids[$index+1];
12286:                 if ($origfiletagids[$index] eq 'part') {
12287: # Original part, part of the problem
12288:                     if ($importedparts) {
12289:                         $metaentry{':partorder'}.=','.$origid;
12290:                     }
12291:                 } elsif ($origfiletagids[$index] eq 'import') {
12292:                     if ($importedparts) {
12293: # We have imported parts at this position
12294:                         if ($importedpartids{$origid} ne '') {
12295:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12296:                         }
12297:                     }
12298:                     if ($importedresponses) {
12299: # We have imported responses at this position
12300:                         if ($importedrespids{$origid} ne '') {
12301:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12302:                         }
12303:                     }
12304:                 } else {
12305: # Original response item, part of the problem
12306:                     if ($importedresponses) {
12307:                         $metaentry{':responseorder'}.=','.$origid;
12308:                     }
12309:                 }
12310:             }
12311:             if ($importedparts) {
12312:                 $metaentry{':partorder'}=~s/^\,//;
12313:             }
12314:             if ($importedresponses) {
12315:                 $metaentry{':responseorder'}=~s/^\,//;
12316:             }
12317:         }
12318: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12319: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12320: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12321:         unless ($liburi) {
12322: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12323:         }
12324: # this is the end of "was not already recently cached
12325:     }
12326:     return $metaentry{':'.$what};
12327: }
12328: 
12329: sub metadata_create_package_def {
12330:     my ($uri,$key,$package,$metathesekeys)=@_;
12331:     my ($pack,$name,$subp)=split(/\&/,$key);
12332:     if ($subp eq 'default') { next; }
12333:     
12334:     if (defined($metaentry{':packages'})) {
12335: 	$metaentry{':packages'}.=','.$package;
12336:     } else {
12337: 	$metaentry{':packages'}=$package;
12338:     }
12339:     my $value=$packagetab{$key};
12340:     my $unikey;
12341:     $unikey='parameter_0_'.$name;
12342:     $metaentry{':'.$unikey.'.part'}=0;
12343:     $$metathesekeys{$unikey}=1;
12344:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12345: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12346:     }
12347:     if (defined($metaentry{':'.$unikey.'.default'})) {
12348: 	$metaentry{':'.$unikey}=
12349: 	    $metaentry{':'.$unikey.'.default'};
12350:     }
12351: }
12352: 
12353: sub metadata_generate_part0 {
12354:     my ($metadata,$metacache,$uri) = @_;
12355:     my %allnames;
12356:     foreach my $metakey (keys(%$metadata)) {
12357: 	if ($metakey=~/^parameter\_(.*)/) {
12358: 	  my $part=$$metacache{':'.$metakey.'.part'};
12359: 	  my $name=$$metacache{':'.$metakey.'.name'};
12360: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12361: 	    $allnames{$name}=$part;
12362: 	  }
12363: 	}
12364:     }
12365:     foreach my $name (keys(%allnames)) {
12366:       $$metadata{"parameter_0_$name"}=1;
12367:       my $key=":parameter_0_$name";
12368:       $$metacache{"$key.part"}='0';
12369:       $$metacache{"$key.name"}=$name;
12370:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12371: 					   $allnames{$name}.'_'.$name.
12372: 					   '.type'};
12373:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12374: 			     '.display'};
12375:       my $expr='[Part: '.$allnames{$name}.']';
12376:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12377:       $$metacache{"$key.display"}=$olddis;
12378:     }
12379: }
12380: 
12381: # ------------------------------------------------------ Devalidate title cache
12382: 
12383: sub devalidate_title_cache {
12384:     my ($url)=@_;
12385:     if (!$env{'request.course.id'}) { return; }
12386:     my $symb=&symbread($url);
12387:     if (!$symb) { return; }
12388:     my $key=$env{'request.course.id'}."\0".$symb;
12389:     &devalidate_cache_new('title',$key);
12390: }
12391: 
12392: # ------------------------------------------------- Get the title of a course
12393: 
12394: sub current_course_title {
12395:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12396: }
12397: # ------------------------------------------------- Get the title of a resource
12398: 
12399: sub gettitle {
12400:     my $urlsymb=shift;
12401:     my $symb=&symbread($urlsymb);
12402:     if ($symb) {
12403: 	my $key=$env{'request.course.id'}."\0".$symb;
12404: 	my ($result,$cached)=&is_cached_new('title',$key);
12405: 	if (defined($cached)) { 
12406: 	    return $result;
12407: 	}
12408: 	my ($map,$resid,$url)=&decode_symb($symb);
12409: 	my $title='';
12410: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12411: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12412: 	} else {
12413: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12414: 		    &GDBM_READER(),0640)) {
12415: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12416: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12417: 		untie(%bighash);
12418: 	    }
12419: 	}
12420: 	$title=~s/\&colon\;/\:/gs;
12421: 	if ($title) {
12422: # Remember both $symb and $title for dynamic metadata
12423:             $accesshash{$symb.'___crstitle'}=$title;
12424:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12425: # Cache this title and then return it
12426: 	    return &do_cache_new('title',$key,$title,600);
12427: 	}
12428: 	$urlsymb=$url;
12429:     }
12430:     my $title=&metadata($urlsymb,'title');
12431:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12432:     return $title;
12433: }
12434: 
12435: sub get_slot {
12436:     my ($which,$cnum,$cdom)=@_;
12437:     if (!$cnum || !$cdom) {
12438: 	(undef,my $courseid)=&whichuser();
12439: 	$cdom=$env{'course.'.$courseid.'.domain'};
12440: 	$cnum=$env{'course.'.$courseid.'.num'};
12441:     }
12442:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12443:     my %slotinfo;
12444:     if (exists($remembered{$key})) {
12445: 	$slotinfo{$which} = $remembered{$key};
12446:     } else {
12447: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12448: 	&Apache::lonhomework::showhash(%slotinfo);
12449: 	my ($tmp)=keys(%slotinfo);
12450: 	if ($tmp=~/^error:/) { return (); }
12451: 	$remembered{$key} = $slotinfo{$which};
12452:     }
12453:     if (ref($slotinfo{$which}) eq 'HASH') {
12454: 	return %{$slotinfo{$which}};
12455:     }
12456:     return $slotinfo{$which};
12457: }
12458: 
12459: sub get_reservable_slots {
12460:     my ($cnum,$cdom,$uname,$udom) = @_;
12461:     my $now = time;
12462:     my $reservable_info;
12463:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12464:     if (exists($remembered{$key})) {
12465:         $reservable_info = $remembered{$key};
12466:     } else {
12467:         my %resv;
12468:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12469:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12470:         $reservable_info = \%resv;
12471:         $remembered{$key} = $reservable_info;
12472:     }
12473:     return $reservable_info;
12474: }
12475: 
12476: sub get_course_slots {
12477:     my ($cnum,$cdom) = @_;
12478:     my $hashid=$cnum.':'.$cdom;
12479:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12480:     if (defined($cached)) {
12481:         if (ref($result) eq 'HASH') {
12482:             return %{$result};
12483:         }
12484:     } else {
12485:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12486:         my ($tmp) = keys(%slots);
12487:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12488:             &do_cache_new('allslots',$hashid,\%slots,600);
12489:             return %slots;
12490:         }
12491:     }
12492:     return;
12493: }
12494: 
12495: sub devalidate_slots_cache {
12496:     my ($cnum,$cdom)=@_;
12497:     my $hashid=$cnum.':'.$cdom;
12498:     &devalidate_cache_new('allslots',$hashid);
12499: }
12500: 
12501: sub get_coursechange {
12502:     my ($cdom,$cnum) = @_;
12503:     if ($cdom eq '' || $cnum eq '') {
12504:         return unless ($env{'request.course.id'});
12505:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12506:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12507:     }
12508:     my $hashid=$cdom.'_'.$cnum;
12509:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12510:     if ((defined($cached)) && ($change ne '')) {
12511:         return $change;
12512:     } else {
12513:         my %crshash;
12514:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12515:         if ($crshash{'internal.contentchange'} eq '') {
12516:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12517:             if ($change eq '') {
12518:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12519:                 $change = $crshash{'internal.created'};
12520:             }
12521:         } else {
12522:             $change = $crshash{'internal.contentchange'};
12523:         }
12524:         my $cachetime = 600;
12525:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12526:     }
12527:     return $change;
12528: }
12529: 
12530: sub devalidate_coursechange_cache {
12531:     my ($cnum,$cdom)=@_;
12532:     my $hashid=$cnum.':'.$cdom;
12533:     &devalidate_cache_new('crschange',$hashid);
12534: }
12535: 
12536: # ------------------------------------------------- Update symbolic store links
12537: 
12538: sub symblist {
12539:     my ($mapname,%newhash)=@_;
12540:     $mapname=&deversion(&declutter($mapname));
12541:     my %hash;
12542:     if (($env{'request.course.fn'}) && (%newhash)) {
12543:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12544:                       &GDBM_WRCREAT(),0640)) {
12545: 	    foreach my $url (keys(%newhash)) {
12546: 		next if ($url eq 'last_known'
12547: 			 && $env{'form.no_update_last_known'});
12548: 		$hash{declutter($url)}=&encode_symb($mapname,
12549: 						    $newhash{$url}->[1],
12550: 						    $newhash{$url}->[0]);
12551:             }
12552:             if (untie(%hash)) {
12553: 		return 'ok';
12554:             }
12555:         }
12556:     }
12557:     return 'error';
12558: }
12559: 
12560: # --------------------------------------------------------------- Verify a symb
12561: 
12562: sub symbverify {
12563:     my ($symb,$thisurl,$encstate)=@_;
12564:     my $thisfn=$thisurl;
12565:     $thisfn=&declutter($thisfn);
12566: # direct jump to resource in page or to a sequence - will construct own symbs
12567:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12568: # check URL part
12569:     my ($map,$resid,$url)=&decode_symb($symb);
12570: 
12571:     unless ($url eq $thisfn) { return 0; }
12572: 
12573:     $symb=&symbclean($symb);
12574:     $thisurl=&deversion($thisurl);
12575:     $thisfn=&deversion($thisfn);
12576: 
12577:     my %bighash;
12578:     my $okay=0;
12579: 
12580:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12581:                             &GDBM_READER(),0640)) {
12582:         my $noclutter;
12583:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12584:             $thisurl =~ s/\?.+$//;
12585:             if ($map =~ m{^uploaded/.+\.page$}) {
12586:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12587:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12588:                 $noclutter = 1;
12589:             }
12590:         }
12591:         my $ids;
12592:         if ($noclutter) {
12593:             $ids=$bighash{'ids_'.$thisurl};
12594:         } else {
12595:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12596:         }
12597:         unless ($ids) {
12598:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12599:             $ids=$bighash{$idkey};
12600:         }
12601:         if ($ids) {
12602: # ------------------------------------------------------------------- Has ID(s)
12603:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12604:                 $symb =~ s/\?.+$//;
12605:             }
12606: 	    foreach my $id (split(/\,/,$ids)) {
12607: 	       my ($mapid,$resid)=split(/\./,$id);
12608:                if (
12609:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12610:    eq $symb) {
12611:                    if (ref($encstate)) {
12612:                        $$encstate = $bighash{'encrypted_'.$id};
12613:                    }
12614: 		   if (($env{'request.role.adv'}) ||
12615: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12616:                        ($thisurl eq '/adm/navmaps')) {
12617: 		       $okay=1;
12618:                        last;
12619: 		   }
12620: 	       }
12621: 	   }
12622:         }
12623: 	untie(%bighash);
12624:     }
12625:     return $okay;
12626: }
12627: 
12628: # --------------------------------------------------------------- Clean-up symb
12629: 
12630: sub symbclean {
12631:     my $symb=shift;
12632:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12633: # remove version from map
12634:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12635: 
12636: # remove version from URL
12637:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12638: 
12639: # remove wrapper
12640: 
12641:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12642:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12643:     return $symb;
12644: }
12645: 
12646: # ---------------------------------------------- Split symb to find map and url
12647: 
12648: sub encode_symb {
12649:     my ($map,$resid,$url)=@_;
12650:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12651: }
12652: 
12653: sub decode_symb {
12654:     my $symb=shift;
12655:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12656:     my ($map,$resid,$url)=split(/___/,$symb);
12657:     return (&fixversion($map),$resid,&fixversion($url));
12658: }
12659: 
12660: sub fixversion {
12661:     my $fn=shift;
12662:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12663:     my %bighash;
12664:     my $uri=&clutter($fn);
12665:     my $key=$env{'request.course.id'}.'_'.$uri;
12666: # is this cached?
12667:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12668:     if (defined($cached)) { return $result; }
12669: # unfortunately not cached, or expired
12670:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12671: 	    &GDBM_READER(),0640)) {
12672:  	if ($bighash{'version_'.$uri}) {
12673:  	    my $version=$bighash{'version_'.$uri};
12674:  	    unless (($version eq 'mostrecent') || 
12675: 		    ($version==&getversion($uri))) {
12676:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12677:  	    }
12678:  	}
12679:  	untie %bighash;
12680:     }
12681:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12682: }
12683: 
12684: sub deversion {
12685:     my $url=shift;
12686:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12687:     return $url;
12688: }
12689: 
12690: # ------------------------------------------------------ Return symb list entry
12691: 
12692: sub symbread {
12693:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12694:     my $cache_str='request.symbread.cached.'.$thisfn;
12695:     if (defined($env{$cache_str})) {
12696:         if ($ignorecachednull) {
12697:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12698:         } else {
12699:             return $env{$cache_str};
12700:         }
12701:     }
12702: # no filename provided? try from environment
12703:     unless ($thisfn) {
12704:         if ($env{'request.symb'}) {
12705: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12706: 	}
12707: 	$thisfn=$env{'request.filename'};
12708:     }
12709:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12710: # is that filename actually a symb? Verify, clean, and return
12711:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12712: 	if (&symbverify($thisfn,$1)) {
12713: 	    return $env{$cache_str}=&symbclean($thisfn);
12714: 	}
12715:     }
12716:     $thisfn=declutter($thisfn);
12717:     my %hash;
12718:     my %bighash;
12719:     my $syval='';
12720:     if (($env{'request.course.fn'}) && ($thisfn)) {
12721:         my $targetfn = $thisfn;
12722:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12723:             $targetfn = 'adm/wrapper/'.$thisfn;
12724:         }
12725: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12726: 	    $targetfn=$1;
12727: 	}
12728:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12729:                       &GDBM_READER(),0640)) {
12730: 	    $syval=$hash{$targetfn};
12731:             untie(%hash);
12732:         }
12733: # ---------------------------------------------------------- There was an entry
12734:         if ($syval) {
12735: 	    #unless ($syval=~/\_\d+$/) {
12736: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12737: 		    #&appenv({'request.ambiguous' => $thisfn});
12738: 		    #return $env{$cache_str}='';
12739: 		#}    
12740: 		#$syval.=$1;
12741: 	    #}
12742:         } else {
12743: # ------------------------------------------------------- Was not in symb table
12744:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12745:                             &GDBM_READER(),0640)) {
12746: # ---------------------------------------------- Get ID(s) for current resource
12747:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12748:               unless ($ids) { 
12749:                  $ids=$bighash{'ids_/'.$thisfn};
12750:               }
12751:               unless ($ids) {
12752: # alias?
12753: 		  $ids=$bighash{'mapalias_'.$thisfn};
12754:               }
12755:               if ($ids) {
12756: # ------------------------------------------------------------------- Has ID(s)
12757:                  my @possibilities=split(/\,/,$ids);
12758:                  if ($#possibilities==0) {
12759: # ----------------------------------------------- There is only one possibility
12760: 		     my ($mapid,$resid)=split(/\./,$ids);
12761: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12762: 						    $resid,$thisfn);
12763:                      if (ref($possibles) eq 'HASH') {
12764:                          $possibles->{$syval} = 1;    
12765:                      }
12766:                      if ($checkforblock) {
12767:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12768:                          if (@blockers) {
12769:                              $syval = '';
12770:                              return;
12771:                          }
12772:                      }
12773:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12774: # ------------------------------------------ There is more than one possibility
12775:                      my $realpossible=0;
12776:                      foreach my $id (@possibilities) {
12777: 			 my $file=$bighash{'src_'.$id};
12778:                          my $canaccess;
12779:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12780:                              $canaccess = 1;
12781:                          } else { 
12782:                              $canaccess = &allowed('bre',$file);
12783:                          }
12784:                          if ($canaccess) {
12785:          		     my ($mapid,$resid)=split(/\./,$id);
12786:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12787:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12788: 						             $resid,$thisfn);
12789:                                  if (ref($possibles) eq 'HASH') {
12790:                                      $possibles->{$syval} = 1;
12791:                                  }
12792:                                  if ($checkforblock) {
12793:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12794:                                      unless (@blockers > 0) {
12795:                                          $syval = $poss_syval;
12796:                                          $realpossible++;
12797:                                      }
12798:                                  } else {
12799:                                      $syval = $poss_syval;
12800:                                      $realpossible++;
12801:                                  }
12802:                              }
12803: 			 }
12804:                      }
12805: 		     if ($realpossible!=1) { $syval=''; }
12806:                  } else {
12807:                      $syval='';
12808:                  }
12809: 	      }
12810:               untie(%bighash);
12811:            }
12812:         }
12813:         if ($syval) {
12814: 	    return $env{$cache_str}=$syval;
12815:         }
12816:     }
12817:     &appenv({'request.ambiguous' => $thisfn});
12818:     return $env{$cache_str}='';
12819: }
12820: 
12821: # ---------------------------------------------------------- Return random seed
12822: 
12823: sub numval {
12824:     my $txt=shift;
12825:     $txt=~tr/A-J/0-9/;
12826:     $txt=~tr/a-j/0-9/;
12827:     $txt=~tr/K-T/0-9/;
12828:     $txt=~tr/k-t/0-9/;
12829:     $txt=~tr/U-Z/0-5/;
12830:     $txt=~tr/u-z/0-5/;
12831:     $txt=~s/\D//g;
12832:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12833:     return int($txt);
12834: }
12835: 
12836: sub numval2 {
12837:     my $txt=shift;
12838:     $txt=~tr/A-J/0-9/;
12839:     $txt=~tr/a-j/0-9/;
12840:     $txt=~tr/K-T/0-9/;
12841:     $txt=~tr/k-t/0-9/;
12842:     $txt=~tr/U-Z/0-5/;
12843:     $txt=~tr/u-z/0-5/;
12844:     $txt=~s/\D//g;
12845:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12846:     my $total;
12847:     foreach my $val (@txts) { $total+=$val; }
12848:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12849:     return int($total);
12850: }
12851: 
12852: sub numval3 {
12853:     use integer;
12854:     my $txt=shift;
12855:     $txt=~tr/A-J/0-9/;
12856:     $txt=~tr/a-j/0-9/;
12857:     $txt=~tr/K-T/0-9/;
12858:     $txt=~tr/k-t/0-9/;
12859:     $txt=~tr/U-Z/0-5/;
12860:     $txt=~tr/u-z/0-5/;
12861:     $txt=~s/\D//g;
12862:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12863:     my $total;
12864:     foreach my $val (@txts) { $total+=$val; }
12865:     if ($_64bit) { $total=(($total<<32)>>32); }
12866:     return $total;
12867: }
12868: 
12869: sub digest {
12870:     my ($data)=@_;
12871:     my $digest=&Digest::MD5::md5($data);
12872:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12873:     my ($e,$f);
12874:     {
12875:         use integer;
12876:         $e=($a+$b);
12877:         $f=($c+$d);
12878:         if ($_64bit) {
12879:             $e=(($e<<32)>>32);
12880:             $f=(($f<<32)>>32);
12881:         }
12882:     }
12883:     if (wantarray) {
12884: 	return ($e,$f);
12885:     } else {
12886: 	my $g;
12887: 	{
12888: 	    use integer;
12889: 	    $g=($e+$f);
12890: 	    if ($_64bit) {
12891: 		$g=(($g<<32)>>32);
12892: 	    }
12893: 	}
12894: 	return $g;
12895:     }
12896: }
12897: 
12898: sub latest_rnd_algorithm_id {
12899:     return '64bit5';
12900: }
12901: 
12902: sub get_rand_alg {
12903:     my ($courseid)=@_;
12904:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12905:     if ($courseid) {
12906: 	return $env{"course.$courseid.rndseed"};
12907:     }
12908:     return &latest_rnd_algorithm_id();
12909: }
12910: 
12911: sub validCODE {
12912:     my ($CODE)=@_;
12913:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12914:     return 0;
12915: }
12916: 
12917: sub getCODE {
12918:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12919:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12920: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12921: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12922: 	return $Apache::lonhomework::history{'resource.CODE'};
12923:     }
12924:     return undef;
12925: }
12926: #
12927: #  Determines the random seed for a specific context:
12928: #
12929: # parameters:
12930: #   symb      - in course context the symb for the seed.
12931: #   course_id - The course id of the form domain_coursenum.
12932: #   domain    - Domain for the user.
12933: #   course    - Course for the user.
12934: #   cenv      - environment of the course.
12935: #
12936: # NOTE:
12937: #   All parameters are picked out of the environment if missing
12938: #   or not defined.
12939: #   If a symb cannot be determined the current time is used instead.
12940: #
12941: #  For a given well defined symb, courside, domain, username,
12942: #  and course environment, the seed is reproducible.
12943: #
12944: sub rndseed {
12945:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12946:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12947:     if (!defined($symb)) {
12948: 	unless ($symb=$wsymb) { return time; }
12949:     }
12950:     if (!defined $courseid) { 
12951: 	$courseid=$wcourseid; 
12952:     }
12953:     if (!defined $domain) { $domain=$wdomain; }
12954:     if (!defined $username) { $username=$wusername }
12955: 
12956:     my $which;
12957:     if (defined($cenv->{'rndseed'})) {
12958: 	$which = $cenv->{'rndseed'};
12959:     } else {
12960: 	$which =&get_rand_alg($courseid);
12961:     }
12962:     if (defined(&getCODE())) {
12963: 
12964: 	if ($which eq '64bit5') {
12965: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12966: 	} elsif ($which eq '64bit4') {
12967: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12968: 	} else {
12969: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12970: 	}
12971:     } elsif ($which eq '64bit5') {
12972: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12973:     } elsif ($which eq '64bit4') {
12974: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12975:     } elsif ($which eq '64bit3') {
12976: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12977:     } elsif ($which eq '64bit2') {
12978: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12979:     } elsif ($which eq '64bit') {
12980: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12981:     }
12982:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12983: }
12984: 
12985: sub rndseed_32bit {
12986:     my ($symb,$courseid,$domain,$username)=@_;
12987:     {
12988: 	use integer;
12989: 	my $symbchck=unpack("%32C*",$symb) << 27;
12990: 	my $symbseed=numval($symb) << 22;
12991: 	my $namechck=unpack("%32C*",$username) << 17;
12992: 	my $nameseed=numval($username) << 12;
12993: 	my $domainseed=unpack("%32C*",$domain) << 7;
12994: 	my $courseseed=unpack("%32C*",$courseid);
12995: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12996: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12997: 	#&logthis("rndseed :$num:$symb");
12998: 	if ($_64bit) { $num=(($num<<32)>>32); }
12999: 	return $num;
13000:     }
13001: }
13002: 
13003: sub rndseed_64bit {
13004:     my ($symb,$courseid,$domain,$username)=@_;
13005:     {
13006: 	use integer;
13007: 	my $symbchck=unpack("%32S*",$symb) << 21;
13008: 	my $symbseed=numval($symb) << 10;
13009: 	my $namechck=unpack("%32S*",$username);
13010: 	
13011: 	my $nameseed=numval($username) << 21;
13012: 	my $domainseed=unpack("%32S*",$domain) << 10;
13013: 	my $courseseed=unpack("%32S*",$courseid);
13014: 	
13015: 	my $num1=$symbchck+$symbseed+$namechck;
13016: 	my $num2=$nameseed+$domainseed+$courseseed;
13017: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13018: 	#&logthis("rndseed :$num:$symb");
13019: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13020: 	return "$num1,$num2";
13021:     }
13022: }
13023: 
13024: sub rndseed_64bit2 {
13025:     my ($symb,$courseid,$domain,$username)=@_;
13026:     {
13027: 	use integer;
13028: 	# strings need to be an even # of cahracters long, it it is odd the
13029:         # last characters gets thrown away
13030: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13031: 	my $symbseed=numval($symb) << 10;
13032: 	my $namechck=unpack("%32S*",$username.' ');
13033: 	
13034: 	my $nameseed=numval($username) << 21;
13035: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13036: 	my $courseseed=unpack("%32S*",$courseid.' ');
13037: 	
13038: 	my $num1=$symbchck+$symbseed+$namechck;
13039: 	my $num2=$nameseed+$domainseed+$courseseed;
13040: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13041: 	#&logthis("rndseed :$num:$symb");
13042: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13043: 	return "$num1,$num2";
13044:     }
13045: }
13046: 
13047: sub rndseed_64bit3 {
13048:     my ($symb,$courseid,$domain,$username)=@_;
13049:     {
13050: 	use integer;
13051: 	# strings need to be an even # of cahracters long, it it is odd the
13052:         # last characters gets thrown away
13053: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13054: 	my $symbseed=numval2($symb) << 10;
13055: 	my $namechck=unpack("%32S*",$username.' ');
13056: 	
13057: 	my $nameseed=numval2($username) << 21;
13058: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13059: 	my $courseseed=unpack("%32S*",$courseid.' ');
13060: 	
13061: 	my $num1=$symbchck+$symbseed+$namechck;
13062: 	my $num2=$nameseed+$domainseed+$courseseed;
13063: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13064: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13065: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13066: 	
13067: 	return "$num1:$num2";
13068:     }
13069: }
13070: 
13071: sub rndseed_64bit4 {
13072:     my ($symb,$courseid,$domain,$username)=@_;
13073:     {
13074: 	use integer;
13075: 	# strings need to be an even # of cahracters long, it it is odd the
13076:         # last characters gets thrown away
13077: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13078: 	my $symbseed=numval3($symb) << 10;
13079: 	my $namechck=unpack("%32S*",$username.' ');
13080: 	
13081: 	my $nameseed=numval3($username) << 21;
13082: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13083: 	my $courseseed=unpack("%32S*",$courseid.' ');
13084: 	
13085: 	my $num1=$symbchck+$symbseed+$namechck;
13086: 	my $num2=$nameseed+$domainseed+$courseseed;
13087: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13088: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13089: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13090: 	
13091: 	return "$num1:$num2";
13092:     }
13093: }
13094: 
13095: sub rndseed_64bit5 {
13096:     my ($symb,$courseid,$domain,$username)=@_;
13097:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13098:     return "$num1:$num2";
13099: }
13100: 
13101: sub rndseed_CODE_64bit {
13102:     my ($symb,$courseid,$domain,$username)=@_;
13103:     {
13104: 	use integer;
13105: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13106: 	my $symbseed=numval2($symb);
13107: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13108: 	my $CODEseed=numval(&getCODE());
13109: 	my $courseseed=unpack("%32S*",$courseid.' ');
13110: 	my $num1=$symbseed+$CODEchck;
13111: 	my $num2=$CODEseed+$courseseed+$symbchck;
13112: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13113: 	#&logthis("rndseed :$num1:$num2:$symb");
13114: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13115: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13116: 	return "$num1:$num2";
13117:     }
13118: }
13119: 
13120: sub rndseed_CODE_64bit4 {
13121:     my ($symb,$courseid,$domain,$username)=@_;
13122:     {
13123: 	use integer;
13124: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13125: 	my $symbseed=numval3($symb);
13126: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13127: 	my $CODEseed=numval3(&getCODE());
13128: 	my $courseseed=unpack("%32S*",$courseid.' ');
13129: 	my $num1=$symbseed+$CODEchck;
13130: 	my $num2=$CODEseed+$courseseed+$symbchck;
13131: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13132: 	#&logthis("rndseed :$num1:$num2:$symb");
13133: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13134: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13135: 	return "$num1:$num2";
13136:     }
13137: }
13138: 
13139: sub rndseed_CODE_64bit5 {
13140:     my ($symb,$courseid,$domain,$username)=@_;
13141:     my $code = &getCODE();
13142:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13143:     return "$num1:$num2";
13144: }
13145: 
13146: sub setup_random_from_rndseed {
13147:     my ($rndseed)=@_;
13148:     if ($rndseed =~/([,:])/) {
13149:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13150:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13151:             &Math::Random::random_set_seed_from_phrase($rndseed);
13152:         } else {
13153:             &Math::Random::random_set_seed($num1,$num2);
13154:         }
13155:     } else {
13156: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13157:     }
13158: }
13159: 
13160: sub latest_receipt_algorithm_id {
13161:     return 'receipt3';
13162: }
13163: 
13164: sub recunique {
13165:     my $fucourseid=shift;
13166:     my $unique;
13167:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13168: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13169: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13170:     } else {
13171: 	$unique=$perlvar{'lonReceipt'};
13172:     }
13173:     return unpack("%32C*",$unique);
13174: }
13175: 
13176: sub recprefix {
13177:     my $fucourseid=shift;
13178:     my $prefix;
13179:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13180: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13181: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13182:     } else {
13183: 	$prefix=$perlvar{'lonHostID'};
13184:     }
13185:     return unpack("%32C*",$prefix);
13186: }
13187: 
13188: sub ireceipt {
13189:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13190: 
13191:     my $return =&recprefix($fucourseid).'-';
13192: 
13193:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13194: 	$env{'request.state'} eq 'construct') {
13195: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13196: 	return $return;
13197:     }
13198: 
13199:     my $cuname=unpack("%32C*",$funame);
13200:     my $cudom=unpack("%32C*",$fudom);
13201:     my $cucourseid=unpack("%32C*",$fucourseid);
13202:     my $cusymb=unpack("%32C*",$fusymb);
13203:     my $cunique=&recunique($fucourseid);
13204:     my $cpart=unpack("%32S*",$part);
13205:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13206: 
13207: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13208: 			       
13209: 	$return.= ($cunique%$cuname+
13210: 		   $cunique%$cudom+
13211: 		   $cusymb%$cuname+
13212: 		   $cusymb%$cudom+
13213: 		   $cucourseid%$cuname+
13214: 		   $cucourseid%$cudom+
13215: 		   $cpart%$cuname+
13216: 		   $cpart%$cudom);
13217:     } else {
13218: 	$return.= ($cunique%$cuname+
13219: 		   $cunique%$cudom+
13220: 		   $cusymb%$cuname+
13221: 		   $cusymb%$cudom+
13222: 		   $cucourseid%$cuname+
13223: 		   $cucourseid%$cudom);
13224:     }
13225:     return $return;
13226: }
13227: 
13228: sub receipt {
13229:     my ($part)=@_;
13230:     my ($symb,$courseid,$domain,$name) = &whichuser();
13231:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13232: }
13233: 
13234: sub whichuser {
13235:     my ($passedsymb)=@_;
13236:     my ($symb,$courseid,$domain,$name,$publicuser);
13237:     if (defined($env{'form.grade_symb'})) {
13238: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13239: 	my $allowed=&allowed('vgr',$tmp_courseid);
13240: 	if (!$allowed &&
13241: 	    exists($env{'request.course.sec'}) &&
13242: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13243: 	    $allowed=&allowed('vgr',$tmp_courseid.
13244: 			      '/'.$env{'request.course.sec'});
13245: 	}
13246: 	if ($allowed) {
13247: 	    ($symb)=&get_env_multiple('form.grade_symb');
13248: 	    $courseid=$tmp_courseid;
13249: 	    ($domain)=&get_env_multiple('form.grade_domain');
13250: 	    ($name)=&get_env_multiple('form.grade_username');
13251: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13252: 	}
13253:     }
13254:     if (!$passedsymb) {
13255: 	$symb=&symbread();
13256:     } else {
13257: 	$symb=$passedsymb;
13258:     }
13259:     $courseid=$env{'request.course.id'};
13260:     $domain=$env{'user.domain'};
13261:     $name=$env{'user.name'};
13262:     if ($name eq 'public' && $domain eq 'public') {
13263: 	if (!defined($env{'form.username'})) {
13264: 	    $env{'form.username'}.=time.rand(10000000);
13265: 	}
13266: 	$name.=$env{'form.username'};
13267:     }
13268:     return ($symb,$courseid,$domain,$name,$publicuser);
13269: 
13270: }
13271: 
13272: # ------------------------------------------------------------ Serves up a file
13273: # returns either the contents of the file or 
13274: # -1 if the file doesn't exist
13275: #
13276: # if the target is a file that was uploaded via DOCS, 
13277: # a check will be made to see if a current copy exists on the local server,
13278: # if it does this will be served, otherwise a copy will be retrieved from
13279: # the home server for the course and stored in /home/httpd/html/userfiles on
13280: # the local server.   
13281: 
13282: sub getfile {
13283:     my ($file) = @_;
13284:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13285:     &repcopy($file);
13286:     return &readfile($file);
13287: }
13288: 
13289: sub repcopy_userfile {
13290:     my ($file)=@_;
13291:     my $londocroot = $perlvar{'lonDocRoot'};
13292:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13293:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13294:     my ($cdom,$cnum,$filename) = 
13295: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13296:     my $uri="/uploaded/$cdom/$cnum/$filename";
13297:     if (-e "$file") {
13298: # we already have a local copy, check it out
13299: 	my @fileinfo = stat($file);
13300: 	my $rtncode;
13301: 	my $info;
13302: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13303: 	if ($lwpresp ne 'ok') {
13304: # there is no such file anymore, even though we had a local copy
13305: 	    if ($rtncode eq '404') {
13306: 		unlink($file);
13307: 	    }
13308: 	    return -1;
13309: 	}
13310: 	if ($info < $fileinfo[9]) {
13311: # nice, the file we have is up-to-date, just say okay
13312: 	    return 'ok';
13313: 	} else {
13314: # the file is outdated, get rid of it
13315: 	    unlink($file);
13316: 	}
13317:     }
13318: # one way or the other, at this point, we don't have the file
13319: # construct the correct path for the file
13320:     my @parts = ($cdom,$cnum); 
13321:     if ($filename =~ m|^(.+)/[^/]+$|) {
13322: 	push @parts, split(/\//,$1);
13323:     }
13324:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13325:     foreach my $part (@parts) {
13326: 	$path .= '/'.$part;
13327: 	if (!-e $path) {
13328: 	    mkdir($path,0770);
13329: 	}
13330:     }
13331: # now the path exists for sure
13332: # get a user agent
13333:     my $transferfile=$file.'.in.transfer';
13334: # FIXME: this should flock
13335:     if (-e $transferfile) { return 'ok'; }
13336:     my $request;
13337:     $uri=~s/^\///;
13338:     my $homeserver = &homeserver($cnum,$cdom);
13339:     my $protocol = $protocol{$homeserver};
13340:     $protocol = 'http' if ($protocol ne 'https');
13341:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13342:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13343: # did it work?
13344:     if ($response->is_error()) {
13345: 	unlink($transferfile);
13346: 	&logthis("Userfile repcopy failed for $uri");
13347: 	return -1;
13348:     }
13349: # worked, rename the transfer file
13350:     rename($transferfile,$file);
13351:     return 'ok';
13352: }
13353: 
13354: sub tokenwrapper {
13355:     my $uri=shift;
13356:     $uri=~s|^https?\://([^/]+)||;
13357:     $uri=~s|^/||;
13358:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13359:     my $token=$1;
13360:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13361:     if ($udom && $uname && $file) {
13362: 	$file=~s|(\?\.*)*$||;
13363:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13364:         my $homeserver = &homeserver($uname,$udom);
13365:         my $protocol = $protocol{$homeserver};
13366:         $protocol = 'http' if ($protocol ne 'https');
13367:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13368:                (($uri=~/\?/)?'&':'?').'token='.$token.
13369:                                '&tokenissued='.$perlvar{'lonHostID'};
13370:     } else {
13371:         return '/adm/notfound.html';
13372:     }
13373: }
13374: 
13375: # call with reqtype HEAD: get last modification time
13376: # call with reqtype GET: get the file contents
13377: # Do not call this with reqtype GET for large files! It loads everything into memory
13378: #
13379: sub getuploaded {
13380:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13381:     $uri=~s/^\///;
13382:     my $homeserver = &homeserver($cnum,$cdom);
13383:     my $protocol = $protocol{$homeserver};
13384:     $protocol = 'http' if ($protocol ne 'https');
13385:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13386:     my $request=new HTTP::Request($reqtype,$uri);
13387:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13388:     $$rtncode = $response->code;
13389:     if (! $response->is_success()) {
13390: 	return 'failed';
13391:     }      
13392:     if ($reqtype eq 'HEAD') {
13393: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13394:     } elsif ($reqtype eq 'GET') {
13395: 	$$info = $response->content;
13396:     }
13397:     return 'ok';
13398: }
13399: 
13400: sub readfile {
13401:     my $file = shift;
13402:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13403:     my $fh;
13404:     open($fh,"<",$file);
13405:     my $a='';
13406:     while (my $line = <$fh>) { $a .= $line; }
13407:     return $a;
13408: }
13409: 
13410: sub filelocation {
13411:     my ($dir,$file) = @_;
13412:     my $location;
13413:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13414: 
13415:     if ($file =~ m-^/adm/-) {
13416: 	$file=~s-^/adm/wrapper/-/-;
13417: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13418:     }
13419: 
13420:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13421:         $location = $file;
13422:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13423:         my ($udom,$uname,$filename)=
13424:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13425:         my $home=&homeserver($uname,$udom);
13426:         my $is_me=0;
13427:         my @ids=&current_machine_ids();
13428:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13429:         if ($is_me) {
13430:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13431:         } else {
13432:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13433:   	      $udom.'/'.$uname.'/'.$filename;
13434:         }
13435:     } elsif ($file =~ m-^/adm/-) {
13436: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13437:     } else {
13438:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13439:         $file=~s:^/(res|priv)/:/:;
13440:         my $space=$1;
13441:         if ( !( $file =~ m:^/:) ) {
13442:             $location = $dir. '/'.$file;
13443:         } else {
13444:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13445:         }
13446:     }
13447:     $location=~s://+:/:g; # remove duplicate /
13448:     while ($location=~m{/\.\./}) {
13449: 	if ($location =~ m{/[^/]+/\.\./}) {
13450: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13451: 	} else {
13452: 	    $location=~ s{/\.\./}{/}g;
13453: 	}
13454:     } #remove dir/..
13455:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13456:     return $location;
13457: }
13458: 
13459: sub hreflocation {
13460:     my ($dir,$file)=@_;
13461:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13462: 	$file=filelocation($dir,$file);
13463:     } elsif ($file=~m-^/adm/-) {
13464: 	$file=~s-^/adm/wrapper/-/-;
13465: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13466:     }
13467:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13468: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13469:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13470: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13471: 	        {/uploaded/$1/$2/}x;
13472:     }
13473:     if ($file=~ m{^/userfiles/}) {
13474: 	$file =~ s{^/userfiles/}{/uploaded/};
13475:     }
13476:     return $file;
13477: }
13478: 
13479: 
13480: 
13481: 
13482: 
13483: sub current_machine_domains {
13484:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13485: }
13486: 
13487: sub machine_domains {
13488:     my ($hostname) = @_;
13489:     my @domains;
13490:     my %hostname = &all_hostnames();
13491:     while( my($id, $name) = each(%hostname)) {
13492: #	&logthis("-$id-$name-$hostname-");
13493: 	if ($hostname eq $name) {
13494: 	    push(@domains,&host_domain($id));
13495: 	}
13496:     }
13497:     return @domains;
13498: }
13499: 
13500: sub current_machine_ids {
13501:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13502: }
13503: 
13504: sub machine_ids {
13505:     my ($hostname) = @_;
13506:     $hostname ||= &hostname($perlvar{'lonHostID'});
13507:     my @ids;
13508:     my %name_to_host = &all_names();
13509:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13510: 	return @{ $name_to_host{$hostname} };
13511:     }
13512:     return;
13513: }
13514: 
13515: sub additional_machine_domains {
13516:     my @domains;
13517:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13518:     while( my $line = <$fh>) {
13519:         $line =~ s/\s//g;
13520:         push(@domains,$line);
13521:     }
13522:     return @domains;
13523: }
13524: 
13525: sub default_login_domain {
13526:     my $domain = $perlvar{'lonDefDomain'};
13527:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13528:     foreach my $posdom (&current_machine_domains(),
13529:                         &additional_machine_domains()) {
13530:         if (lc($posdom) eq lc($testdomain)) {
13531:             $domain=$posdom;
13532:             last;
13533:         }
13534:     }
13535:     return $domain;
13536: }
13537: 
13538: # ------------------------------------------------------------- Declutters URLs
13539: 
13540: sub declutter {
13541:     my $thisfn=shift;
13542:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13543:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13544:         $thisfn=~s{^/home/httpd/html}{};
13545:     }
13546:     $thisfn=~s/^\///;
13547:     $thisfn=~s|^adm/wrapper/||;
13548:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13549:     $thisfn=~s/^res\///;
13550:     $thisfn=~s/^priv\///;
13551:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13552:         $thisfn=~s/\?.+$//;
13553:     }
13554:     return $thisfn;
13555: }
13556: 
13557: # ------------------------------------------------------------- Clutter up URLs
13558: 
13559: sub clutter {
13560:     my $thisfn='/'.&declutter(shift);
13561:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13562: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13563:        $thisfn='/res'.$thisfn; 
13564:     }
13565:     if ($thisfn !~m|^/adm|) {
13566: 	if ($thisfn =~ m|^/ext/|) {
13567: 	    $thisfn='/adm/wrapper'.$thisfn;
13568: 	} else {
13569: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13570: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13571: 	    if ($embstyle eq 'ssi'
13572: 		|| ($embstyle eq 'hdn')
13573: 		|| ($embstyle eq 'rat')
13574: 		|| ($embstyle eq 'prv')
13575: 		|| ($embstyle eq 'ign')) {
13576: 		#do nothing with these
13577: 	    } elsif (($embstyle eq 'img') 
13578: 		|| ($embstyle eq 'emb')
13579: 		|| ($embstyle eq 'wrp')) {
13580: 		$thisfn='/adm/wrapper'.$thisfn;
13581: 	    } elsif ($embstyle eq 'unk'
13582: 		     && $thisfn!~/\.(sequence|page)$/) {
13583: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13584: 	    } else {
13585: #		&logthis("Got a blank emb style");
13586: 	    }
13587: 	}
13588:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13589:         $thisfn='/adm/wrapper'.$thisfn;
13590:     }
13591:     return $thisfn;
13592: }
13593: 
13594: sub clutter_with_no_wrapper {
13595:     my $uri = &clutter(shift);
13596:     if ($uri =~ m-^/adm/-) {
13597: 	$uri =~ s-^/adm/wrapper/-/-;
13598: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13599:     }
13600:     return $uri;
13601: }
13602: 
13603: sub freeze_escape {
13604:     my ($value)=@_;
13605:     if (ref($value)) {
13606: 	$value=&nfreeze($value);
13607: 	return '__FROZEN__'.&escape($value);
13608:     }
13609:     return &escape($value);
13610: }
13611: 
13612: 
13613: sub thaw_unescape {
13614:     my ($value)=@_;
13615:     if ($value =~ /^__FROZEN__/) {
13616: 	substr($value,0,10,undef);
13617: 	$value=&unescape($value);
13618: 	return &thaw($value);
13619:     }
13620:     return &unescape($value);
13621: }
13622: 
13623: sub correct_line_ends {
13624:     my ($result)=@_;
13625:     $$result =~s/\r\n/\n/mg;
13626:     $$result =~s/\r/\n/mg;
13627: }
13628: # ================================================================ Main Program
13629: 
13630: sub goodbye {
13631:    &logthis("Starting Shut down");
13632: #not converted to using infrastruture and probably shouldn't be
13633:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13634: #converted
13635: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13636:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13637: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13638: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13639: #1.1 only
13640: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13641: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13642: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13643: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13644:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13645:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13646:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13647:    &flushcourselogs();
13648:    &logthis("Shutting down");
13649: }
13650: 
13651: sub get_dns {
13652:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13653:     if (!$ignore_cache) {
13654: 	my ($content,$cached)=
13655: 	    &Apache::lonnet::is_cached_new('dns',$url);
13656: 	if ($cached) {
13657: 	    &$func($content,$hashref);
13658: 	    return;
13659: 	}
13660:     }
13661: 
13662:     my %alldns;
13663:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13664:         foreach my $dns (<$config>) {
13665: 	    next if ($dns !~ /^\^(\S*)/x);
13666:             my $line = $1;
13667:             my ($host,$protocol) = split(/:/,$line);
13668:             if ($protocol ne 'https') {
13669:                 $protocol = 'http';
13670:             }
13671: 	    $alldns{$host} = $protocol;
13672:         }
13673:         close($config);
13674:     }
13675:     while (%alldns) {
13676: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13677: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13678:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13679:         delete($alldns{$dns});
13680: 	next if ($response->is_error());
13681:         if ($url eq '/adm/dns/loncapaCRL') {
13682:             return &$func($response);
13683:         } else {
13684: 	    my @content = split("\n",$response->content);
13685: 	    unless ($nocache) {
13686: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13687: 	    }
13688: 	    &$func(\@content,$hashref);
13689:             return;
13690:         }
13691:     }
13692:     my $which = (split('/',$url,4))[3];
13693:     if ($which eq 'loncapaCRL') {
13694:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13695:         if (-e $diskfile) {
13696:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13697:         } else {
13698:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13699:         }
13700:     } else {
13701:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13702:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13703:             my @content = <$config>;
13704:             close($config);
13705:             &$func(\@content,$hashref);
13706:         }
13707:     }
13708:     return;
13709: }
13710: 
13711: # ------------------------------------------------------Get DNS checksums file
13712: sub parse_dns_checksums_tab {
13713:     my ($lines,$hashref) = @_;
13714:     my $lonhost = $perlvar{'lonHostID'};
13715:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13716:     my $loncaparev = &get_server_loncaparev($machine_dom);
13717:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13718:     my $webconfdir = '/etc/httpd/conf';
13719:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13720:         $webconfdir = '/etc/apache2';
13721:     } elsif ($distro =~ /^sles(\d+)$/) {
13722:         if ($1 >= 10) {
13723:             $webconfdir = '/etc/apache2';
13724:         }
13725:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13726:         if ($1 >= 10.0) {
13727:             $webconfdir = '/etc/apache2';
13728:         }
13729:     }
13730:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13731:     my (%chksum,%revnum);
13732:     if (ref($lines) eq 'ARRAY') {
13733:         chomp(@{$lines});
13734:         my $version = shift(@{$lines});
13735:         if ($version eq $release) {  
13736:             foreach my $line (@{$lines}) {
13737:                 my ($file,$version,$shasum) = split(/,/,$line);
13738:                 if ($file =~ m{^/etc/httpd/conf}) {
13739:                     if ($webconfdir eq '/etc/apache2') {
13740:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13741:                     }
13742:                 }
13743:                 $chksum{$file} = $shasum;
13744:                 $revnum{$file} = $version;
13745:             }
13746:             if (ref($hashref) eq 'HASH') {
13747:                 %{$hashref} = (
13748:                                 sums     => \%chksum,
13749:                                 versions => \%revnum,
13750:                               );
13751:             }
13752:         }
13753:     }
13754:     return;
13755: }
13756: 
13757: sub fetch_dns_checksums {
13758:     my %checksums;
13759:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13760:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13761:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13762:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13763:              \%checksums);
13764:     return \%checksums;
13765: }
13766: 
13767: sub fetch_crl_pemfile {
13768:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
13769: }
13770: 
13771: sub save_crl_pem {
13772:     my ($response) = @_;
13773:     my ($msg,$hadchanges);
13774:     if (ref($response)) {
13775:         my $now = time;
13776:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
13777:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
13778:         if (open(my $fh,'>',"$tmpcrl")) {
13779:             print $fh $response->content;
13780:             close($fh);
13781:             if (-e $lonca) {
13782:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
13783:                     my $check = <PIPE>;
13784:                     close(PIPE);
13785:                     chomp($check);
13786:                     if ($check eq 'verify OK') {
13787:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13788:                         my $backup;
13789:                         if (-e $dest) {
13790:                             if (&File::Copy::move($dest,"$dest.bak")) {
13791:                                 $backup = 'ok';
13792:                             }
13793:                         }
13794:                         if (&File::Copy::move($tmpcrl,$dest)) {
13795:                             $msg = 'ok';
13796:                             if ($backup) {
13797:                                 my (%oldnums,%newnums);
13798:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
13799:                                     while (<PIPE>) {
13800:                                         $oldnums{(split(/:/))[1]} = 1;
13801:                                     }
13802:                                     close(PIPE);
13803:                                 }
13804:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
13805:                                     while(<PIPE>) {
13806:                                         $newnums{(split(/:/))[1]} = 1;
13807:                                     }
13808:                                     close(PIPE);
13809:                                 }
13810:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
13811:                                     unless (exists($oldnums{$key})) {
13812:                                         $hadchanges = 1;
13813:                                         last;
13814:                                     }
13815:                                 }
13816:                                 unless ($hadchanges) {
13817:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
13818:                                         unless (exists($newnums{$key})) {
13819:                                             $hadchanges = 1;
13820:                                             last;
13821:                                         }
13822:                                     }
13823:                                 }
13824:                             }
13825:                         }
13826:                     } else {
13827:                         unlink($tmpcrl);
13828:                     }
13829:                 } else {
13830:                     unlink($tmpcrl);
13831:                 }
13832:             } else {
13833:                 unlink($tmpcrl);
13834:             }
13835:         }
13836:     }
13837:     return ($msg,$hadchanges);
13838: }
13839: 
13840: # ------------------------------------------------------------ Read domain file
13841: {
13842:     my $loaded;
13843:     my %domain;
13844: 
13845:     sub parse_domain_tab {
13846: 	my ($lines) = @_;
13847: 	foreach my $line (@$lines) {
13848: 	    next if ($line =~ /^(\#|\s*$ )/x);
13849: 
13850: 	    chomp($line);
13851: 	    my ($name,@elements) = split(/:/,$line,9);
13852: 	    my %this_domain;
13853: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13854: 			       'lang_def', 'city', 'longi', 'lati',
13855: 			       'primary') {
13856: 		$this_domain{$field} = shift(@elements);
13857: 	    }
13858: 	    $domain{$name} = \%this_domain;
13859: 	}
13860:     }
13861: 
13862:     sub reset_domain_info {
13863: 	undef($loaded);
13864: 	undef(%domain);
13865:     }
13866: 
13867:     sub load_domain_tab {
13868: 	my ($ignore_cache,$nocache) = @_;
13869: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13870: 	my $fh;
13871: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13872: 	    my @lines = <$fh>;
13873: 	    &parse_domain_tab(\@lines);
13874: 	}
13875: 	close($fh);
13876: 	$loaded = 1;
13877:     }
13878: 
13879:     sub domain {
13880: 	&load_domain_tab() if (!$loaded);
13881: 
13882: 	my ($name,$what) = @_;
13883: 	return if ( !exists($domain{$name}) );
13884: 
13885: 	if (!$what) {
13886: 	    return $domain{$name}{'description'};
13887: 	}
13888: 	return $domain{$name}{$what};
13889:     }
13890: 
13891:     sub domain_info {
13892:         &load_domain_tab() if (!$loaded);
13893:         return %domain;
13894:     }
13895: 
13896: }
13897: 
13898: 
13899: # ------------------------------------------------------------- Read hosts file
13900: {
13901:     my %hostname;
13902:     my %hostdom;
13903:     my %libserv;
13904:     my $loaded;
13905:     my %name_to_host;
13906:     my %internetdom;
13907:     my %LC_dns_serv;
13908: 
13909:     sub parse_hosts_tab {
13910: 	my ($file) = @_;
13911: 	foreach my $configline (@$file) {
13912: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13913:             chomp($configline);
13914: 	    if ($configline =~ /^\^/) {
13915:                 if ($configline =~ /^\^([\w.\-]+)/) {
13916:                     $LC_dns_serv{$1} = 1;
13917:                 }
13918:                 next;
13919:             }
13920: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13921: 	    $name=~s/\s//g;
13922: 	    if ($id && $domain && $role && $name) {
13923:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13924:                     my $curr = $hostname{$id};
13925:                     my $skip;
13926:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13927:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13928:                             $skip = 1;
13929:                         } else {
13930:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13931:                         }
13932:                     }
13933:                     unless ($skip) {
13934:                         push(@{$name_to_host{$name}},$id);
13935:                     }
13936:                 } else {
13937:                     push(@{$name_to_host{$name}},$id);
13938:                 }
13939: 		$hostname{$id}=$name;
13940: 		$hostdom{$id}=$domain;
13941: 		if ($role eq 'library') { $libserv{$id}=$name; }
13942:                 if (defined($protocol)) {
13943:                     if ($protocol eq 'https') {
13944:                         $protocol{$id} = $protocol;
13945:                     } else {
13946:                         $protocol{$id} = 'http'; 
13947:                     }
13948:                 } else {
13949:                     $protocol{$id} = 'http';
13950:                 }
13951:                 if (defined($intdom)) {
13952:                     $internetdom{$id} = $intdom;
13953:                 }
13954: 	    }
13955: 	}
13956:     }
13957:     
13958:     sub reset_hosts_info {
13959: 	&purge_remembered();
13960: 	&reset_domain_info();
13961: 	&reset_hosts_ip_info();
13962:         undef(%internetdom);
13963: 	undef(%name_to_host);
13964: 	undef(%hostname);
13965: 	undef(%hostdom);
13966: 	undef(%libserv);
13967: 	undef($loaded);
13968:     }
13969: 
13970:     sub load_hosts_tab {
13971: 	my ($ignore_cache,$nocache) = @_;
13972: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13973: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13974: 	my @config = <$config>;
13975: 	&parse_hosts_tab(\@config);
13976: 	close($config);
13977: 	$loaded=1;
13978:     }
13979: 
13980:     sub hostname {
13981: 	&load_hosts_tab() if (!$loaded);
13982: 
13983: 	my ($lonid) = @_;
13984: 	return $hostname{$lonid};
13985:     }
13986: 
13987:     sub all_hostnames {
13988: 	&load_hosts_tab() if (!$loaded);
13989: 
13990: 	return %hostname;
13991:     }
13992: 
13993:     sub all_names {
13994:         my ($ignore_cache,$nocache) = @_;
13995: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13996: 
13997: 	return %name_to_host;
13998:     }
13999: 
14000:     sub all_host_domain {
14001:         &load_hosts_tab() if (!$loaded);
14002:         return %hostdom;
14003:     }
14004: 
14005:     sub all_host_intdom {
14006:         &load_hosts_tab() if (!$loaded);
14007:         return %internetdom;
14008:     }
14009: 
14010:     sub is_library {
14011: 	&load_hosts_tab() if (!$loaded);
14012: 
14013: 	return exists($libserv{$_[0]});
14014:     }
14015: 
14016:     sub all_library {
14017: 	&load_hosts_tab() if (!$loaded);
14018: 
14019: 	return %libserv;
14020:     }
14021: 
14022:     sub unique_library {
14023: 	#2x reverse removes all hostnames that appear more than once
14024:         my %unique = reverse &all_library();
14025:         return reverse %unique;
14026:     }
14027: 
14028:     sub get_servers {
14029: 	&load_hosts_tab() if (!$loaded);
14030: 
14031: 	my ($domain,$type) = @_;
14032: 	my %possible_hosts = ($type eq 'library') ? %libserv
14033: 	                                          : %hostname;
14034: 	my %result;
14035: 	if (ref($domain) eq 'ARRAY') {
14036: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14037: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14038: 		    $result{$host} = $hostname;
14039: 		}
14040: 	    }
14041: 	} else {
14042: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14043: 		if ($hostdom{$host} eq $domain) {
14044: 		    $result{$host} = $hostname;
14045: 		}
14046: 	    }
14047: 	}
14048: 	return %result;
14049:     }
14050: 
14051:     sub get_unique_servers {
14052:         my %unique = reverse &get_servers(@_);
14053: 	return reverse %unique;
14054:     }
14055: 
14056:     sub host_domain {
14057: 	&load_hosts_tab() if (!$loaded);
14058: 
14059: 	my ($lonid) = @_;
14060: 	return $hostdom{$lonid};
14061:     }
14062: 
14063:     sub all_domains {
14064: 	&load_hosts_tab() if (!$loaded);
14065: 
14066: 	my %seen;
14067: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14068: 	return @uniq;
14069:     }
14070: 
14071:     sub internet_dom {
14072:         &load_hosts_tab() if (!$loaded);
14073: 
14074:         my ($lonid) = @_;
14075:         return $internetdom{$lonid};
14076:     }
14077: 
14078:     sub is_LC_dns {
14079:         &load_hosts_tab() if (!$loaded);
14080: 
14081:         my ($hostname) = @_;
14082:         return exists($LC_dns_serv{$hostname});
14083:     }
14084: 
14085: }
14086: 
14087: { 
14088:     my %iphost;
14089:     my %name_to_ip;
14090:     my %lonid_to_ip;
14091: 
14092:     sub get_hosts_from_ip {
14093: 	my ($ip) = @_;
14094: 	my %iphosts = &get_iphost();
14095: 	if (ref($iphosts{$ip})) {
14096: 	    return @{$iphosts{$ip}};
14097: 	}
14098: 	return;
14099:     }
14100:     
14101:     sub reset_hosts_ip_info {
14102: 	undef(%iphost);
14103: 	undef(%name_to_ip);
14104: 	undef(%lonid_to_ip);
14105:     }
14106: 
14107:     sub get_host_ip {
14108: 	my ($lonid) = @_;
14109: 	if (exists($lonid_to_ip{$lonid})) {
14110: 	    return $lonid_to_ip{$lonid};
14111: 	}
14112: 	my $name=&hostname($lonid);
14113:    	my $ip = gethostbyname($name);
14114: 	return if (!$ip || length($ip) ne 4);
14115: 	$ip=inet_ntoa($ip);
14116: 	$name_to_ip{$name}   = $ip;
14117: 	$lonid_to_ip{$lonid} = $ip;
14118: 	return $ip;
14119:     }
14120:     
14121:     sub get_iphost {
14122: 	my ($ignore_cache,$nocache) = @_;
14123: 
14124: 	if (!$ignore_cache) {
14125: 	    if (%iphost) {
14126: 		return %iphost;
14127: 	    }
14128: 	    my ($ip_info,$cached)=
14129: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14130: 	    if ($cached) {
14131: 		%iphost      = %{$ip_info->[0]};
14132: 		%name_to_ip  = %{$ip_info->[1]};
14133: 		%lonid_to_ip = %{$ip_info->[2]};
14134: 		return %iphost;
14135: 	    }
14136: 	}
14137: 
14138: 	# get yesterday's info for fallback
14139: 	my %old_name_to_ip;
14140: 	my ($ip_info,$cached)=
14141: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14142: 	if ($cached) {
14143: 	    %old_name_to_ip = %{$ip_info->[1]};
14144: 	}
14145: 
14146: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14147: 	foreach my $name (keys(%name_to_host)) {
14148: 	    my $ip;
14149: 	    if (!exists($name_to_ip{$name})) {
14150: 		$ip = gethostbyname($name);
14151: 		if (!$ip || length($ip) ne 4) {
14152: 		    if (defined($old_name_to_ip{$name})) {
14153: 			$ip = $old_name_to_ip{$name};
14154: 			&logthis("Can't find $name defaulting to old $ip");
14155: 		    } else {
14156: 			&logthis("Name $name no IP found");
14157: 			next;
14158: 		    }
14159: 		} else {
14160: 		    $ip=inet_ntoa($ip);
14161: 		}
14162: 		$name_to_ip{$name} = $ip;
14163: 	    } else {
14164: 		$ip = $name_to_ip{$name};
14165: 	    }
14166: 	    foreach my $id (@{ $name_to_host{$name} }) {
14167: 		$lonid_to_ip{$id} = $ip;
14168: 	    }
14169: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14170: 	}
14171:         unless ($nocache) {
14172: 	    &do_cache_new('iphost','iphost',
14173: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14174: 		          48*60*60);
14175:         }
14176: 
14177: 	return %iphost;
14178:     }
14179: 
14180:     #
14181:     #  Given a DNS returns the loncapa host name for that DNS 
14182:     # 
14183:     sub host_from_dns {
14184:         my ($dns) = @_;
14185:         my @hosts;
14186:         my $ip;
14187: 
14188:         if (exists($name_to_ip{$dns})) {
14189:             $ip = $name_to_ip{$dns};
14190:         }
14191:         if (!$ip) {
14192:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14193:             if (length($ip) == 4) { 
14194: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14195:             }
14196:         }
14197:         if ($ip) {
14198: 	    @hosts = get_hosts_from_ip($ip);
14199: 	    return $hosts[0];
14200:         }
14201:         return undef;
14202:     }
14203: 
14204:     sub get_internet_names {
14205:         my ($lonid) = @_;
14206:         return if ($lonid eq '');
14207:         my ($idnref,$cached)=
14208:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14209:         if ($cached) {
14210:             return $idnref;
14211:         }
14212:         my $ip = &get_host_ip($lonid);
14213:         my @hosts = &get_hosts_from_ip($ip);
14214:         my %iphost = &get_iphost();
14215:         my (@idns,%seen);
14216:         foreach my $id (@hosts) {
14217:             my $dom = &host_domain($id);
14218:             my $prim_id = &domain($dom,'primary');
14219:             my $prim_ip = &get_host_ip($prim_id);
14220:             next if ($seen{$prim_ip});
14221:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14222:                 foreach my $id (@{$iphost{$prim_ip}}) {
14223:                     my $intdom = &internet_dom($id);
14224:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14225:                         push(@idns,$intdom);
14226:                     }
14227:                 }
14228:             }
14229:             $seen{$prim_ip} = 1;
14230:         }
14231:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14232:     }
14233: 
14234: }
14235: 
14236: sub all_loncaparevs {
14237:     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);
14238: }
14239: 
14240: # ---------------------------------------------------------- Read loncaparev table
14241: {
14242:     sub load_loncaparevs { 
14243:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14244:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14245:                 while (my $configline=<$config>) {
14246:                     chomp($configline);
14247:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14248:                     $loncaparevs{$hostid}=$loncaparev;
14249:                 }
14250:                 close($config);
14251:             }
14252:         }
14253:     }
14254: }
14255: 
14256: # ---------------------------------------------------------- Read serverhostID table
14257: {
14258:     sub load_serverhomeIDs {
14259:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14260:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14261:                 while (my $configline=<$config>) {
14262:                     chomp($configline);
14263:                     my ($name,$id)=split(/:/,$configline);
14264:                     $serverhomeIDs{$name}=$id;
14265:                 }
14266:                 close($config);
14267:             }
14268:         }
14269:     }
14270: }
14271: 
14272: 
14273: BEGIN {
14274: 
14275: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14276:     unless ($readit) {
14277: {
14278:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14279:     %perlvar = (%perlvar,%{$configvars});
14280: }
14281: 
14282: 
14283: # ------------------------------------------------------ Read spare server file
14284: {
14285:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14286: 
14287:     while (my $configline=<$config>) {
14288:        chomp($configline);
14289:        if ($configline) {
14290: 	   my ($host,$type) = split(':',$configline,2);
14291: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14292: 	   push(@{ $spareid{$type} }, $host);
14293:        }
14294:     }
14295:     close($config);
14296: }
14297: # ------------------------------------------------------------ Read permissions
14298: {
14299:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14300: 
14301:     while (my $configline=<$config>) {
14302: 	chomp($configline);
14303: 	if ($configline) {
14304: 	    my ($role,$perm)=split(/ /,$configline);
14305: 	    if ($perm ne '') { $pr{$role}=$perm; }
14306: 	}
14307:     }
14308:     close($config);
14309: }
14310: 
14311: # -------------------------------------------- Read plain texts for permissions
14312: {
14313:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14314: 
14315:     while (my $configline=<$config>) {
14316: 	chomp($configline);
14317: 	if ($configline) {
14318: 	    my ($short,@plain)=split(/:/,$configline);
14319:             %{$prp{$short}} = ();
14320: 	    if (@plain > 0) {
14321:                 $prp{$short}{'std'} = $plain[0];
14322:                 for (my $i=1; $i<@plain; $i++) {
14323:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14324:                 }
14325:             }
14326: 	}
14327:     }
14328:     close($config);
14329: }
14330: 
14331: # ---------------------------------------------------------- Read package table
14332: {
14333:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14334: 
14335:     while (my $configline=<$config>) {
14336: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14337: 	chomp($configline);
14338: 	my ($short,$plain)=split(/:/,$configline);
14339: 	my ($pack,$name)=split(/\&/,$short);
14340: 	if ($plain ne '') {
14341: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14342: 	    $packagetab{$short}=$plain; 
14343: 	}
14344:     }
14345:     close($config);
14346: }
14347: 
14348: # ---------------------------------------------------------- Read loncaparev table
14349: 
14350: &load_loncaparevs();
14351: 
14352: # ---------------------------------------------------------- Read serverhostID table
14353: 
14354: &load_serverhomeIDs();
14355: 
14356: # ---------------------------------------------------------- Read releaseslist XML
14357: {
14358:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14359:     if (-e $file) {
14360:         my $parser = HTML::LCParser->new($file);
14361:         while (my $token = $parser->get_token()) {
14362:             if ($token->[0] eq 'S') {
14363:                 my $item = $token->[1];
14364:                 my $name = $token->[2]{'name'};
14365:                 my $value = $token->[2]{'value'};
14366:                 my $valuematch = $token->[2]{'valuematch'};
14367:                 my $namematch = $token->[2]{'namematch'};
14368:                 if ($item eq 'parameter') {
14369:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14370:                         my $release = $parser->get_text();
14371:                         $release =~ s/(^\s*|\s*$ )//gx;
14372:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14373:                     }
14374:                 } elsif ($item ne '' && $name ne '') {
14375:                     my $release = $parser->get_text();
14376:                     $release =~ s/(^\s*|\s*$ )//gx;
14377:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14378:                 }
14379:             }
14380:         }
14381:     }
14382: }
14383: 
14384: # ---------------------------------------------------------- Read managers table
14385: {
14386:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14387:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14388:             while (my $configline=<$config>) {
14389:                 chomp($configline);
14390:                 next if ($configline =~ /^\#/);
14391:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14392:                     $managerstab{$configline} = 1;
14393:                 }
14394:             }
14395:             close($config);
14396:         }
14397:     }
14398: }
14399: 
14400: # ------------- set up temporary directory
14401: {
14402:     $tmpdir = LONCAPA::tempdir();
14403: 
14404: }
14405: 
14406: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14407: 				'compress_threshold'=> 20_000,
14408:  			        });
14409: 
14410: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14411: $dumpcount=0;
14412: $locknum=0;
14413: 
14414: &logtouch();
14415: &logthis('<font color="yellow">INFO: Read configuration</font>');
14416: $readit=1;
14417:     {
14418: 	use integer;
14419: 	my $test=(2**32)+1;
14420: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14421: 	&logthis(" Detected 64bit platform ($_64bit)");
14422:     }
14423: }
14424: }
14425: 
14426: 1;
14427: __END__
14428: 
14429: =pod
14430: 
14431: =head1 NAME
14432: 
14433: Apache::lonnet - Subroutines to ask questions about things in the network.
14434: 
14435: =head1 SYNOPSIS
14436: 
14437: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14438: 
14439:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14440: 
14441: Common parameters:
14442: 
14443: =over 4
14444: 
14445: =item *
14446: 
14447: $uname : an internal username (if $cname expecting a course Id specifically)
14448: 
14449: =item *
14450: 
14451: $udom : a domain (if $cdom expecting a course's domain specifically)
14452: 
14453: =item *
14454: 
14455: $symb : a resource instance identifier
14456: 
14457: =item *
14458: 
14459: $namespace : the name of a .db file that contains the data needed or
14460: being set.
14461: 
14462: =back
14463: 
14464: =head1 OVERVIEW
14465: 
14466: lonnet provides subroutines which interact with the
14467: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14468: about classes, users, and resources.
14469: 
14470: For many of these objects you can also use this to store data about
14471: them or modify them in various ways.
14472: 
14473: =head2 Symbs
14474: 
14475: To identify a specific instance of a resource, LON-CAPA uses symbols
14476: or "symbs"X<symb>. These identifiers are built from the URL of the
14477: map, the resource number of the resource in the map, and the URL of
14478: the resource itself. The latter is somewhat redundant, but might help
14479: if maps change.
14480: 
14481: An example is
14482: 
14483:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14484: 
14485: The respective map entry is
14486: 
14487:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14488:   title="Problem 2">
14489:  </resource>
14490: 
14491: Symbs are used by the random number generator, as well as to store and
14492: restore data specific to a certain instance of for example a problem.
14493: 
14494: =head2 Storing And Retrieving Data
14495: 
14496: X<store()>X<cstore()>X<restore()>Three of the most important functions
14497: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14498: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14499: is is the non-critical message twin of cstore. These functions are for
14500: handlers to store a perl hash to a user's permanent data space in an
14501: easy manner, and to retrieve it again on another call. It is expected
14502: that a handler would use this once at the beginning to retrieve data,
14503: and then again once at the end to send only the new data back.
14504: 
14505: The data is stored in the user's data directory on the user's
14506: homeserver under the ID of the course.
14507: 
14508: The hash that is returned by restore will have all of the previous
14509: value for all of the elements of the hash.
14510: 
14511: Example:
14512: 
14513:  #creating a hash
14514:  my %hash;
14515:  $hash{'foo'}='bar';
14516: 
14517:  #storing it
14518:  &Apache::lonnet::cstore(\%hash);
14519: 
14520:  #changing a value
14521:  $hash{'foo'}='notbar';
14522: 
14523:  #adding a new value
14524:  $hash{'bar'}='foo';
14525:  &Apache::lonnet::cstore(\%hash);
14526: 
14527:  #retrieving the hash
14528:  my %history=&Apache::lonnet::restore();
14529: 
14530:  #print the hash
14531:  foreach my $key (sort(keys(%history))) {
14532:    print("\%history{$key} = $history{$key}");
14533:  }
14534: 
14535: Will print out:
14536: 
14537:  %history{1:foo} = bar
14538:  %history{1:keys} = foo:timestamp
14539:  %history{1:timestamp} = 990455579
14540:  %history{2:bar} = foo
14541:  %history{2:foo} = notbar
14542:  %history{2:keys} = foo:bar:timestamp
14543:  %history{2:timestamp} = 990455580
14544:  %history{bar} = foo
14545:  %history{foo} = notbar
14546:  %history{timestamp} = 990455580
14547:  %history{version} = 2
14548: 
14549: Note that the special hash entries C<keys>, C<version> and
14550: C<timestamp> were added to the hash. C<version> will be equal to the
14551: total number of versions of the data that have been stored. The
14552: C<timestamp> attribute will be the UNIX time the hash was
14553: stored. C<keys> is available in every historical section to list which
14554: keys were added or changed at a specific historical revision of a
14555: hash.
14556: 
14557: B<Warning>: do not store the hash that restore returns directly. This
14558: will cause a mess since it will restore the historical keys as if the
14559: were new keys. I.E. 1:foo will become 1:1:foo etc.
14560: 
14561: Calling convention:
14562: 
14563:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14564:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14565: 
14566: For more detailed information, see lonnet specific documentation.
14567: 
14568: =head1 RETURN MESSAGES
14569: 
14570: =over 4
14571: 
14572: =item * B<con_lost>: unable to contact remote host
14573: 
14574: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14575: when the connection is brought back up
14576: 
14577: =item * B<con_failed>: unable to contact remote host and unable to save message
14578: for later delivery
14579: 
14580: =item * B<error:>: an error a occurred, a description of the error follows the :
14581: 
14582: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14583: that was requested
14584: 
14585: =back
14586: 
14587: =head1 PUBLIC SUBROUTINES
14588: 
14589: =head2 Session Environment Functions
14590: 
14591: =over 4
14592: 
14593: =item * 
14594: X<appenv()>
14595: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14596: the user envirnoment file, and will be restored for each access this
14597: user makes during this session, also modifies the %env for the current
14598: process. Optional rolesarrayref - if defined contains a reference to an array
14599: of roles which are exempt from the restriction on modifying user.role entries 
14600: in the user's environment.db and in %env.    
14601: 
14602: =item *
14603: X<delenv()>
14604: B<delenv($delthis,$regexp)>: removes all items from the session
14605: environment file that begin with $delthis. If the 
14606: optional second arg - $regexp - is true, $delthis is treated as a 
14607: regular expression, otherwise \Q$delthis\E is used. 
14608: The values are also deleted from the current processes %env.
14609: 
14610: =item * get_env_multiple($name) 
14611: 
14612: gets $name from the %env hash, it seemlessly handles the cases where multiple
14613: values may be defined and end up as an array ref.
14614: 
14615: returns an array of values
14616: 
14617: =back
14618: 
14619: =head2 User Information
14620: 
14621: =over 4
14622: 
14623: =item *
14624: X<queryauthenticate()>
14625: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14626: authentication scheme
14627: 
14628: =item *
14629: X<authenticate()>
14630: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14631: authenticate user from domain's lib servers (first use the current
14632: one). C<$upass> should be the users password.
14633: $checkdefauth is optional (value is 1 if a check should be made to
14634:    authenticate user using default authentication method, and allow
14635:    account creation if username does not have account in the domain).
14636: $clientcancheckhost is optional (value is 1 if checking whether the
14637:    server can host will occur on the client side in lonauth.pm).   
14638: 
14639: =item *
14640: X<homeserver()>
14641: B<homeserver($uname,$udom)>: find the server which has
14642: the user's directory and files (there must be only one), this caches
14643: the answer, and also caches if there is a borken connection.
14644: 
14645: =item *
14646: X<idget()>
14647: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14648: a list of student/employee IDs or clicker IDs
14649: (student/employee IDs are a unique resource in a domain, there must be 
14650: only 1 ID per username, and only 1 username per ID in a specific domain).
14651: clickerIDs are not necessarily unique, as students might share clickers.
14652: (returns hash: id=>name,id=>name)
14653: 
14654: =item *
14655: X<idrget()>
14656: B<idrget($udom,@unames)>: find the IDs behind a list of
14657: usernames (returns hash: name=>id,name=>id)
14658: 
14659: =item *
14660: X<idput()>
14661: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14662: names and associated student/employee IDs or clicker IDs.
14663: 
14664: =item *
14665: X<iddel()>
14666: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14667: student/employee ID or clicker ID username look-ups from domain.
14668: The homeserver ($uhome) and namespace ($namespace) are optional.
14669: If no $uhome is provided, it will be determined usig &homeserver()
14670: for each user.  If no $namespace is provided, the default is ids.
14671: 
14672: =item *
14673: X<updateclickers()>
14674: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14675: clicker ID-to-username look-ups in clickers.db on library server.
14676: Permitted actions are add or del (i.e., add or delete). The 
14677: clickers.db contains clickerID as keys (escaped), and each corresponding
14678: value is an escaped comma-separated list of usernames (for whom the
14679: library server is the homeserver), who registered that particular ID.
14680: If $critical is true, the update will be sent via &critical, otherwise
14681: &reply() will be used.
14682: 
14683: =item *
14684: X<rolesinit()>
14685: B<rolesinit($udom,$username)>: get user privileges.
14686: returns user role, first access and timer interval hashes
14687: 
14688: =item *
14689: X<privileged()>
14690: B<privileged($username,$domain)>: returns a true if user has a
14691: privileged and active role (i.e. su or dc), false otherwise.
14692: 
14693: =item *
14694: X<getsection()>
14695: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14696: course $cname, return section name/number or '' for "not in course"
14697: and '-1' for "no section"
14698: 
14699: =item *
14700: X<userenvironment()>
14701: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14702: passed in @what from the requested user's environment, returns a hash
14703: 
14704: =item * 
14705: X<userlog_query()>
14706: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14707: activity.log file. %filters defines filters applied when parsing the
14708: log file. These can be start or end timestamps, or the type of action
14709: - log to look for Login or Logout events, check for Checkin or
14710: Checkout, role for role selection. The response is in the form
14711: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14712: escaped strings of the action recorded in the activity.log file.
14713: 
14714: =back
14715: 
14716: =head2 User Roles
14717: 
14718: =over 4
14719: 
14720: =item *
14721: 
14722: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14723: returns codes for allowed actions.
14724: 
14725: The first argument is required, all others are optional.
14726: 
14727: $priv is the privilege being checked.
14728: $uri contains additional information about what is being checked for access (e.g.,
14729: URL, course ID etc.). 
14730: $symb is the unique resource instance identifier in a course; if needed,
14731: but not provided, it will be retrieved via a call to &symbread(). 
14732: $role is the role for which a priv is being checked (only used if priv is evb). 
14733: $clientip is the user's IP address (only used when checking for access to portfolio 
14734: files).
14735: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14736: prevents recursive calls to &allowed.
14737: 
14738:  F: full access
14739:  U,I,K: authentication modes (cxx only)
14740:  '': forbidden
14741:  1: user needs to choose course
14742:  2: browse allowed
14743:  A: passphrase authentication needed
14744:  B: access temporarily blocked because of a blocking event in a course.
14745: 
14746: =item *
14747: 
14748: constructaccess($url,$setpriv) : check for access to construction space URL
14749: 
14750: See if the owner domain and name in the URL match those in the
14751: expected environment.  If so, return three element list
14752: ($ownername,$ownerdomain,$ownerhome).
14753: 
14754: Otherwise return the null string.
14755: 
14756: If second argument 'setpriv' is true, it assigns the privileges,
14757: and returns the same three element list, unless the owner has
14758: blocked "ad hoc" Domain Coordinator access to the Author Space,
14759: in which case the null string is returned.
14760: 
14761: =item *
14762: 
14763: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14764: define a custom role rolename set privileges in format of lonTabs/roles.tab
14765: for system, domain, and course level. $uname and $udom are optional (current
14766: user's username and domain will be used when either of $uname or $udom are absent.
14767: 
14768: =item *
14769: 
14770: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14771: (rolesplain.tab); plain text explanation of a user role term.
14772: $type is Course (default) or Community.
14773: If $forcedefault evaluates to true, text returned will be default 
14774: text for $type. Otherwise, if this is a course, the text returned 
14775: will be a custom name for the role (if defined in the course's 
14776: environment).  If no custom name is defined the default is returned.
14777:    
14778: =item *
14779: 
14780: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14781: All arguments are optional. Returns a hash of a roles, either for
14782: co-author/assistant author roles for a user's Construction Space
14783: (default), or if $context is 'userroles', roles for the user himself,
14784: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14785: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14786: For each key, value is set to colon-separated start and end times for
14787: the role.  If no username and domain are specified, will default to
14788: current user/domain. Types, roles, and roledoms are references to arrays
14789: of role statuses (active, future or previous), roles 
14790: (e.g., cc,in, st etc.) and domains of the roles which can be used
14791: to restrict the list of roles reported. If no array ref is 
14792: provided for types, will default to return only active roles.
14793: 
14794: =item *
14795: 
14796: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14797: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14798: 
14799: Additional optional arguments are: $type (if role checking is to be restricted 
14800: to certain user status types -- previous (expired roles), active (currently
14801: available roles) or future (roles available in the future), and
14802: $hideprivileged -- if true will not report course roles for users who
14803: have active Domain Coordinator role in course's domain or in additional
14804: domains (specified in 'Domains to check for privileged users' in course
14805: environment -- set via:  Course Settings -> Classlists and staff listing).
14806: 
14807: =item *
14808: 
14809: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14810: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14811: $possdomains and $possroles are optional array refs -- to domains to check and
14812: roles to check.  If $possdomains is not specified, a dump will be done of the
14813: users' roles.db to check for a dc or su role in any domain. This can be
14814: time consuming if &privileged is called repeatedly (e.g., when displaying a
14815: classlist), so in such cases, supplying a $possdomains array is preferred, as
14816: this then allows &privileged_by_domain() to be used, which caches the identity
14817: of privileged users, eliminating the need for repeated calls to &dump().
14818: 
14819: =item *
14820: 
14821: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14822: where the outer hash keys are domains specified in the $possdomains array ref,
14823: next inner hash keys are privileged roles specified in the $roles array ref,
14824: and the innermost hash contains key = value pairs for username:domain = end:start
14825: for active or future "privileged" users with that role in that domain. To avoid
14826: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14827: innerhash are cached using priv_$role and $dom as the identifiers.
14828: 
14829: =back
14830: 
14831: =head2 User Modification
14832: 
14833: =over 4
14834: 
14835: =item *
14836: 
14837: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14838: user for the level given by URL.  Optional start and end dates (leave empty
14839: string or zero for "no date")
14840: 
14841: =item *
14842: 
14843: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14844: change a users, password, possible return values are: ok,
14845: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14846: refused
14847: 
14848: =item *
14849: 
14850: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14851: 
14852: =item *
14853: 
14854: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14855:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14856: 
14857: will update user information (firstname,middlename,lastname,generation,
14858: permanentemail), and if forceid is true, student/employee ID also.
14859: A user's institutional affiliation(s) can also be updated.
14860: User information fields will not be overwritten with empty entries 
14861: unless the field is included in the $candelete array reference.
14862: This array is included when a single user is modified via "Manage Users",
14863: or when Autoupdate.pl is run by cron in a domain.
14864: 
14865: =item *
14866: 
14867: modifystudent
14868: 
14869: modify a student's enrollment and identification information.
14870: The course id is resolved based on the current user's environment.  
14871: This means the invoking user must be a course coordinator or otherwise
14872: associated with a course.
14873: 
14874: This call is essentially a wrapper for lonnet::modifyuser and
14875: lonnet::modify_student_enrollment
14876: 
14877: Inputs: 
14878: 
14879: =over 4
14880: 
14881: =item B<$udom> Student's loncapa domain
14882: 
14883: =item B<$uname> Student's loncapa login name
14884: 
14885: =item B<$uid> Student/Employee ID
14886: 
14887: =item B<$umode> Student's authentication mode
14888: 
14889: =item B<$upass> Student's password
14890: 
14891: =item B<$first> Student's first name
14892: 
14893: =item B<$middle> Student's middle name
14894: 
14895: =item B<$last> Student's last name
14896: 
14897: =item B<$gene> Student's generation
14898: 
14899: =item B<$usec> Student's section in course
14900: 
14901: =item B<$end> Unix time of the roles expiration
14902: 
14903: =item B<$start> Unix time of the roles start date
14904: 
14905: =item B<$forceid> If defined, allow $uid to be changed
14906: 
14907: =item B<$desiredhome> server to use as home server for student
14908: 
14909: =item B<$email> Student's permanent e-mail address
14910: 
14911: =item B<$type> Type of enrollment (auto or manual)
14912: 
14913: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14914: 
14915: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14916: 
14917: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14918: 
14919: =item B<$context> role change context (shown in User Management Logs display in a course)
14920: 
14921: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14922: 
14923: =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.
14924: 
14925: =back
14926: 
14927: =item *
14928: 
14929: modify_student_enrollment
14930: 
14931: Change a student's enrollment status in a class.  The environment variable
14932: 'role.request.course' must be defined for this function to proceed.
14933: 
14934: Inputs:
14935: 
14936: =over 4
14937: 
14938: =item $udom, student's domain
14939: 
14940: =item $uname, student's name
14941: 
14942: =item $uid, student's user id
14943: 
14944: =item $first, student's first name
14945: 
14946: =item $middle
14947: 
14948: =item $last
14949: 
14950: =item $gene
14951: 
14952: =item $usec
14953: 
14954: =item $end
14955: 
14956: =item $start
14957: 
14958: =item $type
14959: 
14960: =item $locktype
14961: 
14962: =item $cid
14963: 
14964: =item $selfenroll
14965: 
14966: =item $context
14967: 
14968: =item $credits, number of credits student will earn from this class
14969: 
14970: =item $instsec, institutional course section code for student
14971: 
14972: =back
14973: 
14974: 
14975: =item *
14976: 
14977: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14978: custom role; give a custom role to a user for the level given by URL.  Specify
14979: name and domain of role author, and role name
14980: 
14981: =item *
14982: 
14983: revokerole($udom,$uname,$url,$role) : revoke a role for url
14984: 
14985: =item *
14986: 
14987: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14988: 
14989: =back
14990: 
14991: =head2 Course Infomation
14992: 
14993: =over 4
14994: 
14995: =item *
14996: 
14997: coursedescription($courseid,$options) : returns a hash of information about the
14998: specified course id, including all environment settings for the
14999: course, the description of the course will be in the hash under the
15000: key 'description'
15001: 
15002: $options is an optional parameter that if supplied is a hash reference that controls
15003: what how this function works.  It has the following key/values:
15004: 
15005: =over 4
15006: 
15007: =item freshen_cache
15008: 
15009: If defined, and the environment cache for the course is valid, it is 
15010: returned in the returned hash.
15011: 
15012: =item one_time
15013: 
15014: If defined, the last cache time is set to _now_
15015: 
15016: =item user
15017: 
15018: If defined, the supplied username is used instead of the current user.
15019: 
15020: 
15021: =back
15022: 
15023: =item *
15024: 
15025: resdata($name,$domain,$type,@which) : request for current parameter
15026: setting for a specific $type, where $type is either 'course' or 'user',
15027: @what should be a list of parameters to ask about. This routine caches
15028: answers for 10 minutes.
15029: 
15030: =item *
15031: 
15032: get_courseresdata($courseid, $domain) : dump the entire course resource
15033: data base, returning a hash that is keyed by the resource name and has
15034: values that are the resource value.  I believe that the timestamps and
15035: versions are also returned.
15036: 
15037: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15038: supplemental content area. This routine caches the number of files for 
15039: 10 minutes.
15040: 
15041: =back
15042: 
15043: =head2 Course Modification
15044: 
15045: =over 4
15046: 
15047: =item *
15048: 
15049: writecoursepref($courseid,%prefs) : write preferences (environment
15050: database) for a course
15051: 
15052: =item *
15053: 
15054: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15055: 
15056: =item *
15057: 
15058: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15059: 
15060: =item *
15061: 
15062: is_course($courseid), is_course($cdom, $cnum)
15063: 
15064: Accepts either a combined $courseid (in the form of domain_courseid) or the
15065: two component version $cdom, $cnum. It checks if the specified course exists.
15066: 
15067: Returns:
15068:     undef if the course doesn't exist, otherwise
15069:     in scalar context the combined courseid.
15070:     in list context the two components of the course identifier, domain and 
15071:     courseid.    
15072: 
15073: =back
15074: 
15075: =head2 Resource Subroutines
15076: 
15077: =over 4
15078: 
15079: =item *
15080: 
15081: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15082: 
15083: =item *
15084: 
15085: repcopy($filename) : subscribes to the requested file, and attempts to
15086: replicate from the owning library server, Might return
15087: 'unavailable', 'not_found', 'forbidden', 'ok', or
15088: 'bad_request', also attempts to grab the metadata for the
15089: resource. Expects the local filesystem pathname
15090: (/home/httpd/html/res/....)
15091: 
15092: =back
15093: 
15094: =head2 Resource Information
15095: 
15096: =over 4
15097: 
15098: =item *
15099: 
15100: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15101: and returns the value of a variety of different possible values,
15102: $varname should be a request string, and the other parameters can be
15103: used to specify who and what one is asking about. Ordinarily, $cid 
15104: does not need to be specified, as it is retrived from 
15105: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15106: within lonuserstate::loadmap() when initializing a course, before
15107: $env{'request.course.id'} has been set, so it needs to be provided
15108: in that one case.
15109: 
15110: Possible values for $varname are environment.lastname (or other item
15111: from the envirnment hash), user.name (or someother aspect about the
15112: user), resource.0.maxtries (or some other part and parameter of a
15113: resource)
15114: 
15115: =item *
15116: 
15117: directcondval($number) : get current value of a condition; reads from a state
15118: string
15119: 
15120: =item *
15121: 
15122: condval($condidx) : value of condition index based on state
15123: 
15124: =item *
15125: 
15126: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15127: resource's metadata, $what should be either a specific key, or either
15128: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15129: packages that this resource currently uses, the last 3 arguments are 
15130: only used internally for recursive metadata.
15131: 
15132: the toolsymb is only used where the uri is for an external tool (for which
15133: the uri as well as the symb are guaranteed to be unique).
15134: 
15135: this function automatically caches all requests except any made recursively
15136: to retrieve a list of metadata keys for an imported library file ($liburi is 
15137: defined).
15138: 
15139: =item *
15140: 
15141: metadata_query($query,$custom,$customshow) : make a metadata query against the
15142: network of library servers; returns file handle of where SQL and regex results
15143: will be stored for query
15144: 
15145: =item *
15146: 
15147: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15148: return symbolic list entry (all arguments optional). 
15149: 
15150: Args: filename is the filename (including path) for the file for which a symb 
15151: is required; donotrecurse, if true will prevent calls to allowed() being made 
15152: to check access status if more than one resource was found in the bighash 
15153: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15154: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15155: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15156: cause possible symbs to be checked to determine if they are subject to content
15157: blocking, if so they will not be included as possible symbs; possibles is a
15158: ref to a hash, which, as a side effect, will be populated with all possible 
15159: symbs (content blocking not tested).
15160:  
15161: returns the data handle
15162: 
15163: =item *
15164: 
15165: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15166: and is a possible symb for the URL in $thisfn, and if is an encrypted
15167: resource that the user accessed using /enc/ returns a 1 on success, 0
15168: on failure, user must be in a course, as it assumes the existence of
15169: the course initial hash, and uses $env('request.course.id'}.  The third
15170: arg is an optional reference to a scalar.  If this arg is passed in the 
15171: call to symbverify, it will be set to 1 if the symb has been set to be 
15172: encrypted; otherwise it will be null.  
15173: 
15174: =item *
15175: 
15176: symbclean($symb) : removes versions numbers from a symb, returns the
15177: cleaned symb
15178: 
15179: =item *
15180: 
15181: is_on_map($uri) : checks if the $uri is somewhere on the current
15182: course map, user must be in a course for it to work.
15183: 
15184: =item *
15185: 
15186: numval($salt) : return random seed value (addend for rndseed)
15187: 
15188: =item *
15189: 
15190: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15191: a random seed, all arguments are optional, if they aren't sent it uses the
15192: environment to derive them. Note: if symb isn't sent and it can't get one
15193: from &symbread it will use the current time as its return value
15194: 
15195: =item *
15196: 
15197: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15198: unfakeable, receipt
15199: 
15200: =item *
15201: 
15202: receipt() : API to ireceipt working off of env values; given out to users
15203: 
15204: =item *
15205: 
15206: countacc($url) : count the number of accesses to a given URL
15207: 
15208: =item *
15209: 
15210: 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
15211: 
15212: =item *
15213: 
15214: 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)
15215: 
15216: =item *
15217: 
15218: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15219: 
15220: =item *
15221: 
15222: devalidate($symb) : devalidate temporary spreadsheet calculations,
15223: forcing spreadsheet to reevaluate the resource scores next time.
15224: 
15225: =item * 
15226: 
15227: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15228: when viewing in course context.
15229: 
15230:  input: six args -- filename (decluttered), course number, course domain,
15231:                     url, symb (if registered) and group (if this is a 
15232:                     group item -- e.g., bulletin board, group page etc.).
15233: 
15234:  output: array of five scalars --
15235:          $cfile -- url for file editing if editable on current server
15236:          $home -- homeserver of resource (i.e., for author if published,
15237:                                           or course if uploaded.).
15238:          $switchserver --  1 if server switch will be needed.
15239:          $forceedit -- 1 if icon/link should be to go to edit mode 
15240:          $forceview -- 1 if icon/link should be to go to view mode
15241: 
15242: =item *
15243: 
15244: is_course_upload($file,$cnum,$cdom)
15245: 
15246: Used in course context to determine if current file was uploaded to 
15247: the course (i.e., would be found in /userfiles/docs on the course's 
15248: homeserver.
15249: 
15250:   input: 3 args -- filename (decluttered), course number and course domain.
15251:   output: boolean -- 1 if file was uploaded.
15252: 
15253: =back
15254: 
15255: =head2 Storing/Retreiving Data
15256: 
15257: =over 4
15258: 
15259: =item *
15260: 
15261: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15262: permanently for this url; hashref needs to be given and should be a \%hashname;
15263: the remaining args aren't required and if they aren't passed or are '' they will
15264: be derived from the env (with the exception of $laststore, which is an 
15265: optional arg used when a user's submission is stored in grading).
15266: $laststore is $version=$timestamp, where $version is the most recent version
15267: number retrieved for the corresponding $symb in the $namespace db file, and
15268: $timestamp is the timestamp for that transaction (UNIX time).
15269: $laststore is currently only passed when cstore() is called by 
15270: structuretags::finalize_storage().
15271: 
15272: =item *
15273: 
15274: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15275: but uses critical subroutine
15276: 
15277: =item *
15278: 
15279: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15280: all args are optional
15281: 
15282: =item *
15283: 
15284: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15285: dumps the complete (or key matching regexp) namespace into a hash
15286: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15287: normally &store()ed into
15288: 
15289: $range should be either an integer '100' (give me the first 100
15290:                                            matching records)
15291:               or be  two integers sperated by a - with no spaces
15292:                  '30-50' (give me the 30th through the 50th matching
15293:                           records)
15294: 
15295: 
15296: =item *
15297: 
15298: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15299: replaces a &store() version of data with a replacement set of data
15300: for a particular resource in a namespace passed in the $storehash hash 
15301: reference. If $tolog is true, the transaction is logged in the courselog
15302: with an action=PUTSTORE.
15303: 
15304: =item *
15305: 
15306: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15307: works very similar to store/cstore, but all data is stored in a
15308: temporary location and can be reset using tmpreset, $storehash should
15309: be a hash reference, returns nothing on success
15310: 
15311: =item *
15312: 
15313: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15314: similar to restore, but all data is stored in a temporary location and
15315: can be reset using tmpreset. Returns a hash of values on success,
15316: error string otherwise.
15317: 
15318: =item *
15319: 
15320: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15321: deltes all keys for $symb form the temporary storage hash.
15322: 
15323: =item *
15324: 
15325: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15326: reference filled in from namesp ($udom and $uname are optional)
15327: 
15328: =item *
15329: 
15330: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15331: namesp ($udom and $uname are optional)
15332: 
15333: =item *
15334: 
15335: dump($namespace,$udom,$uname,$regexp,$range) : 
15336: dumps the complete (or key matching regexp) namespace into a hash
15337: ($udom, $uname, $regexp, $range are optional)
15338: 
15339: $range should be either an integer '100' (give me the first 100
15340:                                            matching records)
15341:               or be  two integers sperated by a - with no spaces
15342:                  '30-50' (give me the 30th through the 50th matching
15343:                           records)
15344: =item *
15345: 
15346: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15347: $store can be a scalar, an array reference, or if the amount to be 
15348: incremented is > 1, a hash reference.
15349: 
15350: ($udom and $uname are optional)
15351: 
15352: =item *
15353: 
15354: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15355: ($udom and $uname are optional)
15356: 
15357: =item *
15358: 
15359: cput($namespace,$storehash,$udom,$uname) : critical put
15360: ($udom and $uname are optional)
15361: 
15362: =item *
15363: 
15364: newput($namespace,$storehash,$udom,$uname) :
15365: 
15366: Attempts to store the items in the $storehash, but only if they don't
15367: currently exist, if this succeeds you can be certain that you have 
15368: successfully created a new key value pair in the $namespace db.
15369: 
15370: 
15371: Args:
15372:  $namespace: name of database to store values to
15373:  $storehash: hashref to store to the db
15374:  $udom: (optional) domain of user containing the db
15375:  $uname: (optional) name of user caontaining the db
15376: 
15377: Returns:
15378:  'ok' -> succeeded in storing all keys of $storehash
15379:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15380:                         least <key> already existed in the db (other
15381:                         requested keys may also already exist)
15382:  'error: <msg>' -> unable to tie the DB or other error occurred
15383:  'con_lost' -> unable to contact request server
15384:  'refused' -> action was not allowed by remote machine
15385: 
15386: 
15387: =item *
15388: 
15389: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15390: reference filled in from namesp (encrypts the return communication)
15391: ($udom and $uname are optional)
15392: 
15393: =item *
15394: 
15395: log($udom,$name,$home,$message) : write to permanent log for user; use
15396: critical subroutine
15397: 
15398: =item *
15399: 
15400: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15401: array reference filled in from namespace found in domain level on either
15402: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15403: 
15404: =item *
15405: 
15406: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15407: domain level either on specified domain server ($uhome) or primary domain 
15408: server ($udom and $uhome are optional)
15409: 
15410: =item * 
15411: 
15412: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15413: for: authentication, language, quotas, timezone, date locale, and portal URL in
15414: the target domain.
15415: 
15416: May also include additional key => value pairs for the following groups:
15417: 
15418: =over
15419: 
15420: =item
15421: disk quotas (MB allocated by default to portfolios and authoring spaces).
15422: 
15423: =over
15424: 
15425: =item defaultquota, authorquota
15426: 
15427: =back
15428: 
15429: =item
15430: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15431: portfolio for users).
15432: 
15433: =over
15434: 
15435: =item
15436: aboutme, blog, webdav, portfolio
15437: 
15438: =back
15439: 
15440: =item
15441: requestcourses: ability to request courses, and how requests are processed.
15442: 
15443: =over
15444: 
15445: =item
15446: official, unofficial, community, textbook, placement
15447: 
15448: =back
15449: 
15450: =item
15451: inststatus: types of institutional affiliation, and order in which they are displayed.
15452: 
15453: =over
15454: 
15455: =item
15456: inststatustypes, inststatusorder, inststatusguest
15457: 
15458: =back
15459: 
15460: =item
15461: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15462: for course's uploaded content.
15463: 
15464: =over
15465: 
15466: =item
15467: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15468: communityquota, textbookquota, placementquota
15469: 
15470: =back
15471: 
15472: =item
15473: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15474: on your servers.
15475: 
15476: =over
15477: 
15478: =item 
15479: remotesessions, hostedsessions
15480: 
15481: =back
15482: 
15483: =back
15484: 
15485: In cases where a domain coordinator has never used the "Set Domain Configuration"
15486: utility to create a configuration.db file on a domain's primary library server 
15487: only the following domain defaults: auth_def, auth_arg_def, lang_def
15488: -- corresponding values are authentication type (internal, krb4, krb5,
15489: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15490: will be available. Values are retrieved from cache (if current), unless the
15491: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15492: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15493: 
15494: Typical usage:
15495: 
15496: %domdefaults = &get_domain_defaults($target_domain);
15497: 
15498: =back
15499: 
15500: =head2 Network Status Functions
15501: 
15502: =over 4
15503: 
15504: =item *
15505: 
15506: dirlist() : return directory list based on URI (first arg).
15507: 
15508: Inputs: 1 required, 5 optional.
15509: 
15510: =over
15511: 
15512: =item 
15513: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15514: 
15515: =item
15516: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15517: 
15518: =item
15519: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15520: 
15521: =item
15522: $getpropath - boolean: 1 if prepend path using &propath(). 
15523: 
15524: =item
15525: $getuserdir - boolean: 1 if prepend path for "userfiles".
15526: 
15527: =item 
15528: $alternateRoot - path to prepend in place of path from $uri.
15529: 
15530: =back
15531: 
15532: Returns: Array of up to two items.
15533: 
15534: =over
15535: 
15536: a reference to an array of files/subdirectories
15537: 
15538: =over
15539: 
15540: Each element in the array of files/subdirectories is a & separated list of
15541: item name and the result of running stat on the item.  If dirlist was requested
15542: for a file instead of a directory, the item name will be ''. For a directory 
15543: listing, if the item is a metadata file, the element will end &N&M 
15544: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15545: default copyright set (1).  
15546: 
15547: =back
15548: 
15549: a scalar containing error condition (if encountered).
15550: 
15551: =over
15552: 
15553: =item 
15554: no_host (no homeserver identified for $username:$domain).
15555: 
15556: =item 
15557: no_such_host (server contacted for listing not identified as valid host).
15558: 
15559: =item 
15560: con_lost (connection to remote server failed).
15561: 
15562: =item 
15563: refused (invalid $username:$domain received on lond side).
15564: 
15565: =item 
15566: no_such_dir (directory at specified path on lond side does not exist). 
15567: 
15568: =item 
15569: empty (directory at specified path on lond side is empty).
15570: 
15571: =over
15572: 
15573: This is currently not encountered because the &ls3, &ls2, 
15574: &ls (_handler) routines on the lond side do not filter out
15575: . and .. from a directory listing. 
15576: 
15577: =back
15578: 
15579: =back
15580: 
15581: =back
15582: 
15583: =item *
15584: 
15585: spareserver() : find server with least workload from spare.tab
15586: 
15587: 
15588: =item *
15589: 
15590: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15591: if there is no corresponding loncapa host.
15592: 
15593: =back
15594: 
15595: 
15596: =head2 Apache Request
15597: 
15598: =over 4
15599: 
15600: =item *
15601: 
15602: ssi($url,%hash) : server side include, does a complete request cycle on url to
15603: localhost, posts hash
15604: 
15605: =back
15606: 
15607: =head2 Data to String to Data
15608: 
15609: =over 4
15610: 
15611: =item *
15612: 
15613: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15614: and '&' separators, supports elements that are arrayrefs and hashrefs
15615: 
15616: =item *
15617: 
15618: hashref2str($hashref) : convert a hashref into a string complete with
15619: escaping and '=' and '&' separators, supports elements that are
15620: arrayrefs and hashrefs
15621: 
15622: =item *
15623: 
15624: arrayref2str($arrayref) : convert an arrayref into a string complete
15625: with escaping and '&' separators, supports elements that are arrayrefs
15626: and hashrefs
15627: 
15628: =item *
15629: 
15630: str2hash($string) : convert string to hash using unescaping and
15631: splitting on '=' and '&', supports elements that are arrayrefs and
15632: hashrefs
15633: 
15634: =item *
15635: 
15636: str2array($string) : convert string to hash using unescaping and
15637: splitting on '&', supports elements that are arrayrefs and hashrefs
15638: 
15639: =back
15640: 
15641: =head2 Logging Routines
15642: 
15643: 
15644: These routines allow one to make log messages in the lonnet.log and
15645: lonnet.perm logfiles.
15646: 
15647: =over 4
15648: 
15649: =item *
15650: 
15651: logtouch() : make sure the logfile, lonnet.log, exists
15652: 
15653: =item *
15654: 
15655: logthis() : append message to the normal lonnet.log file, it gets
15656: preiodically rolled over and deleted.
15657: 
15658: =item *
15659: 
15660: logperm() : append a permanent message to lonnet.perm.log, this log
15661: file never gets deleted by any automated portion of the system, only
15662: messages of critical importance should go in here.
15663: 
15664: 
15665: =back
15666: 
15667: =head2 General File Helper Routines
15668: 
15669: =over 4
15670: 
15671: =item *
15672: 
15673: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15674: (a) files in /uploaded
15675:   (i) If a local copy of the file exists - 
15676:       compares modification date of local copy with last-modified date for 
15677:       definitive version stored on home server for course. If local copy is 
15678:       stale, requests a new version from the home server and stores it. 
15679:       If the original has been removed from the home server, then local copy 
15680:       is unlinked.
15681:   (ii) If local copy does not exist -
15682:       requests the file from the home server and stores it. 
15683:   
15684:   If $caller is 'uploadrep':  
15685:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15686:     for request for files originally uploaded via DOCS. 
15687:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15688:   
15689:   Otherwise:
15690:      This indicates a call from the content generation phase of the request.
15691:      -  returns the entire contents of the file or -1.
15692:      
15693: (b) files in /res
15694:    - returns the entire contents of a file or -1; 
15695:    it properly subscribes to and replicates the file if neccessary.
15696: 
15697: 
15698: =item *
15699: 
15700: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15701:                   reference
15702: 
15703: returns either a stat() list of data about the file or an empty list
15704: if the file doesn't exist or couldn't find out about it (connection
15705: problems or user unknown)
15706: 
15707: =item *
15708: 
15709: filelocation($dir,$file) : returns file system location of a file
15710: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15711: directory that relative $file lookups are to looked in ($dir of /a/dir
15712: and a file of ../bob will become /a/bob)
15713: 
15714: =item *
15715: 
15716: hreflocation($dir,$file) : returns file system location or a URL; same as
15717: filelocation except for hrefs
15718: 
15719: =item *
15720: 
15721: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15722: also removes beginning /home/httpd/html unless /priv/ follows it.
15723: 
15724: =back
15725: 
15726: =head2 Usererfile file routines (/uploaded*)
15727: 
15728: =over 4
15729: 
15730: =item *
15731: 
15732: userfileupload(): main rotine for putting a file in a user or course's
15733:                   filespace, arguments are,
15734: 
15735:  formname - required - this is the name of the element in $env where the
15736:            filename, and the contents of the file to create/modifed exist
15737:            the filename is in $env{'form.'.$formname.'.filename'} and the
15738:            contents of the file is located in $env{'form.'.$formname}
15739:  context - if coursedoc, store the file in the course of the active role
15740:              of the current user; 
15741:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15742:            if 'canceloverwrite': delete file in tmp/overwrites directory
15743:  subdir - required - subdirectory to put the file in under ../userfiles/
15744:          if undefined, it will be placed in "unknown"
15745: 
15746:  (This routine calls clean_filename() to remove any dangerous
15747:  characters from the filename, and then calls finuserfileupload() to
15748:  complete the transaction)
15749: 
15750:  returns either the url of the uploaded file (/uploaded/....) if successful
15751:  and /adm/notfound.html if unsuccessful
15752: 
15753: =item *
15754: 
15755: clean_filename(): routine for cleaing a filename up for storage in
15756:                  userfile space, argument is:
15757: 
15758:  filename - proposed filename
15759: 
15760: returns: the new clean filename
15761: 
15762: =item *
15763: 
15764: finishuserfileupload(): routine that creates and sends the file to
15765: userspace, probably shouldn't be called directly
15766: 
15767:   docuname: username or courseid of destination for the file
15768:   docudom: domain of user/course of destination for the file
15769:   formname: same as for userfileupload()
15770:   fname: filename (including subdirectories) for the file
15771:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15772:   allfiles: reference to hash used to store objects found by parser
15773:   codebase: reference to hash used for codebases of java objects found by parser
15774:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15775:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15776:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15777:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15778:   context: if 'overwrite', will move the uploaded file from its temporary location to
15779:             userfiles to facilitate overwriting a previously uploaded file with same name.
15780:   mimetype: reference to scalar to accommodate mime type determined
15781:             from File::MMagic if $parser = parse.
15782: 
15783:  returns either the url of the uploaded file (/uploaded/....) if successful
15784:  and /adm/notfound.html if unsuccessful (or an error message if context 
15785:  was 'overwrite').
15786:  
15787: 
15788: =item *
15789: 
15790: renameuserfile(): renames an existing userfile to a new name
15791: 
15792:   Args:
15793:    docuname: username or courseid of destination for the file
15794:    docudom: domain of user/course of destination for the file
15795:    old: current file name (including any subdirs under userfiles)
15796:    new: desired file name (including any subdirs under userfiles)
15797: 
15798: =item *
15799: 
15800: mkdiruserfile(): creates a directory is a userfiles dir
15801: 
15802:   Args:
15803:    docuname: username or courseid of destination for the file
15804:    docudom: domain of user/course of destination for the file
15805:    dir: dir to create (including any subdirs under userfiles)
15806: 
15807: =item *
15808: 
15809: removeuserfile(): removes a file that exists in userfiles
15810: 
15811:   Args:
15812:    docuname: username or courseid of destination for the file
15813:    docudom: domain of user/course of destination for the file
15814:    fname: filname to delete (including any subdirs under userfiles)
15815: 
15816: =item *
15817: 
15818: removeuploadedurl(): convience function for removeuserfile()
15819: 
15820:   Args:
15821:    url:  a full /uploaded/... url to delete
15822: 
15823: =item * 
15824: 
15825: get_portfile_permissions():
15826:   Args:
15827:     domain: domain of user or course contain the portfolio files
15828:     user: name of user or num of course contain the portfolio files
15829:   Returns:
15830:     hashref of a dump of the proper file_permissions.db
15831:    
15832: 
15833: =item * 
15834: 
15835: get_access_controls():
15836: 
15837: Args:
15838:   current_permissions: the hash ref returned from get_portfile_permissions()
15839:   group: (optional) the group you want the files associated with
15840:   file: (optional) the file you want access info on
15841: 
15842: Returns:
15843:     a hash (keys are file names) of hashes containing
15844:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15845:         values are XML containing access control settings (see below) 
15846: 
15847: Internal notes:
15848: 
15849:  access controls are stored in file_permissions.db as key=value pairs.
15850:     key -> path to file/file_name\0uniqueID:scope_end_start
15851:         where scope -> public,guest,course,group,domains or users.
15852:               end -> UNIX time for end of access (0 -> no end date)
15853:               start -> UNIX time for start of access
15854: 
15855:     value -> XML description of access control
15856:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15857:             <start></start>
15858:             <end></end>
15859: 
15860:             <password></password>  for scope type = guest
15861: 
15862:             <domain></domain>     for scope type = course or group
15863:             <number></number>
15864:             <roles id="">
15865:              <role></role>
15866:              <access></access>
15867:              <section></section>
15868:              <group></group>
15869:             </roles>
15870: 
15871:             <dom></dom>         for scope type = domains
15872: 
15873:             <users>             for scope type = users
15874:              <user>
15875:               <uname></uname>
15876:               <udom></udom>
15877:              </user>
15878:             </users>
15879:            </scope> 
15880:               
15881:  Access data is also aggregated for each file in an additional key=value pair:
15882:  key -> path to file/file_name\0accesscontrol 
15883:  value -> reference to hash
15884:           hash contains key = value pairs
15885:           where key = uniqueID:scope_end_start
15886:                 value = UNIX time record was last updated
15887: 
15888:           Used to improve speed of look-ups of access controls for each file.  
15889:  
15890:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15891: 
15892: =item *
15893: 
15894: modify_access_controls():
15895: 
15896: Modifies access controls for a portfolio file
15897: Args
15898: 1. file name
15899: 2. reference to hash of required changes,
15900: 3. domain
15901: 4. username
15902:   where domain,username are the domain of the portfolio owner 
15903:   (either a user or a course) 
15904: 
15905: Returns:
15906: 1. result of additions or updates ('ok' or 'error', with error message). 
15907: 2. result of deletions ('ok' or 'error', with error message).
15908: 3. reference to hash of any new or updated access controls.
15909: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15910:    key = integer (inbound ID)
15911:    value = uniqueID
15912: 
15913: =item *
15914: 
15915: get_timebased_id():
15916: 
15917: Attempts to get a unique timestamp-based suffix for use with items added to a 
15918: course via the Course Editor (e.g., folders, composite pages, 
15919: group bulletin boards).
15920: 
15921: Args: (first three required; six others optional)
15922: 
15923: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15924:    docssequence, or name of group
15925: 
15926: 2. keyid (alphanumeric): name of temporary locking key in hash,
15927:    e.g., num, boardids
15928: 
15929: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15930:    file will be named nohist_namespace.db
15931: 
15932: 4. cdom: domain of course; default is current course domain from %env
15933: 
15934: 5. cnum: course number; default is current course number from %env
15935: 
15936: 6. idtype: set to concat if an additional digit is to be appended to the 
15937:    unix timestamp to form the suffix, if the plain timestamp is already
15938:    in use.  Default is to not do this, but simply increment the unix 
15939:    timestamp by 1 until a unique key is obtained.
15940: 
15941: 7. who: holder of locking key; defaults to user:domain for user.
15942: 
15943: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15944:    retrying); default is 3.
15945: 
15946: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15947: 
15948: Returns:
15949: 
15950: 1. suffix obtained (numeric)
15951: 
15952: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15953: 
15954: 3. error: contains (localized) error message if an error occurred.
15955: 
15956: 
15957: =back
15958: 
15959: =head2 HTTP Helper Routines
15960: 
15961: =over 4
15962: 
15963: =item *
15964: 
15965: escape() : unpack non-word characters into CGI-compatible hex codes
15966: 
15967: =item *
15968: 
15969: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15970: 
15971: =back
15972: 
15973: =head1 PRIVATE SUBROUTINES
15974: 
15975: =head2 Underlying communication routines (Shouldn't call)
15976: 
15977: =over 4
15978: 
15979: =item *
15980: 
15981: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15982: 
15983: =item *
15984: 
15985: reply() : uses subreply to send a message to remote machine, logs all failures
15986: 
15987: =item *
15988: 
15989: critical() : passes a critical message to another server; if cannot
15990: get through then place message in connection buffer directory and
15991: returns con_delayed, if incapable of saving message, returns
15992: con_failed
15993: 
15994: =item *
15995: 
15996: reconlonc() : tries to reconnect lonc client processes.
15997: 
15998: =back
15999: 
16000: =head2 Resource Access Logging
16001: 
16002: =over 4
16003: 
16004: =item *
16005: 
16006: flushcourselogs() : flush (save) buffer logs and access logs
16007: 
16008: =item *
16009: 
16010: courselog($what) : save message for course in hash
16011: 
16012: =item *
16013: 
16014: courseacclog($what) : save message for course using &courselog().  Perform
16015: special processing for specific resource types (problems, exams, quizzes, etc).
16016: 
16017: =item *
16018: 
16019: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16020: as a PerlChildExitHandler
16021: 
16022: =back
16023: 
16024: =head2 Other
16025: 
16026: =over 4
16027: 
16028: =item *
16029: 
16030: symblist($mapname,%newhash) : update symbolic storage links
16031: 
16032: =back
16033: 
16034: =cut
16035: 

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