File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1395: download - view: text, annotated - select for diffs
Sat Dec 8 17:38:47 2018 UTC (5 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Trust settings

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1395 2018/12/08 17:38:47 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$hostname,$context) = @_;
  234:     return if ($lonhost eq '');
  235:     if ($hostname eq '') {
  236:         $hostname = &hostname($lonhost);
  237:     }
  238:     return if ($hostname eq '');
  239:     my ($rep,$uselocal);
  240:     if ($context eq 'install') {
  241:         $uselocal = 1;
  242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  243:         $uselocal = 1;
  244:     }
  245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  247:         if ($distro eq '') {
  248:             $uselocal = 0;
  249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  250:             if ($1 < 6) {
  251:                 $uselocal = 0;
  252:             }
  253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  254:             if ($1 < 12) {
  255:                 $uselocal = 0;
  256:             }
  257:         }
  258:     }
  259:     if ($uselocal) {
  260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  261:     } else {
  262:         $rep=&reply('servercerts',$lonhost);
  263:     }
  264:     my ($result,%returnhash);
  265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  266:         ($rep eq 'unknown_cmd')) {
  267:         $result = $rep;
  268:     } else {
  269:         $result = 'ok';
  270:         my @pairs=split(/\&/,$rep);
  271:         foreach my $item (@pairs) {
  272:             my ($key,$value)=split(/=/,$item,2);
  273:             my $what = &unescape($key);
  274:             $returnhash{$what}=&thaw_unescape($value);
  275:         }
  276:     }
  277:     return ($result,\%returnhash);
  278: }
  279: 
  280: sub get_server_loncaparev {
  281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  282:     if (defined($lonhost)) {
  283:         if (!defined(&hostname($lonhost))) {
  284:             undef($lonhost);
  285:         }
  286:     }
  287:     if (!defined($lonhost)) {
  288:         if (defined(&domain($dom,'primary'))) {
  289:             $lonhost=&domain($dom,'primary');
  290:             if ($lonhost eq 'no_host') {
  291:                 undef($lonhost);
  292:             }
  293:         }
  294:     }
  295:     if (defined($lonhost)) {
  296:         my $cachetime = 12*3600;
  297:         if (!$ignore_cache) {
  298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  299:             if (defined($cached)) {
  300:                 return $loncaparev;
  301:             }
  302:         }
  303:         my ($answer,$loncaparev);
  304:         my @ids=&current_machine_ids();
  305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  306:             $answer = $perlvar{'lonVersion'};
  307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  308:                 $loncaparev = $1;
  309:             }
  310:         } else {
  311:             $answer = &reply('serverloncaparev',$lonhost);
  312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  313:                 if ($caller eq 'loncron') {
  314:                     my $protocol = $protocol{$lonhost};
  315:                     $protocol = 'http' if ($protocol ne 'https');
  316:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  317:                     my $request=new HTTP::Request('GET',$url);
  318:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  319:                     unless ($response->is_error()) {
  320:                         my $content = $response->content;
  321:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  322:                             $loncaparev = $1;
  323:                         }
  324:                     }
  325:                 } else {
  326:                     $loncaparev = $loncaparevs{$lonhost};
  327:                 }
  328:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  329:                 $loncaparev = $1;
  330:             }
  331:         }
  332:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  333:     }
  334: }
  335: 
  336: sub get_server_homeID {
  337:     my ($hostname,$ignore_cache,$caller) = @_;
  338:     unless ($ignore_cache) {
  339:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  340:         if (defined($cached)) {
  341:             return $serverhomeID;
  342:         }
  343:     }
  344:     my $cachetime = 12*3600;
  345:     my $serverhomeID;
  346:     if ($caller eq 'loncron') { 
  347:         my @machine_ids = &machine_ids($hostname);
  348:         foreach my $id (@machine_ids) {
  349:             my $response = &reply('serverhomeID',$id);
  350:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  351:                 $serverhomeID = $response;
  352:                 last;
  353:             }
  354:         }
  355:         if ($serverhomeID eq '') {
  356:             $serverhomeID = $machine_ids[-1];
  357:         }
  358:     } else {
  359:         $serverhomeID = $serverhomeIDs{$hostname};
  360:     }
  361:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  362: }
  363: 
  364: sub get_remote_globals {
  365:     my ($lonhost,$whathash,$ignore_cache) = @_;
  366:     my ($result,%returnhash,%whatneeded);
  367:     if (ref($whathash) eq 'HASH') {
  368:         foreach my $what (sort(keys(%{$whathash}))) {
  369:             my $hashid = $lonhost.'-'.$what;
  370:             my ($response,$cached);
  371:             unless ($ignore_cache) {
  372:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  373:             }
  374:             if (defined($cached)) {
  375:                 $returnhash{$what} = $response;
  376:             } else {
  377:                 $whatneeded{$what} = 1;
  378:             }
  379:         }
  380:         if (keys(%whatneeded) == 0) {
  381:             $result = 'ok';
  382:         } else {
  383:             my $requested = &freeze_escape(\%whatneeded);
  384:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  385:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  386:                 ($rep eq 'unknown_cmd')) {
  387:                 $result = $rep;
  388:             } else {
  389:                 $result = 'ok';
  390:                 my @pairs=split(/\&/,$rep);
  391:                 foreach my $item (@pairs) {
  392:                     my ($key,$value)=split(/=/,$item,2);
  393:                     my $what = &unescape($key);
  394:                     my $hashid = $lonhost.'-'.$what;
  395:                     $returnhash{$what}=&thaw_unescape($value);
  396:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  397:                 }
  398:             }
  399:         }
  400:     }
  401:     return ($result,\%returnhash);
  402: }
  403: 
  404: sub remote_devalidate_cache {
  405:     my ($lonhost,$cachekeys) = @_;
  406:     my $items;
  407:     return unless (ref($cachekeys) eq 'ARRAY');
  408:     my $cachestr = join('&',@{$cachekeys});
  409:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  410:     return $response;
  411: }
  412: 
  413: # -------------------------------------------------- Non-critical communication
  414: sub subreply {
  415:     my ($cmd,$server)=@_;
  416:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  417:     #
  418:     #  With loncnew process trimming, there's a timing hole between lonc server
  419:     #  process exit and the master server picking up the listen on the AF_UNIX
  420:     #  socket.  In that time interval, a lock file will exist:
  421: 
  422:     my $lockfile=$peerfile.".lock";
  423:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  424: 	sleep(0.1);
  425:     }
  426:     # At this point, either a loncnew parent is listening or an old lonc
  427:     # or loncnew child is listening so we can connect or everything's dead.
  428:     #
  429:     #   We'll give the connection a few tries before abandoning it.  If
  430:     #   connection is not possible, we'll con_lost back to the client.
  431:     #   
  432:     my $client;
  433:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  434: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  435: 				      Type    => SOCK_STREAM,
  436: 				      Timeout => 10);
  437: 	if ($client) {
  438: 	    last;		# Connected!
  439: 	} else {
  440: 	    &create_connection(&hostname($server),$server);
  441: 	}
  442:         sleep(0.1);	# Try again later if failed connection.
  443:     }
  444:     my $answer;
  445:     if ($client) {
  446: 	print $client "sethost:$server:$cmd\n";
  447: 	$answer=<$client>;
  448: 	if (!$answer) { $answer="con_lost"; }
  449: 	chomp($answer);
  450:     } else {
  451: 	$answer = 'con_lost';	# Failed connection.
  452:     }
  453:     return $answer;
  454: }
  455: 
  456: sub reply {
  457:     my ($cmd,$server)=@_;
  458:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  459:     my $answer=subreply($cmd,$server);
  460:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  461:        &logthis("<font color=\"blue\">WARNING:".
  462:                 " $cmd to $server returned $answer</font>");
  463:     }
  464:     return $answer;
  465: }
  466: 
  467: # ----------------------------------------------------------- Send USR1 to lonc
  468: 
  469: sub reconlonc {
  470:     my ($lonid) = @_;
  471:     if ($lonid) {
  472:         my $hostname = &hostname($lonid);
  473: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  474: 	if ($hostname && -e $peerfile) {
  475: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  476: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  477: 					     Type    => SOCK_STREAM,
  478: 					     Timeout => 10);
  479: 	    if ($client) {
  480: 		print $client ("reset_retries\n");
  481: 		my $answer=<$client>;
  482: 		#reset just this one.
  483: 	    }
  484: 	}
  485: 	return;
  486:     }
  487: 
  488:     &logthis("Trying to reconnect lonc");
  489:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  490:     if (open(my $fh,"<",$loncfile)) {
  491: 	my $loncpid=<$fh>;
  492:         chomp($loncpid);
  493:         if (kill 0 => $loncpid) {
  494: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  495:             kill USR1 => $loncpid;
  496:             sleep 1;
  497:         } else {
  498: 	    &logthis(
  499:                "<font color=\"blue\">WARNING:".
  500:                " lonc at pid $loncpid not responding, giving up</font>");
  501:         }
  502:     } else {
  503: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  504:     }
  505: }
  506: 
  507: # ------------------------------------------------------ Critical communication
  508: 
  509: sub critical {
  510:     my ($cmd,$server)=@_;
  511:     unless (&hostname($server)) {
  512:         &logthis("<font color=\"blue\">WARNING:".
  513:                " Critical message to unknown server ($server)</font>");
  514:         return 'no_such_host';
  515:     }
  516:     my $answer=reply($cmd,$server);
  517:     if ($answer eq 'con_lost') {
  518: 	&reconlonc($server);
  519: 	my $answer=reply($cmd,$server);
  520:         if ($answer eq 'con_lost') {
  521:             my $now=time;
  522:             my $middlename=$cmd;
  523:             $middlename=substr($middlename,0,16);
  524:             $middlename=~s/\W//g;
  525:             my $dfilename=
  526:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  527:             $dumpcount++;
  528:             {
  529: 		my $dfh;
  530: 		if (open($dfh,">",$dfilename)) {
  531: 		    print $dfh "$cmd\n"; 
  532: 		    close($dfh);
  533: 		}
  534:             }
  535:             sleep 1;
  536:             my $wcmd='';
  537:             {
  538: 		my $dfh;
  539: 		if (open($dfh,"<",$dfilename)) {
  540: 		    $wcmd=<$dfh>; 
  541: 		    close($dfh);
  542: 		}
  543:             }
  544:             chomp($wcmd);
  545:             if ($wcmd eq $cmd) {
  546: 		&logthis("<font color=\"blue\">WARNING: ".
  547:                          "Connection buffer $dfilename: $cmd</font>");
  548:                 &logperm("D:$server:$cmd");
  549: 	        return 'con_delayed';
  550:             } else {
  551:                 &logthis("<font color=\"red\">CRITICAL:"
  552:                         ." Critical connection failed: $server $cmd</font>");
  553:                 &logperm("F:$server:$cmd");
  554:                 return 'con_failed';
  555:             }
  556:         }
  557:     }
  558:     return $answer;
  559: }
  560: 
  561: # ------------------------------------------- check if return value is an error
  562: 
  563: sub error {
  564:     my ($result) = @_;
  565:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  566: 	if ($2 == 2) { return undef; }
  567: 	return $1;
  568:     }
  569:     return undef;
  570: }
  571: 
  572: sub convert_and_load_session_env {
  573:     my ($lonidsdir,$handle)=@_;
  574:     my @profile;
  575:     {
  576: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  577: 	if (!$opened) {
  578: 	    return 0;
  579: 	}
  580: 	flock($idf,LOCK_SH);
  581: 	@profile=<$idf>;
  582: 	close($idf);
  583:     }
  584:     my %temp_env;
  585:     foreach my $line (@profile) {
  586: 	if ($line !~ m/=/) {
  587: 	    return 0;
  588: 	}
  589: 	chomp($line);
  590: 	my ($envname,$envvalue)=split(/=/,$line,2);
  591: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  592:     }
  593:     unlink("$lonidsdir/$handle.id");
  594:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  595: 	    0640)) {
  596: 	%disk_env = %temp_env;
  597: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  598: 	untie(%disk_env);
  599:     }
  600:     return 1;
  601: }
  602: 
  603: # ------------------------------------------- Transfer profile into environment
  604: my $env_loaded;
  605: sub transfer_profile_to_env {
  606:     my ($lonidsdir,$handle,$force_transfer) = @_;
  607:     if (!$force_transfer && $env_loaded) { return; } 
  608: 
  609:     if (!defined($lonidsdir)) {
  610: 	$lonidsdir = $perlvar{'lonIDsDir'};
  611:     }
  612:     if (!defined($handle)) {
  613:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  614:     }
  615: 
  616:     my $convert;
  617:     {
  618:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  619: 	if (!$opened) {
  620: 	    return;
  621: 	}
  622: 	flock($idf,LOCK_SH);
  623: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  624: 		&GDBM_READER(),0640)) {
  625: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  626: 	    untie(%disk_env);
  627: 	} else {
  628: 	    $convert = 1;
  629: 	}
  630:     }
  631:     if ($convert) {
  632: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  633: 	    &logthis("Failed to load session, or convert session.");
  634: 	}
  635:     }
  636: 
  637:     my %remove;
  638:     while ( my $envname = each(%env) ) {
  639:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  640:             if ($time < time-300) {
  641:                 $remove{$key}++;
  642:             }
  643:         }
  644:     }
  645: 
  646:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  647:     $env_loaded=1;
  648:     foreach my $expired_key (keys(%remove)) {
  649:         &delenv($expired_key);
  650:     }
  651: }
  652: 
  653: # ---------------------------------------------------- Check for valid session 
  654: sub check_for_valid_session {
  655:     my ($r,$name,$userhashref,$domref) = @_;
  656:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  657:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  658:     if ($name eq 'lonDAV') {
  659:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  660:     } else {
  661:         $lonidsdir=$r->dir_config('lonIDsDir');
  662:         if ($name eq '') {
  663:             $name = 'lonID';
  664:         }
  665:     }
  666:     if ($name eq 'lonID') {
  667:         $secure = 'lonSID';
  668:         $linkname = 'lonLinkID';
  669:         $pubname = 'lonPubID';
  670:         if (exists($cookies{$secure})) {
  671:             $lonid=$cookies{$secure};
  672:         } elsif (exists($cookies{$name})) {
  673:             $lonid=$cookies{$name};
  674:         } elsif (exists($cookies{$linkname})) {
  675:             $lonid=$cookies{$linkname};
  676:         } elsif (exists($cookies{$pubname})) {
  677:             $lonid=$cookies{$pubname};
  678:         }
  679:     } else {
  680:         $lonid=$cookies{$name};
  681:     }
  682:     return undef if (!$lonid);
  683: 
  684:     my $handle=&LONCAPA::clean_handle($lonid->value);
  685:     if (-l "$lonidsdir/$handle.id") {
  686:         my $link = readlink("$lonidsdir/$handle.id");
  687:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  688:             $handle = $1;
  689:         }
  690:     }
  691:     if (!-e "$lonidsdir/$handle.id") {
  692:         if ((ref($domref)) && ($name eq 'lonID') && 
  693:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  694:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  695:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  696:                 $$domref = $possudom;
  697:             }
  698:         }
  699:         return undef;
  700:     }
  701: 
  702:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  703:     return undef if (!$opened);
  704: 
  705:     flock($idf,LOCK_SH);
  706:     my %disk_env;
  707:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  708: 	    &GDBM_READER(),0640)) {
  709: 	return undef;	
  710:     }
  711: 
  712:     if (!defined($disk_env{'user.name'})
  713: 	|| !defined($disk_env{'user.domain'})) {
  714:         untie(%disk_env);
  715: 	return undef;
  716:     }
  717: 
  718:     if (ref($userhashref) eq 'HASH') {
  719:         $userhashref->{'name'} = $disk_env{'user.name'};
  720:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  721:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  722:         if ($userhashref->{'lti'}) {
  723:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  724:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  725:         }
  726:     }
  727:     untie(%disk_env);
  728: 
  729:     return $handle;
  730: }
  731: 
  732: sub timed_flock {
  733:     my ($file,$lock_type) = @_;
  734:     my $failed=0;
  735:     eval {
  736: 	local $SIG{__DIE__}='DEFAULT';
  737: 	local $SIG{ALRM}=sub {
  738: 	    $failed=1;
  739: 	    die("failed lock");
  740: 	};
  741: 	alarm(13);
  742: 	flock($file,$lock_type);
  743: 	alarm(0);
  744:     };
  745:     if ($failed) {
  746: 	return undef;
  747:     } else {
  748: 	return 1;
  749:     }
  750: }
  751: 
  752: sub get_sessionfile_vars {
  753:     my ($handle,$lonidsdir,$storearr) = @_;
  754:     my %returnhash;
  755:     unless (ref($storearr) eq 'ARRAY') {
  756:         return %returnhash;
  757:     }
  758:     if (-l "$lonidsdir/$handle.id") {
  759:         my $link = readlink("$lonidsdir/$handle.id");
  760:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  761:             $handle = $1;
  762:         }
  763:     }
  764:     if ((-e "$lonidsdir/$handle.id") &&
  765:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  766:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  767:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  768:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  769:                 flock($idf,LOCK_SH);
  770:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  771:                         &GDBM_READER(),0640)) {
  772:                     foreach my $item (@{$storearr}) {
  773:                         $returnhash{$item} = $disk_env{$item};
  774:                     }
  775:                     untie(%disk_env);
  776:                 }
  777:             }
  778:         }
  779:     }
  780:     return %returnhash;
  781: }
  782: 
  783: # ---------------------------------------------------------- Append Environment
  784: 
  785: sub appenv {
  786:     my ($newenv,$roles) = @_;
  787:     if (ref($newenv) eq 'HASH') {
  788:         foreach my $key (keys(%{$newenv})) {
  789:             my $refused = 0;
  790: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  791:                 $refused = 1;
  792:                 if (ref($roles) eq 'ARRAY') {
  793:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  794:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  795:                         $refused = 0;
  796:                     }
  797:                 }
  798:             }
  799:             if ($refused) {
  800:                 &logthis("<font color=\"blue\">WARNING: ".
  801:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  802:                          .'</font>');
  803: 	        delete($newenv->{$key});
  804:             } else {
  805:                 $env{$key}=$newenv->{$key};
  806:             }
  807:         }
  808:         my $lonids = $perlvar{'lonIDsDir'};
  809:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  810:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  811:             if ($opened
  812: 	        && &timed_flock($env_file,LOCK_EX)
  813: 	        &&
  814: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  815: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  816: 	        while (my ($key,$value) = each(%{$newenv})) {
  817: 	            $disk_env{$key} = $value;
  818: 	        }
  819: 	        untie(%disk_env);
  820:             }
  821:         }
  822:     }
  823:     return 'ok';
  824: }
  825: # ----------------------------------------------------- Delete from Environment
  826: 
  827: sub delenv {
  828:     my ($delthis,$regexp,$roles) = @_;
  829:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  830:         my $refused = 1;
  831:         if (ref($roles) eq 'ARRAY') {
  832:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  833:             if (grep(/^\Q$role\E$/,@{$roles})) {
  834:                 $refused = 0;
  835:             }
  836:         }
  837:         if ($refused) {
  838:             &logthis("<font color=\"blue\">WARNING: ".
  839:                      "Attempt to delete from environment ".$delthis);
  840:             return 'error';
  841:         }
  842:     }
  843:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  844:     if ($opened
  845: 	&& &timed_flock($env_file,LOCK_EX)
  846: 	&&
  847: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  848: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  849: 	foreach my $key (keys(%disk_env)) {
  850: 	    if ($regexp) {
  851:                 if ($key=~/^$delthis/) {
  852:                     delete($env{$key});
  853:                     delete($disk_env{$key});
  854:                 } 
  855:             } else {
  856:                 if ($key=~/^\Q$delthis\E/) {
  857: 		    delete($env{$key});
  858: 		    delete($disk_env{$key});
  859: 	        }
  860:             }
  861: 	}
  862: 	untie(%disk_env);
  863:     }
  864:     return 'ok';
  865: }
  866: 
  867: sub get_env_multiple {
  868:     my ($name) = @_;
  869:     my @values;
  870:     if (defined($env{$name})) {
  871:         # exists is it an array
  872:         if (ref($env{$name})) {
  873:             @values=@{ $env{$name} };
  874:         } else {
  875:             $values[0]=$env{$name};
  876:         }
  877:     }
  878:     return(@values);
  879: }
  880: 
  881: # ------------------------------------------------------------------- Locking
  882: 
  883: sub set_lock {
  884:     my ($text)=@_;
  885:     $locknum++;
  886:     my $id=$$.'-'.$locknum;
  887:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  888:              'session.lock.'.$id => $text});
  889:     return $id;
  890: }
  891: 
  892: sub get_locks {
  893:     my $num=0;
  894:     my %texts=();
  895:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  896:        if ($lock=~/\w/) {
  897:           $num++;
  898:           $texts{$lock}=$env{'session.lock.'.$lock};
  899:        }
  900:    }
  901:    return ($num,%texts);
  902: }
  903: 
  904: sub remove_lock {
  905:     my ($id)=@_;
  906:     my $newlocks='';
  907:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  908:        if (($lock=~/\w/) && ($lock ne $id)) {
  909:           $newlocks.=','.$lock;
  910:        }
  911:     }
  912:     &appenv({'session.locks' => $newlocks});
  913:     &delenv('session.lock.'.$id);
  914: }
  915: 
  916: sub remove_all_locks {
  917:     my $activelocks=$env{'session.locks'};
  918:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  919:        if ($lock=~/\w/) {
  920:           &remove_lock($lock);
  921:        }
  922:     }
  923: }
  924: 
  925: 
  926: # ------------------------------------------ Find out current server userload
  927: sub userload {
  928:     my $numusers=0;
  929:     {
  930: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  931: 	my $filename;
  932: 	my $curtime=time;
  933: 	while ($filename=readdir(LONIDS)) {
  934: 	    next if ($filename eq '.' || $filename eq '..');
  935: 	    next if ($filename =~ /publicuser_\d+\.id/);
  936:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  937: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  938: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  939: 	}
  940: 	closedir(LONIDS);
  941:     }
  942:     my $userloadpercent=0;
  943:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  944:     if ($maxuserload) {
  945: 	$userloadpercent=100*$numusers/$maxuserload;
  946:     }
  947:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  948:     return $userloadpercent;
  949: }
  950: 
  951: # ------------------------------ Find server with least workload from spare.tab
  952: 
  953: sub spareserver {
  954:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  955:     my $spare_server;
  956:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  957:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  958:                                                      :  $userloadpercent;
  959:     my ($uint_dom,$remotesessions);
  960:     if (($udom ne '') && (&domain($udom) ne '')) {
  961:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  962:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  963:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  964:         $remotesessions = $udomdefaults{'remotesessions'};
  965:     }
  966:     my $spareshash = &this_host_spares($udom);
  967:     if (ref($spareshash) eq 'HASH') {
  968:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  969:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  970:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  971:                                              $try_server));
  972: 	        ($spare_server, $lowest_load) =
  973: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  974:             }
  975:         }
  976: 
  977:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  978: 
  979:         if (!$found_server) {
  980:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  981: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  982:                     next unless (&spare_can_host($udom,$uint_dom,
  983:                                                  $remotesessions,$try_server));
  984: 	            ($spare_server, $lowest_load) =
  985: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  986:                 }
  987: 	    }
  988:         }
  989:     }
  990: 
  991:     if (!$want_server_name) {
  992:         my $protocol = 'http';
  993:         if ($protocol{$spare_server} eq 'https') {
  994:             $protocol = $protocol{$spare_server};
  995:         }
  996:         if (defined($spare_server)) {
  997:             my $hostname = &hostname($spare_server);
  998:             if (defined($hostname)) {
  999: 	        $spare_server = $protocol.'://'.$hostname;
 1000:             }
 1001:         }
 1002:     }
 1003:     return $spare_server;
 1004: }
 1005: 
 1006: sub compare_server_load {
 1007:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1008: 
 1009:     if ($required) {
 1010:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1011:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1012:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1013:         if (($major eq '' && $minor eq '') ||
 1014:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1015:             return ($spare_server,$lowest_load);
 1016:         }
 1017:     }
 1018: 
 1019:     my $loadans     = &reply('load',    $try_server);
 1020:     my $userloadans = &reply('userload',$try_server);
 1021: 
 1022:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1023: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1024:     }
 1025: 
 1026:     my $load;
 1027:     if ($loadans =~ /\d/) {
 1028: 	if ($userloadans =~ /\d/) {
 1029: 	    #both are numbers, pick the bigger one
 1030: 	    $load = ($loadans > $userloadans) ? $loadans 
 1031: 		                              : $userloadans;
 1032: 	} else {
 1033: 	    $load = $loadans;
 1034: 	}
 1035:     } else {
 1036: 	$load = $userloadans;
 1037:     }
 1038: 
 1039:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1040: 	$spare_server = $try_server;
 1041: 	$lowest_load  = $load;
 1042:     }
 1043:     return ($spare_server,$lowest_load);
 1044: }
 1045: 
 1046: # --------------------------- ask offload servers if user already has a session
 1047: sub find_existing_session {
 1048:     my ($udom,$uname) = @_;
 1049:     my $spareshash = &this_host_spares($udom);
 1050:     if (ref($spareshash) eq 'HASH') {
 1051:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1052:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1053:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1054:             }
 1055:         }
 1056:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1057:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1058:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1059:             }
 1060:         }
 1061:     }
 1062:     return;
 1063: }
 1064: 
 1065: # check if user's browser sent load balancer cookie and server still has session
 1066: # and is not overloaded.
 1067: sub check_for_balancer_cookie {
 1068:     my ($r,$update_mtime) = @_;
 1069:     my ($otherserver,$cookie);
 1070:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1071:     if (exists($cookies{'balanceID'})) {
 1072:         my $balid = $cookies{'balanceID'};
 1073:         $cookie=&LONCAPA::clean_handle($balid->value);
 1074:         my $balancedir=$r->dir_config('lonBalanceDir');
 1075:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1076:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1077:                 my ($possudom,$possuname) = ($1,$2);
 1078:                 my $has_session = 0;
 1079:                 if ((&domain($possudom) ne '') &&
 1080:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1081:                     my $try_server;
 1082:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1083:                     if ($opened) {
 1084:                         flock($idf,LOCK_SH);
 1085:                         while (my $line = <$idf>) {
 1086:                             chomp($line);
 1087:                             if (&hostname($line) ne '') {
 1088:                                 $try_server = $line;
 1089:                                 last;
 1090:                             }
 1091:                         }
 1092:                         close($idf);
 1093:                         if (($try_server) &&
 1094:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1095:                             my $lowest_load = 30000;
 1096:                             ($otherserver,$lowest_load) =
 1097:                                 &compare_server_load($try_server,undef,$lowest_load);
 1098:                             if ($otherserver ne '' && $lowest_load < 100) {
 1099:                                 $has_session = 1;
 1100:                             } else {
 1101:                                 undef($otherserver);
 1102:                             }
 1103:                         }
 1104:                     }
 1105:                 }
 1106:                 if ($has_session) {
 1107:                     if ($update_mtime) {
 1108:                         my $atime = my $mtime = time;
 1109:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1110:                     }
 1111:                 } else {
 1112:                     unlink("$balancedir/$cookie.id");
 1113:                 }
 1114:             }
 1115:         }
 1116:     }
 1117:     return ($otherserver,$cookie);
 1118: }
 1119: 
 1120: sub delbalcookie {
 1121:     my ($cookie,$balancer) =@_;
 1122:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1123:         my ($udom,$uname) = ($1,$2);
 1124:         my $uprimary_id = &domain($udom,'primary');
 1125:         my $uintdom = &internet_dom($uprimary_id);
 1126:         my $intdom = &internet_dom($balancer);
 1127:         my $serverhomedom = &host_domain($balancer);
 1128:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1129:             return &reply("delbalcookie:$cookie",$balancer);
 1130:         }
 1131:     }
 1132: }
 1133: 
 1134: # -------------------------------- ask if server already has a session for user
 1135: sub has_user_session {
 1136:     my ($lonid,$udom,$uname) = @_;
 1137:     my $result = &reply(join(':','userhassession',
 1138: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1139:     return 1 if ($result eq 'ok');
 1140: 
 1141:     return 0;
 1142: }
 1143: 
 1144: # --------- determine least loaded server in a user's domain which allows login
 1145: 
 1146: sub choose_server {
 1147:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1148:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1149:     my %servers = &get_servers($udom);
 1150:     my $lowest_load = 30000;
 1151:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1152:     if ($skiploadbal) {
 1153:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1154:         unless (defined($cached)) {
 1155:             my $cachetime = 60*60*24;
 1156:             my %domconfig =
 1157:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1158:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1159:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1160:                                            $cachetime);
 1161:             }
 1162:         }
 1163:     }
 1164:     foreach my $lonhost (keys(%servers)) {
 1165:         if ($skiploadbal) {
 1166:             if (ref($balancers) eq 'HASH') {
 1167:                 next if (exists($balancers->{$lonhost}));
 1168:             }
 1169:         }
 1170:         my $loginvia;
 1171:         if ($checkloginvia) {
 1172:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1173:             if ($loginvia) {
 1174:                 my ($server,$path) = split(/:/,$loginvia);
 1175:                 ($login_host, $lowest_load) =
 1176:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1177:                 if ($login_host eq $server) {
 1178:                     $portal_path = $path;
 1179:                     $isredirect = 1;
 1180:                 }
 1181:             } else {
 1182:                 ($login_host, $lowest_load) =
 1183:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1184:                 if ($login_host eq $lonhost) {
 1185:                     $portal_path = '';
 1186:                     $isredirect = ''; 
 1187:                 }
 1188:             }
 1189:         } else {
 1190:             ($login_host, $lowest_load) =
 1191:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1192:         }
 1193:     }
 1194:     if ($login_host ne '') {
 1195:         $hostname = &hostname($login_host);
 1196:     }
 1197:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1198: }
 1199: 
 1200: # --------------------------------------------- Try to change a user's password
 1201: 
 1202: sub changepass {
 1203:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1204:     $currentpass = &escape($currentpass);
 1205:     $newpass     = &escape($newpass);
 1206:     my $lonhost = $perlvar{'lonHostID'};
 1207:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1208: 		       $server);
 1209:     if (! $answer) {
 1210: 	&logthis("No reply on password change request to $server ".
 1211: 		 "by $uname in domain $udom.");
 1212:     } elsif ($answer =~ "^ok") {
 1213:         &logthis("$uname in $udom successfully changed their password ".
 1214: 		 "on $server.");
 1215:     } elsif ($answer =~ "^pwchange_failure") {
 1216: 	&logthis("$uname in $udom was unable to change their password ".
 1217: 		 "on $server.  The action was blocked by either lcpasswd ".
 1218: 		 "or pwchange");
 1219:     } elsif ($answer =~ "^non_authorized") {
 1220:         &logthis("$uname in $udom did not get their password correct when ".
 1221: 		 "attempting to change it on $server.");
 1222:     } elsif ($answer =~ "^auth_mode_error") {
 1223:         &logthis("$uname in $udom attempted to change their password despite ".
 1224: 		 "not being locally or internally authenticated on $server.");
 1225:     } elsif ($answer =~ "^unknown_user") {
 1226:         &logthis("$uname in $udom attempted to change their password ".
 1227: 		 "on $server but were unable to because $server is not ".
 1228: 		 "their home server.");
 1229:     } elsif ($answer =~ "^refused") {
 1230: 	&logthis("$server refused to change $uname in $udom password because ".
 1231: 		 "it was sent an unencrypted request to change the password.");
 1232:     } elsif ($answer =~ "invalid_client") {
 1233:         &logthis("$server refused to change $uname in $udom password because ".
 1234:                  "it was a reset by e-mail originating from an invalid server.");
 1235:     }
 1236:     return $answer;
 1237: }
 1238: 
 1239: # ----------------------- Try to determine user's current authentication scheme
 1240: 
 1241: sub queryauthenticate {
 1242:     my ($uname,$udom)=@_;
 1243:     my $uhome=&homeserver($uname,$udom);
 1244:     if (!$uhome) {
 1245: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1246: 	return 'no_host';
 1247:     }
 1248:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1249:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1250: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1251:     }
 1252:     return $answer;
 1253: }
 1254: 
 1255: # --------- Try to authenticate user from domain's lib servers (first this one)
 1256: 
 1257: sub authenticate {
 1258:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1259:     $upass=&escape($upass);
 1260:     $uname= &LONCAPA::clean_username($uname);
 1261:     my $uhome=&homeserver($uname,$udom,1);
 1262:     my $newhome;
 1263:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1264: # Maybe the machine was offline and only re-appeared again recently?
 1265:         &reconlonc();
 1266: # One more
 1267: 	$uhome=&homeserver($uname,$udom,1);
 1268:         if (($uhome eq 'no_host') && $checkdefauth) {
 1269:             if (defined(&domain($udom,'primary'))) {
 1270:                 $newhome=&domain($udom,'primary');
 1271:             }
 1272:             if ($newhome ne '') {
 1273:                 $uhome = $newhome;
 1274:             }
 1275:         }
 1276: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1277: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1278: 	    return 'no_host';
 1279:         }
 1280:     }
 1281:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1282:     if ($answer eq 'authorized') {
 1283:         if ($newhome) {
 1284:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1285:             return 'no_account_on_host'; 
 1286:         } else {
 1287:             &logthis("User $uname at $udom authorized by $uhome");
 1288:             return $uhome;
 1289:         }
 1290:     }
 1291:     if ($answer eq 'non_authorized') {
 1292: 	&logthis("User $uname at $udom rejected by $uhome");
 1293: 	return 'no_host'; 
 1294:     }
 1295:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1296:     return 'no_host';
 1297: }
 1298: 
 1299: sub can_host_session {
 1300:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1301:     my $canhost = 1;
 1302:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1303:     if (ref($remotesessions) eq 'HASH') {
 1304:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1305:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1306:                 $canhost = 0;
 1307:             } else {
 1308:                 $canhost = 1;
 1309:             }
 1310:         }
 1311:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1312:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1313:                 $canhost = 1;
 1314:             } else {
 1315:                 $canhost = 0;
 1316:             }
 1317:         }
 1318:         if ($canhost) {
 1319:             if ($remotesessions->{'version'} ne '') {
 1320:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1321:                 if ($reqmajor ne '' && $reqminor ne '') {
 1322:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1323:                         my $major = $1;
 1324:                         my $minor = $2;
 1325:                         if (($major < $reqmajor ) ||
 1326:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1327:                             $canhost = 0;
 1328:                         }
 1329:                     } else {
 1330:                         $canhost = 0;
 1331:                     }
 1332:                 }
 1333:             }
 1334:         }
 1335:     }
 1336:     if ($canhost) {
 1337:         if (ref($hostedsessions) eq 'HASH') {
 1338:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1339:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1340:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1341:                 if (($uint_dom ne '') && 
 1342:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1343:                     $canhost = 0;
 1344:                 } else {
 1345:                     $canhost = 1;
 1346:                 }
 1347:             }
 1348:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1349:                 if (($uint_dom ne '') && 
 1350:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1351:                     $canhost = 1;
 1352:                 } else {
 1353:                     $canhost = 0;
 1354:                 }
 1355:             }
 1356:         }
 1357:     }
 1358:     return $canhost;
 1359: }
 1360: 
 1361: sub spare_can_host {
 1362:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1363:     my $canhost=1;
 1364:     my $try_server_hostname = &hostname($try_server);
 1365:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1366:     my $serverhomedom = &host_domain($serverhomeID);
 1367:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1368:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1369:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1370:             $canhost = 0;
 1371:         }
 1372:     }
 1373:     if (($canhost) && ($uint_dom)) {
 1374:         my @intdoms;
 1375:         my $internet_names = &get_internet_names($try_server);
 1376:         if (ref($internet_names) eq 'ARRAY') {
 1377:             @intdoms = @{$internet_names};
 1378:         }
 1379:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1380:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1381:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1382:                                          $remotesessions,
 1383:                                          $defdomdefaults{'hostedsessions'});
 1384:         }
 1385:     }
 1386:     return $canhost;
 1387: }
 1388: 
 1389: sub this_host_spares {
 1390:     my ($dom) = @_;
 1391:     my ($dom_in_use,$lonhost_in_use,$result);
 1392:     my @hosts = &current_machine_ids();
 1393:     foreach my $lonhost (@hosts) {
 1394:         if (&host_domain($lonhost) eq $dom) {
 1395:             $dom_in_use = $dom;
 1396:             $lonhost_in_use = $lonhost;
 1397:             last;
 1398:         }
 1399:     }
 1400:     if ($dom_in_use ne '') {
 1401:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1402:     }
 1403:     if (ref($result) ne 'HASH') {
 1404:         $lonhost_in_use = $perlvar{'lonHostID'};
 1405:         $dom_in_use = &host_domain($lonhost_in_use);
 1406:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1407:         if (ref($result) ne 'HASH') {
 1408:             $result = \%spareid;
 1409:         }
 1410:     }
 1411:     return $result;
 1412: }
 1413: 
 1414: sub spares_for_offload  {
 1415:     my ($dom_in_use,$lonhost_in_use) = @_;
 1416:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1417:     if (defined($cached)) {
 1418:         return $result;
 1419:     } else {
 1420:         my $cachetime = 60*60*24;
 1421:         my %domconfig =
 1422:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1423:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1424:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1425:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1426:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return;
 1432: }
 1433: 
 1434: sub get_lonbalancer_config {
 1435:     my ($servers) = @_;
 1436:     my ($currbalancer,$currtargets);
 1437:     if (ref($servers) eq 'HASH') {
 1438:         foreach my $server (keys(%{$servers})) {
 1439:             my %what = (
 1440:                          spareid => 1,
 1441:                          perlvar => 1,
 1442:                        );
 1443:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1444:             if ($result eq 'ok') {
 1445:                 if (ref($returnhash) eq 'HASH') {
 1446:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1447:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1448:                             $currbalancer = $server;
 1449:                             $currtargets = {};
 1450:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1451:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1452:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1453:                                 }
 1454:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1455:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1456:                                 }
 1457:                             }
 1458:                             last;
 1459:                         }
 1460:                     }
 1461:                 }
 1462:             }
 1463:         }
 1464:     }
 1465:     return ($currbalancer,$currtargets);
 1466: }
 1467: 
 1468: sub check_loadbalancing {
 1469:     my ($uname,$udom,$caller) = @_;
 1470:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1471:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1472:     my $lonhost = $perlvar{'lonHostID'};
 1473:     my @hosts = &current_machine_ids();
 1474:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1475:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1476:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1477:     my $serverhomedom = &host_domain($lonhost);
 1478:     my $domneedscache;
 1479:     my $cachetime = 60*60*24;
 1480: 
 1481:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1482:         $dom_in_use = $udom;
 1483:         $homeintdom = 1;
 1484:     } else {
 1485:         $dom_in_use = $serverhomedom;
 1486:     }
 1487:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1488:     unless (defined($cached)) {
 1489:         my %domconfig =
 1490:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1491:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1492:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1493:         } else {
 1494:             $domneedscache = $dom_in_use;
 1495:         }
 1496:     }
 1497:     if (ref($result) eq 'HASH') {
 1498:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1499:             &check_balancer_result($result,@hosts);
 1500:         if ($is_balancer) {
 1501:             if (ref($currrules) eq 'HASH') {
 1502:                 if ($homeintdom) {
 1503:                     if ($uname ne '') {
 1504:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1505:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1506:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1507:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1508:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1509:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1510:                             }
 1511:                         }
 1512:                         if ($rule_in_effect eq '') {
 1513:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1514:                             if ($userenv{'inststatus'} ne '') {
 1515:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1516:                                 my ($othertitle,$usertypes,$types) =
 1517:                                     &Apache::loncommon::sorted_inst_types($udom);
 1518:                                 if (ref($types) eq 'ARRAY') {
 1519:                                     foreach my $type (@{$types}) {
 1520:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1521:                                             if (exists($currrules->{$type})) {
 1522:                                                 $rule_in_effect = $currrules->{$type};
 1523:                                             }
 1524:                                         }
 1525:                                     }
 1526:                                 }
 1527:                             } else {
 1528:                                 if (exists($currrules->{'default'})) {
 1529:                                     $rule_in_effect = $currrules->{'default'};
 1530:                                 }
 1531:                             }
 1532:                         }
 1533:                     } else {
 1534:                         if (exists($currrules->{'default'})) {
 1535:                             $rule_in_effect = $currrules->{'default'};
 1536:                         }
 1537:                     }
 1538:                 } else {
 1539:                     if ($currrules->{'_LC_external'} ne '') {
 1540:                         $rule_in_effect = $currrules->{'_LC_external'};
 1541:                     }
 1542:                 }
 1543:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1544:                                                        $uname,$udom);
 1545:             }
 1546:         }
 1547:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1548:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1549:         unless (defined($cached)) {
 1550:             my %domconfig =
 1551:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1552:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1553:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1554:             } else {
 1555:                 $domneedscache = $serverhomedom;
 1556:             }
 1557:         }
 1558:         if (ref($result) eq 'HASH') {
 1559:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1560:                 &check_balancer_result($result,@hosts);
 1561:             if ($is_balancer) {
 1562:                 if (ref($currrules) eq 'HASH') {
 1563:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1564:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1565:                     }
 1566:                 }
 1567:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1568:                                                        $uname,$udom);
 1569:             }
 1570:         } else {
 1571:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1572:                 $is_balancer = 1;
 1573:                 $offloadto = &this_host_spares($dom_in_use);
 1574:             }
 1575:             unless (defined($cached)) {
 1576:                 $domneedscache = $serverhomedom;
 1577:             }
 1578:         }
 1579:     } else {
 1580:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1581:             $is_balancer = 1;
 1582:             $offloadto = &this_host_spares($dom_in_use);
 1583:         }
 1584:         unless (defined($cached)) {
 1585:             $domneedscache = $serverhomedom;
 1586:         }
 1587:     }
 1588:     if ($domneedscache) {
 1589:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1590:     }
 1591:     if ($is_balancer) {
 1592:         my $lowest_load = 30000;
 1593:         if (ref($offloadto) eq 'HASH') {
 1594:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1595:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1596:                     ($otherserver,$lowest_load) =
 1597:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1598:                 }
 1599:             }
 1600:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1601: 
 1602:             if (!$found_server) {
 1603:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1604:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1605:                         ($otherserver,$lowest_load) =
 1606:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1607:                     }
 1608:                 }
 1609:             }
 1610:         } elsif (ref($offloadto) eq 'ARRAY') {
 1611:             if (@{$offloadto} == 1) {
 1612:                 $otherserver = $offloadto->[0];
 1613:             } elsif (@{$offloadto} > 1) {
 1614:                 foreach my $try_server (@{$offloadto}) {
 1615:                     ($otherserver,$lowest_load) =
 1616:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1617:                 }
 1618:             }
 1619:         }
 1620:         unless ($caller eq 'login') {
 1621:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1622:                 $is_balancer = 0;
 1623:                 if ($uname ne '' && $udom ne '') {
 1624:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1625:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1626:                                  'user.loadbalcheck.time' => time});
 1627:                     }
 1628:                 }
 1629:             }
 1630:         }
 1631:         unless ($homeintdom) {
 1632:             undef($setcookie);
 1633:         }
 1634:     }
 1635:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1636: }
 1637: 
 1638: sub check_balancer_result {
 1639:     my ($result,@hosts) = @_;
 1640:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1641:     if (ref($result) eq 'HASH') {
 1642:         if ($result->{'lonhost'} ne '') {
 1643:             my $currbalancer = $result->{'lonhost'};
 1644:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1645:                 $is_balancer = 1;
 1646:                 $currtargets = $result->{'targets'};
 1647:                 $currrules = $result->{'rules'};
 1648:             }
 1649:             $dom_balancers = $currbalancer;
 1650:         } else {
 1651:             if (keys(%{$result})) {
 1652:                 foreach my $key (keys(%{$result})) {
 1653:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1654:                         (ref($result->{$key}) eq 'HASH')) {
 1655:                         $is_balancer = 1;
 1656:                         $currrules = $result->{$key}{'rules'};
 1657:                         $currtargets = $result->{$key}{'targets'};
 1658:                         $setcookie = $result->{$key}{'cookie'};
 1659:                         last;
 1660:                     }
 1661:                 }
 1662:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1663:             }
 1664:         }
 1665:     }
 1666:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1667: }
 1668: 
 1669: sub get_loadbalancer_targets {
 1670:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1671:     my $offloadto;
 1672:     if ($rule_in_effect eq 'none') {
 1673:         return [$perlvar{'lonHostID'}];
 1674:     } elsif ($rule_in_effect eq '') {
 1675:         $offloadto = $currtargets;
 1676:     } else {
 1677:         if ($rule_in_effect eq 'homeserver') {
 1678:             my $homeserver = &homeserver($uname,$udom);
 1679:             if ($homeserver ne 'no_host') {
 1680:                 $offloadto = [$homeserver];
 1681:             }
 1682:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1683:             my %domconfig =
 1684:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1685:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1686:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1687:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1688:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1689:                     }
 1690:                 }
 1691:             } else {
 1692:                 my %servers = &internet_dom_servers($udom);
 1693:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1694:                 if (&hostname($remotebalancer) ne '') {
 1695:                     $offloadto = [$remotebalancer];
 1696:                 }
 1697:             }
 1698:         } elsif (&hostname($rule_in_effect) ne '') {
 1699:             $offloadto = [$rule_in_effect];
 1700:         }
 1701:     }
 1702:     return $offloadto;
 1703: }
 1704: 
 1705: sub internet_dom_servers {
 1706:     my ($dom) = @_;
 1707:     my (%uniqservers,%servers);
 1708:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1709:     my @machinedoms = &machine_domains($primaryserver);
 1710:     foreach my $mdom (@machinedoms) {
 1711:         my %currservers = %servers;
 1712:         my %server = &get_servers($mdom);
 1713:         %servers = (%currservers,%server);
 1714:     }
 1715:     my %by_hostname;
 1716:     foreach my $id (keys(%servers)) {
 1717:         push(@{$by_hostname{$servers{$id}}},$id);
 1718:     }
 1719:     foreach my $hostname (sort(keys(%by_hostname))) {
 1720:         if (@{$by_hostname{$hostname}} > 1) {
 1721:             my $match = 0;
 1722:             foreach my $id (@{$by_hostname{$hostname}}) {
 1723:                 if (&host_domain($id) eq $dom) {
 1724:                     $uniqservers{$id} = $hostname;
 1725:                     $match = 1;
 1726:                 }
 1727:             }
 1728:             unless ($match) {
 1729:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1730:             }
 1731:         } else {
 1732:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1733:         }
 1734:     }
 1735:     return %uniqservers;
 1736: }
 1737: 
 1738: sub trusted_domains {
 1739:     my ($cmdtype,$calldom) = @_;
 1740:     my ($trusted,$untrusted);
 1741:     if (&domain($calldom) eq '') {
 1742:         return ($trusted,$untrusted);
 1743:     }
 1744:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1745:         return ($trusted,$untrusted);
 1746:     }
 1747:     my $callprimary = &domain($calldom,'primary');
 1748:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1749:     if ($intcalldom eq '') {
 1750:         return ($trusted,$untrusted);
 1751:     }
 1752: 
 1753:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1754:     unless (defined($cached)) {
 1755:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1756:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1757:         $trustconfig = $domconfig{'trust'};
 1758:     }
 1759:     if (ref($trustconfig)) {
 1760:         my (%possexc,%possinc,@allexc,@allinc); 
 1761:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1762:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1763:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1764:             }
 1765:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1766:                 $possinc{$intcalldom} = 1;
 1767:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1768:             }
 1769:         }
 1770:         if (keys(%possexc)) {
 1771:             if (keys(%possinc)) {
 1772:                 foreach my $key (sort(keys(%possexc))) {
 1773:                     next if ($key eq $intcalldom);
 1774:                     unless ($possinc{$key}) {
 1775:                         push(@allexc,$key);
 1776:                     }
 1777:                 }
 1778:             } else {
 1779:                 @allexc = sort(keys(%possexc));
 1780:             }
 1781:         }
 1782:         if (keys(%possinc)) {
 1783:             $possinc{$intcalldom} = 1;
 1784:             @allinc = sort(keys(%possinc));
 1785:         }
 1786:         if ((@allexc > 0) || (@allinc > 0)) {
 1787:             my %doms_by_intdom;
 1788:             my %allintdoms = &all_host_intdom();
 1789:             my %alldoms = &all_host_domain();
 1790:             foreach my $key (%allintdoms) {
 1791:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1792:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1793:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1794:                     }
 1795:                 } else {
 1796:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1797:                 }
 1798:             }
 1799:             foreach my $exc (@allexc) {
 1800:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1801:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1802:                 }
 1803:             }
 1804:             foreach my $inc (@allinc) {
 1805:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1806:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1807:                 }
 1808:             }
 1809:         }
 1810:     }
 1811:     return ($trusted,$untrusted);
 1812: }
 1813: 
 1814: sub will_trust {
 1815:     my ($cmdtype,$domain,$possdom) = @_;
 1816:     return 1 if ($domain eq $possdom);
 1817:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1818:     my $willtrust; 
 1819:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1820:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1821:             $willtrust = 1;
 1822:         }
 1823:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1824:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1825:             $willtrust = 1;
 1826:         }
 1827:     } else {
 1828:         $willtrust = 1;
 1829:     }
 1830:     return $willtrust;
 1831: }
 1832: 
 1833: # ---------------------- Find the homebase for a user from domain's lib servers
 1834: 
 1835: my %homecache;
 1836: sub homeserver {
 1837:     my ($uname,$udom,$ignoreBadCache)=@_;
 1838:     my $index="$uname:$udom";
 1839: 
 1840:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1841: 
 1842:     my %servers = &get_servers($udom,'library');
 1843:     foreach my $tryserver (keys(%servers)) {
 1844:         next if ($ignoreBadCache ne 'true' && 
 1845: 		 exists($badServerCache{$tryserver}));
 1846: 
 1847: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1848: 	if ($answer eq 'found') {
 1849: 	    delete($badServerCache{$tryserver}); 
 1850: 	    return $homecache{$index}=$tryserver;
 1851: 	} elsif ($answer eq 'no_host') {
 1852: 	    $badServerCache{$tryserver}=1;
 1853: 	}
 1854:     }    
 1855:     return 'no_host';
 1856: }
 1857: 
 1858: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1859: 
 1860: sub idget {
 1861:     my ($udom,$idsref,$namespace)=@_;
 1862:     my %returnhash=();
 1863:     my @ids=(); 
 1864:     if (ref($idsref) eq 'ARRAY') {
 1865:         @ids = @{$idsref};
 1866:     } else {
 1867:         return %returnhash; 
 1868:     }
 1869:     if ($namespace eq '') {
 1870:         $namespace = 'ids';
 1871:     }
 1872:     
 1873:     my %servers = &get_servers($udom,'library');
 1874:     foreach my $tryserver (keys(%servers)) {
 1875: 	my $idlist=join('&', map { &escape($_); } @ids);
 1876: 	if ($namespace eq 'ids') {
 1877: 	    $idlist=~tr/A-Z/a-z/;
 1878: 	}
 1879: 	my $reply;
 1880: 	if ($namespace eq 'ids') {
 1881: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1882: 	} else {
 1883: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1884: 	}
 1885: 	my @answer=();
 1886: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1887: 	    @answer=split(/\&/,$reply);
 1888: 	}                    ;
 1889: 	my $i;
 1890: 	for ($i=0;$i<=$#ids;$i++) {
 1891: 	    if ($answer[$i]) {
 1892: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1893: 	    }
 1894: 	}
 1895:     }
 1896:     return %returnhash;
 1897: }
 1898: 
 1899: # ------------------------------------- Find the IDs behind a list of usernames
 1900: 
 1901: sub idrget {
 1902:     my ($udom,@unames)=@_;
 1903:     my %returnhash=();
 1904:     foreach my $uname (@unames) {
 1905:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1906:     }
 1907:     return %returnhash;
 1908: }
 1909: 
 1910: # Store away a list of names and associated student/employee IDs or clicker IDs
 1911: 
 1912: sub idput {
 1913:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1914:     my %servers=();
 1915:     my %ids=();
 1916:     my %byid = ();
 1917:     if (ref($idsref) eq 'HASH') {
 1918:         %ids=%{$idsref};
 1919:     }
 1920:     if ($namespace eq '') {
 1921:         $namespace = 'ids'; 
 1922:     }
 1923:     foreach my $uname (keys(%ids)) {
 1924: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1925:         if ($uhom eq '') {
 1926:             $uhom=&homeserver($uname,$udom);
 1927:         }
 1928:         if ($uhom ne 'no_host') {
 1929:             my $esc_unam=&escape($uname);
 1930:             if ($namespace eq 'ids') {
 1931:                 my $id=&escape($ids{$uname});
 1932:                 $id=~tr/A-Z/a-z/;
 1933:                 my $esc_unam=&escape($uname);
 1934:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1935:             } else {
 1936:                 my @currids = split(/,/,$ids{$uname});
 1937:                 foreach my $id (@currids) {
 1938:                     $byid{$uhom}{$id} .= $uname.',';
 1939:                 }
 1940:             }
 1941:         }
 1942:     }
 1943:     if ($namespace eq 'clickers') {
 1944:         foreach my $server (keys(%byid)) {
 1945:             if (ref($byid{$server}) eq 'HASH') {
 1946:                 foreach my $id (keys(%{$byid{$server}})) {
 1947:                     $byid{$server} =~ s/,$//;
 1948:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1949:                 }
 1950:             }
 1951:         }
 1952:     }
 1953:     foreach my $server (keys(%servers)) {
 1954:         $servers{$server} =~ s/\&$//;
 1955:         if ($namespace eq 'ids') {     
 1956:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1957:         } else {
 1958:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1959:         }
 1960:     }
 1961: }
 1962: 
 1963: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1964: 
 1965: sub iddel {
 1966:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1967:     my %result=();
 1968:     my %ids=();
 1969:     my %byid = ();
 1970:     if (ref($idshashref) eq 'HASH') {
 1971:         %ids=%{$idshashref};
 1972:     } else {
 1973:         return %result;
 1974:     }
 1975:     if ($namespace eq '') {
 1976:         $namespace = 'ids';
 1977:     }
 1978:     my %servers=();
 1979:     while (my ($id,$unamestr) = each(%ids)) {
 1980:         if ($namespace eq 'ids') {
 1981:             my $uhom = $uhome;
 1982:             if ($uhom eq '') { 
 1983:                 $uhom=&homeserver($unamestr,$udom);
 1984:             }
 1985:             if ($uhom ne 'no_host') {
 1986:                 $servers{$uhom}.='&'.&escape($id);
 1987:             }
 1988:          } else {
 1989:             my @curritems = split(/,/,$ids{$id});
 1990:             foreach my $uname (@curritems) {
 1991:                 my $uhom = $uhome;
 1992:                 if ($uhom eq '') {
 1993:                     $uhom=&homeserver($uname,$udom);
 1994:                 }
 1995:                 if ($uhom ne 'no_host') { 
 1996:                     $byid{$uhom}{$id} .= $uname.',';
 1997:                 }
 1998:             }
 1999:         }
 2000:     }
 2001:     if ($namespace eq 'clickers') {
 2002:         foreach my $server (keys(%byid)) {
 2003:             if (ref($byid{$server}) eq 'HASH') {
 2004:                 foreach my $id (keys(%{$byid{$server}})) {
 2005:                     $byid{$server}{$id} =~ s/,$//;
 2006:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2007:                 }
 2008:             }
 2009:         }
 2010:     }
 2011:     foreach my $server (keys(%servers)) {
 2012:         $servers{$server} =~ s/\&$//;
 2013:         if ($namespace eq 'ids') {
 2014:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2015:         } elsif ($namespace eq 'clickers') {
 2016:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2017:         }
 2018:     }
 2019:     return %result;
 2020: }
 2021: 
 2022: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2023: 
 2024: sub updateclickers {
 2025:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2026:     my %clickers;
 2027:     if (ref($idshashref) eq 'HASH') {
 2028:         %clickers=%{$idshashref};
 2029:     } else {
 2030:         return;
 2031:     }
 2032:     my $items='';
 2033:     foreach my $item (keys(%clickers)) {
 2034:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2035:     }
 2036:     $items=~s/\&$//;
 2037:     my $request = "updateclickers:$udom:$action:$items";
 2038:     if ($critical) {
 2039:         return &critical($request,$uhome);
 2040:     } else {
 2041:         return &reply($request,$uhome);
 2042:     }
 2043: }
 2044: 
 2045: # ------------------------------dump from db file owned by domainconfig user
 2046: sub dump_dom {
 2047:     my ($namespace, $udom, $regexp) = @_;
 2048: 
 2049:     $udom ||= $env{'user.domain'};
 2050: 
 2051:     return () unless $udom;
 2052: 
 2053:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2054: }
 2055: 
 2056: # ------------------------------------------ get items from domain db files   
 2057: 
 2058: sub get_dom {
 2059:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2060:     return if ($udom eq 'public');
 2061:     my $items='';
 2062:     foreach my $item (@$storearr) {
 2063:         $items.=&escape($item).'&';
 2064:     }
 2065:     $items=~s/\&$//;
 2066:     if (!$udom) {
 2067:         $udom=$env{'user.domain'};
 2068:         return if ($udom eq 'public');
 2069:         if (defined(&domain($udom,'primary'))) {
 2070:             $uhome=&domain($udom,'primary');
 2071:         } else {
 2072:             undef($uhome);
 2073:         }
 2074:     } else {
 2075:         if (!$uhome) {
 2076:             if (defined(&domain($udom,'primary'))) {
 2077:                 $uhome=&domain($udom,'primary');
 2078:             }
 2079:         }
 2080:     }
 2081:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2082:         my $rep;
 2083:         if ($namespace =~ /^enc/) {
 2084:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2085:         } else {
 2086:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2087:         }
 2088:         my %returnhash;
 2089:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2090:             return %returnhash;
 2091:         }
 2092:         my @pairs=split(/\&/,$rep);
 2093:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2094:             return @pairs;
 2095:         }
 2096:         my $i=0;
 2097:         foreach my $item (@$storearr) {
 2098:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2099:             $i++;
 2100:         }
 2101:         return %returnhash;
 2102:     } else {
 2103:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2104:     }
 2105: }
 2106: 
 2107: # -------------------------------------------- put items in domain db files 
 2108: 
 2109: sub put_dom {
 2110:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2111:     if (!$udom) {
 2112:         $udom=$env{'user.domain'};
 2113:         if (defined(&domain($udom,'primary'))) {
 2114:             $uhome=&domain($udom,'primary');
 2115:         } else {
 2116:             undef($uhome);
 2117:         }
 2118:     } else {
 2119:         if (!$uhome) {
 2120:             if (defined(&domain($udom,'primary'))) {
 2121:                 $uhome=&domain($udom,'primary');
 2122:             }
 2123:         }
 2124:     } 
 2125:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2126:         my $items='';
 2127:         foreach my $item (keys(%$storehash)) {
 2128:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2129:         }
 2130:         $items=~s/\&$//;
 2131:         if ($namespace =~ /^enc/) {
 2132:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2133:         } else {
 2134:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2135:         }
 2136:     } else {
 2137:         &logthis("put_dom failed - no homeserver and/or domain");
 2138:     }
 2139: }
 2140: 
 2141: # --------------------- newput for items in db file owned by domainconfig user
 2142: sub newput_dom {
 2143:     my ($namespace,$storehash,$udom) = @_;
 2144:     my $result;
 2145:     if (!$udom) {
 2146:         $udom=$env{'user.domain'};
 2147:     }
 2148:     if ($udom) {
 2149:         my $uname = &get_domainconfiguser($udom);
 2150:         $result = &newput($namespace,$storehash,$udom,$uname);
 2151:     }
 2152:     return $result;
 2153: }
 2154: 
 2155: # --------------------- delete for items in db file owned by domainconfig user
 2156: sub del_dom {
 2157:     my ($namespace,$storearr,$udom)=@_;
 2158:     if (ref($storearr) eq 'ARRAY') {
 2159:         if (!$udom) {
 2160:             $udom=$env{'user.domain'};
 2161:         }
 2162:         if ($udom) {
 2163:             my $uname = &get_domainconfiguser($udom); 
 2164:             return &del($namespace,$storearr,$udom,$uname);
 2165:         }
 2166:     }
 2167: }
 2168: 
 2169: # ----------------------------------construct domainconfig user for a domain 
 2170: sub get_domainconfiguser {
 2171:     my ($udom) = @_;
 2172:     return $udom.'-domainconfig';
 2173: }
 2174: 
 2175: sub retrieve_inst_usertypes {
 2176:     my ($udom) = @_;
 2177:     my (%returnhash,@order);
 2178:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2179:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2180:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2181:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2182:     } else {
 2183:         if (defined(&domain($udom,'primary'))) {
 2184:             my $uhome=&domain($udom,'primary');
 2185:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2186:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2187:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2188:                 return (\%returnhash,\@order);
 2189:             }
 2190:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2191:             my @pairs=split(/\&/,$hashitems);
 2192:             foreach my $item (@pairs) {
 2193:                 my ($key,$value)=split(/=/,$item,2);
 2194:                 $key = &unescape($key);
 2195:                 next if ($key =~ /^error: 2 /);
 2196:                 $returnhash{$key}=&thaw_unescape($value);
 2197:             }
 2198:             my @esc_order = split(/\&/,$orderitems);
 2199:             foreach my $item (@esc_order) {
 2200:                 push(@order,&unescape($item));
 2201:             }
 2202:         } else {
 2203:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2204:         }
 2205:         return (\%returnhash,\@order);
 2206:     }
 2207: }
 2208: 
 2209: sub is_domainimage {
 2210:     my ($url) = @_;
 2211:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2212:         if (&domain($1) ne '') {
 2213:             return '1';
 2214:         }
 2215:     }
 2216:     return;
 2217: }
 2218: 
 2219: sub inst_directory_query {
 2220:     my ($srch) = @_;
 2221:     my $udom = $srch->{'srchdomain'};
 2222:     my %results;
 2223:     my $homeserver = &domain($udom,'primary');
 2224:     my $outcome;
 2225:     if ($homeserver ne '') {
 2226:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2227:             if ($srch->{'srchby'} eq 'email') {
 2228:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2229:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2230:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2231:                     (($major == 2) && ($minor < 12))) {
 2232:                     return;
 2233:                 }
 2234:             }
 2235:         }
 2236: 	my $queryid=&reply("querysend:instdirsearch:".
 2237: 			   &escape($srch->{'srchby'}).':'.
 2238: 			   &escape($srch->{'srchterm'}).':'.
 2239: 			   &escape($srch->{'srchtype'}),$homeserver);
 2240: 	my $host=&hostname($homeserver);
 2241: 	if ($queryid !~/^\Q$host\E\_/) {
 2242: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2243: 	    return;
 2244: 	}
 2245: 	my $response = &get_query_reply($queryid);
 2246: 	my $maxtries = 5;
 2247: 	my $tries = 1;
 2248: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2249: 	    $response = &get_query_reply($queryid);
 2250: 	    $tries ++;
 2251: 	}
 2252: 
 2253:         if (!&error($response) && $response ne 'refused') {
 2254:             if ($response eq 'unavailable') {
 2255:                 $outcome = $response;
 2256:             } else {
 2257:                 $outcome = 'ok';
 2258:                 my @matches = split(/\n/,$response);
 2259:                 foreach my $match (@matches) {
 2260:                     my ($key,$value) = split(/=/,$match);
 2261:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2262:                 }
 2263:             }
 2264:         }
 2265:     }
 2266:     return ($outcome,%results);
 2267: }
 2268: 
 2269: sub usersearch {
 2270:     my ($srch) = @_;
 2271:     my $dom = $srch->{'srchdomain'};
 2272:     my %results;
 2273:     my %libserv = &all_library();
 2274:     my $query = 'usersearch';
 2275:     foreach my $tryserver (keys(%libserv)) {
 2276:         if (&host_domain($tryserver) eq $dom) {
 2277:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2278:                 if ($srch->{'srchby'} eq 'email') {
 2279:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2280:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2281:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2282:                              (($major == 2) && ($minor < 12)));
 2283:                 }
 2284:             }
 2285:             my $host=&hostname($tryserver);
 2286:             my $queryid=
 2287:                 &reply("querysend:".&escape($query).':'.
 2288:                        &escape($srch->{'srchby'}).':'.
 2289:                        &escape($srch->{'srchtype'}).':'.
 2290:                        &escape($srch->{'srchterm'}),$tryserver);
 2291:             if ($queryid !~/^\Q$host\E\_/) {
 2292:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2293:                 next;
 2294:             }
 2295:             my $reply = &get_query_reply($queryid);
 2296:             my $maxtries = 1;
 2297:             my $tries = 1;
 2298:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2299:                 $reply = &get_query_reply($queryid);
 2300:                 $tries ++;
 2301:             }
 2302:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2303:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2304:             } else {
 2305:                 my @matches;
 2306:                 if ($reply =~ /\n/) {
 2307:                     @matches = split(/\n/,$reply);
 2308:                 } else {
 2309:                     @matches = split(/\&/,$reply);
 2310:                 }
 2311:                 foreach my $match (@matches) {
 2312:                     my ($uname,$udom,%userhash);
 2313:                     foreach my $entry (split(/:/,$match)) {
 2314:                         my ($key,$value) =
 2315:                             map {&unescape($_);} split(/=/,$entry);
 2316:                         $userhash{$key} = $value;
 2317:                         if ($key eq 'username') {
 2318:                             $uname = $value;
 2319:                         } elsif ($key eq 'domain') {
 2320:                             $udom = $value;
 2321:                         }
 2322:                     }
 2323:                     $results{$uname.':'.$udom} = \%userhash;
 2324:                 }
 2325:             }
 2326:         }
 2327:     }
 2328:     return %results;
 2329: }
 2330: 
 2331: sub get_instuser {
 2332:     my ($udom,$uname,$id) = @_;
 2333:     my $homeserver = &domain($udom,'primary');
 2334:     my ($outcome,%results);
 2335:     if ($homeserver ne '') {
 2336:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2337:                            &escape($id).':'.&escape($udom),$homeserver);
 2338:         my $host=&hostname($homeserver);
 2339:         if ($queryid !~/^\Q$host\E\_/) {
 2340:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2341:             return;
 2342:         }
 2343:         my $response = &get_query_reply($queryid);
 2344:         my $maxtries = 5;
 2345:         my $tries = 1;
 2346:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2347:             $response = &get_query_reply($queryid);
 2348:             $tries ++;
 2349:         }
 2350:         if (!&error($response) && $response ne 'refused') {
 2351:             if ($response eq 'unavailable') {
 2352:                 $outcome = $response;
 2353:             } else {
 2354:                 $outcome = 'ok';
 2355:                 my @matches = split(/\n/,$response);
 2356:                 foreach my $match (@matches) {
 2357:                     my ($key,$value) = split(/=/,$match);
 2358:                     $results{&unescape($key)} = &thaw_unescape($value);
 2359:                 }
 2360:             }
 2361:         }
 2362:     }
 2363:     my %userinfo;
 2364:     if (ref($results{$uname}) eq 'HASH') {
 2365:         %userinfo = %{$results{$uname}};
 2366:     } 
 2367:     return ($outcome,%userinfo);
 2368: }
 2369: 
 2370: sub get_multiple_instusers {
 2371:     my ($udom,$users,$caller) = @_;
 2372:     my ($outcome,$results);
 2373:     if (ref($users) eq 'HASH') {
 2374:         my $count = keys(%{$users}); 
 2375:         my $requested = &freeze_escape($users);
 2376:         my $homeserver = &domain($udom,'primary');
 2377:         if ($homeserver ne '') {
 2378:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2379:             my $host=&hostname($homeserver);
 2380:             if ($queryid !~/^\Q$host\E\_/) {
 2381:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2382:                          ' for host: '.$homeserver.'in domain '.$udom);
 2383:                 return ($outcome,$results);
 2384:             }
 2385:             my $response = &get_query_reply($queryid);
 2386:             my $maxtries = 5;
 2387:             if ($count > 100) {
 2388:                 $maxtries = 1+int($count/20);
 2389:             }
 2390:             my $tries = 1;
 2391:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2392:                 $response = &get_query_reply($queryid);
 2393:                 $tries ++;
 2394:             }
 2395:             if ($response eq '') {
 2396:                 $results = {};
 2397:                 foreach my $key (keys(%{$users})) {
 2398:                     my ($uname,$id);
 2399:                     if ($caller eq 'id') {
 2400:                         $id = $key;
 2401:                     } else {
 2402:                         $uname = $key;
 2403:                     }
 2404:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2405:                     $outcome = $resp;
 2406:                     if ($resp eq 'ok') {
 2407:                         %{$results} = (%{$results}, %info);
 2408:                     } else {
 2409:                         last;
 2410:                     }
 2411:                 }
 2412:             } elsif(!&error($response) && ($response ne 'refused')) {
 2413:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2414:                     $outcome = $response;
 2415:                 } else {
 2416:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2417:                     if ($outcome eq 'ok') {
 2418:                         $results = &thaw_unescape($userdata); 
 2419:                     }
 2420:                 }
 2421:             }
 2422:         }
 2423:     }
 2424:     return ($outcome,$results);
 2425: }
 2426: 
 2427: sub inst_rulecheck {
 2428:     my ($udom,$uname,$id,$item,$rules) = @_;
 2429:     my %returnhash;
 2430:     if ($udom ne '') {
 2431:         if (ref($rules) eq 'ARRAY') {
 2432:             @{$rules} = map {&escape($_);} (@{$rules});
 2433:             my $rulestr = join(':',@{$rules});
 2434:             my $homeserver=&domain($udom,'primary');
 2435:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2436:                 my $response;
 2437:                 if ($item eq 'username') {                
 2438:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2439:                                               ':'.&escape($uname).':'.$rulestr,
 2440:                                               $homeserver));
 2441:                 } elsif ($item eq 'id') {
 2442:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2443:                                               ':'.&escape($id).':'.$rulestr,
 2444:                                               $homeserver));
 2445:                 } elsif ($item eq 'selfcreate') {
 2446:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2447:                                                &escape($udom).':'.&escape($uname).
 2448:                                               ':'.$rulestr,$homeserver));
 2449:                 }
 2450:                 if ($response ne 'refused') {
 2451:                     my @pairs=split(/\&/,$response);
 2452:                     foreach my $item (@pairs) {
 2453:                         my ($key,$value)=split(/=/,$item,2);
 2454:                         $key = &unescape($key);
 2455:                         next if ($key =~ /^error: 2 /);
 2456:                         $returnhash{$key}=&thaw_unescape($value);
 2457:                     }
 2458:                 }
 2459:             }
 2460:         }
 2461:     }
 2462:     return %returnhash;
 2463: }
 2464: 
 2465: sub inst_userrules {
 2466:     my ($udom,$check) = @_;
 2467:     my (%ruleshash,@ruleorder);
 2468:     if ($udom ne '') {
 2469:         my $homeserver=&domain($udom,'primary');
 2470:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2471:             my $response;
 2472:             if ($check eq 'id') {
 2473:                 $response=&reply('instidrules:'.&escape($udom),
 2474:                                  $homeserver);
 2475:             } elsif ($check eq 'email') {
 2476:                 $response=&reply('instemailrules:'.&escape($udom),
 2477:                                  $homeserver);
 2478:             } else {
 2479:                 $response=&reply('instuserrules:'.&escape($udom),
 2480:                                  $homeserver);
 2481:             }
 2482:             if (($response ne 'refused') && ($response ne 'error') && 
 2483:                 ($response ne 'unknown_cmd') && 
 2484:                 ($response ne 'no_such_host')) {
 2485:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2486:                 my @pairs=split(/\&/,$hashitems);
 2487:                 foreach my $item (@pairs) {
 2488:                     my ($key,$value)=split(/=/,$item,2);
 2489:                     $key = &unescape($key);
 2490:                     next if ($key =~ /^error: 2 /);
 2491:                     $ruleshash{$key}=&thaw_unescape($value);
 2492:                 }
 2493:                 my @esc_order = split(/\&/,$orderitems);
 2494:                 foreach my $item (@esc_order) {
 2495:                     push(@ruleorder,&unescape($item));
 2496:                 }
 2497:             }
 2498:         }
 2499:     }
 2500:     return (\%ruleshash,\@ruleorder);
 2501: }
 2502: 
 2503: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2504: 
 2505: sub get_domain_defaults {
 2506:     my ($domain,$ignore_cache) = @_;
 2507:     return if (($domain eq '') || ($domain eq 'public'));
 2508:     my $cachetime = 60*60*24;
 2509:     unless ($ignore_cache) {
 2510:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2511:         if (defined($cached)) {
 2512:             if (ref($result) eq 'HASH') {
 2513:                 return %{$result};
 2514:             }
 2515:         }
 2516:     }
 2517:     my %domdefaults;
 2518:     my %domconfig =
 2519:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2520:                                   'requestcourses','inststatus',
 2521:                                   'coursedefaults','usersessions',
 2522:                                   'requestauthor','selfenrollment',
 2523:                                   'coursecategories','ssl','autoenroll',
 2524:                                   'trust','helpsettings'],$domain);
 2525:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2526:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2527:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2528:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2529:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2530:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2531:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2532:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2533:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2534:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2535:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2536:     } else {
 2537:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2538:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2539:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2540:     }
 2541:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2542:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2543:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2544:         } else {
 2545:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2546:         }
 2547:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2548:         foreach my $item (@usertools) {
 2549:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2550:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2551:             }
 2552:         }
 2553:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2554:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2555:         }
 2556:     }
 2557:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2558:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2559:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2560:         }
 2561:     }
 2562:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2563:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2564:     }
 2565:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2566:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2567:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2568:         }
 2569:     }
 2570:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2571:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2572:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2573:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2574:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2575:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2576:         }
 2577:         foreach my $type (@coursetypes) {
 2578:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2579:                 unless ($type eq 'community') {
 2580:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2581:                 }
 2582:             }
 2583:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2584:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2585:             }
 2586:             if ($domdefaults{'postsubmit'} eq 'on') {
 2587:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2588:                     $domdefaults{$type.'postsubtimeout'} = 
 2589:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2590:                 }
 2591:             }
 2592:         }
 2593:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2594:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2595:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2596:                 if (@clonecodes) {
 2597:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2598:                 }
 2599:             }
 2600:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2601:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2602:         }
 2603:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2604:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2605:         } 
 2606:     }
 2607:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2608:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2609:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2610:         }
 2611:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2612:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2613:         }
 2614:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2615:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2616:         }
 2617:     }
 2618:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2619:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2620:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2621:                             'approval','limit');
 2622:             foreach my $type (@coursetypes) {
 2623:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2624:                     my @mgrdc = ();
 2625:                     foreach my $item (@settings) {
 2626:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2627:                             push(@mgrdc,$item);
 2628:                         }
 2629:                     }
 2630:                     if (@mgrdc) {
 2631:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2632:                     }
 2633:                 }
 2634:             }
 2635:         }
 2636:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2637:             foreach my $type (@coursetypes) {
 2638:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2639:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2640:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2641:                     }
 2642:                 }
 2643:             }
 2644:         }
 2645:     }
 2646:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2647:         $domdefaults{'catauth'} = 'std';
 2648:         $domdefaults{'catunauth'} = 'std';
 2649:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2650:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2651:         }
 2652:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2653:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2654:         }
 2655:     }
 2656:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2657:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2658:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2659:         }
 2660:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2661:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2662:         }
 2663:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2664:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2665:         }
 2666:     }
 2667:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2668:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2669:         foreach my $prefix (@prefixes) {
 2670:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2671:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2672:             }
 2673:         }
 2674:     }
 2675:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2676:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2677:     }
 2678:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2679:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2680:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2681:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2682:         }
 2683:     }
 2684:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2685:     return %domdefaults;
 2686: }
 2687: 
 2688: sub course_portal_url {
 2689:     my ($cnum,$cdom) = @_;
 2690:     my $chome = &homeserver($cnum,$cdom);
 2691:     my $hostname = &hostname($chome);
 2692:     my $protocol = $protocol{$chome};
 2693:     $protocol = 'http' if ($protocol ne 'https');
 2694:     my %domdefaults = &get_domain_defaults($cdom);
 2695:     my $firsturl;
 2696:     if ($domdefaults{'portal_def'}) {
 2697:         $firsturl = $domdefaults{'portal_def'};
 2698:     } else {
 2699:         $firsturl = $protocol.'://'.$hostname;
 2700:     }
 2701:     return $firsturl;
 2702: }
 2703: 
 2704: # --------------------------------------------------- Assign a key to a student
 2705: 
 2706: sub assign_access_key {
 2707: #
 2708: # a valid key looks like uname:udom#comments
 2709: # comments are being appended
 2710: #
 2711:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2712:     $kdom=
 2713:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2714:     $knum=
 2715:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2716:     $cdom=
 2717:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2718:     $cnum=
 2719:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2720:     $udom=$env{'user.name'} unless (defined($udom));
 2721:     $uname=$env{'user.domain'} unless (defined($uname));
 2722:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2723:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2724:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2725:                                                   # assigned to this person
 2726:                                                   # - this should not happen,
 2727:                                                   # unless something went wrong
 2728:                                                   # the first time around
 2729: # ready to assign
 2730:         $logentry=$1.'; '.$logentry;
 2731:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2732:                                                  $kdom,$knum) eq 'ok') {
 2733: # key now belongs to user
 2734: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2735:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2736:                 &appenv({'environment.'.$envkey => $ckey});
 2737:                 return 'ok';
 2738:             } else {
 2739:                 return 
 2740:   'error: Count not permanently assign key, will need to be re-entered later.';
 2741: 	    }
 2742:         } else {
 2743:             return 'error: Could not assign key, try again later.';
 2744:         }
 2745:     } elsif (!$existing{$ckey}) {
 2746: # the key does not exist
 2747: 	return 'error: The key does not exist';
 2748:     } else {
 2749: # the key is somebody else's
 2750: 	return 'error: The key is already in use';
 2751:     }
 2752: }
 2753: 
 2754: # ------------------------------------------ put an additional comment on a key
 2755: 
 2756: sub comment_access_key {
 2757: #
 2758: # a valid key looks like uname:udom#comments
 2759: # comments are being appended
 2760: #
 2761:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2762:     $cdom=
 2763:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2764:     $cnum=
 2765:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2766:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2767:     if ($existing{$ckey}) {
 2768:         $existing{$ckey}.='; '.$logentry;
 2769: # ready to assign
 2770:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2771:                                                  $cdom,$cnum) eq 'ok') {
 2772: 	    return 'ok';
 2773:         } else {
 2774: 	    return 'error: Count not store comment.';
 2775:         }
 2776:     } else {
 2777: # the key does not exist
 2778: 	return 'error: The key does not exist';
 2779:     }
 2780: }
 2781: 
 2782: # ------------------------------------------------------ Generate a set of keys
 2783: 
 2784: sub generate_access_keys {
 2785:     my ($number,$cdom,$cnum,$logentry)=@_;
 2786:     $cdom=
 2787:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2788:     $cnum=
 2789:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2790:     unless (&allowed('mky',$cdom)) { return 0; }
 2791:     unless (($cdom) && ($cnum)) { return 0; }
 2792:     if ($number>10000) { return 0; }
 2793:     sleep(2); # make sure don't get same seed twice
 2794:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2795:     my $total=0;
 2796:     for (my $i=1;$i<=$number;$i++) {
 2797:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2798:                   sprintf("%lx",int(100000*rand)).'-'.
 2799:                   sprintf("%lx",int(100000*rand));
 2800:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2801:        $newkey=~s/0/h/g; # and also 0 and O
 2802:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2803:        if ($existing{$newkey}) {
 2804:            $i--;
 2805:        } else {
 2806: 	  if (&put('accesskeys',
 2807:               { $newkey => '# generated '.localtime().
 2808:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2809:                            '; '.$logentry },
 2810: 		   $cdom,$cnum) eq 'ok') {
 2811:               $total++;
 2812: 	  }
 2813:        }
 2814:     }
 2815:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2816:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2817:     return $total;
 2818: }
 2819: 
 2820: # ------------------------------------------------------- Validate an accesskey
 2821: 
 2822: sub validate_access_key {
 2823:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2824:     $cdom=
 2825:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2826:     $cnum=
 2827:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2828:     $udom=$env{'user.domain'} unless (defined($udom));
 2829:     $uname=$env{'user.name'} unless (defined($uname));
 2830:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2831:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2832: }
 2833: 
 2834: # ------------------------------------- Find the section of student in a course
 2835: sub devalidate_getsection_cache {
 2836:     my ($udom,$unam,$courseid)=@_;
 2837:     my $hashid="$udom:$unam:$courseid";
 2838:     &devalidate_cache_new('getsection',$hashid);
 2839: }
 2840: 
 2841: sub courseid_to_courseurl {
 2842:     my ($courseid) = @_;
 2843:     #already url style courseid
 2844:     return $courseid if ($courseid =~ m{^/});
 2845: 
 2846:     if (exists($env{'course.'.$courseid.'.num'})) {
 2847: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2848: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2849: 	return "/$cdom/$cnum";
 2850:     }
 2851: 
 2852:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2853:     if (exists($courseinfo{'num'})) {
 2854: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2855:     }
 2856: 
 2857:     return undef;
 2858: }
 2859: 
 2860: sub getsection {
 2861:     my ($udom,$unam,$courseid)=@_;
 2862:     my $cachetime=1800;
 2863: 
 2864:     my $hashid="$udom:$unam:$courseid";
 2865:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2866:     if (defined($cached)) { return $result; }
 2867: 
 2868:     my %Pending; 
 2869:     my %Expired;
 2870:     #
 2871:     # Each role can either have not started yet (pending), be active, 
 2872:     #    or have expired.
 2873:     #
 2874:     # If there is an active role, we are done.
 2875:     #
 2876:     # If there is more than one role which has not started yet, 
 2877:     #     choose the one which will start sooner
 2878:     # If there is one role which has not started yet, return it.
 2879:     #
 2880:     # If there is more than one expired role, choose the one which ended last.
 2881:     # If there is a role which has expired, return it.
 2882:     #
 2883:     $courseid = &courseid_to_courseurl($courseid);
 2884:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2885:     foreach my $key (keys(%roleshash)) {
 2886:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2887:         my $section=$1;
 2888:         if ($key eq $courseid.'_st') { $section=''; }
 2889:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2890:         my $now=time;
 2891:         if (defined($end) && $end && ($now > $end)) {
 2892:             $Expired{$end}=$section;
 2893:             next;
 2894:         }
 2895:         if (defined($start) && $start && ($now < $start)) {
 2896:             $Pending{$start}=$section;
 2897:             next;
 2898:         }
 2899:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2900:     }
 2901:     #
 2902:     # Presumedly there will be few matching roles from the above
 2903:     # loop and the sorting time will be negligible.
 2904:     if (scalar(keys(%Pending))) {
 2905:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2906:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2907:     } 
 2908:     if (scalar(keys(%Expired))) {
 2909:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2910:         my $time = pop(@sorted);
 2911:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2912:     }
 2913:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2914: }
 2915: 
 2916: sub save_cache {
 2917:     &purge_remembered();
 2918:     #&Apache::loncommon::validate_page();
 2919:     undef(%env);
 2920:     undef($env_loaded);
 2921: }
 2922: 
 2923: my $to_remember=-1;
 2924: my %remembered;
 2925: my %accessed;
 2926: my $kicks=0;
 2927: my $hits=0;
 2928: sub make_key {
 2929:     my ($name,$id) = @_;
 2930:     if (length($id) > 65 
 2931: 	&& length(&escape($id)) > 200) {
 2932: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2933:     }
 2934:     return &escape($name.':'.$id);
 2935: }
 2936: 
 2937: sub devalidate_cache_new {
 2938:     my ($name,$id,$debug) = @_;
 2939:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2940:     my $remembered_id=$name.':'.$id;
 2941:     $id=&make_key($name,$id);
 2942:     $memcache->delete($id);
 2943:     delete($remembered{$remembered_id});
 2944:     delete($accessed{$remembered_id});
 2945: }
 2946: 
 2947: sub is_cached_new {
 2948:     my ($name,$id,$debug) = @_;
 2949:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2950:     if (exists($remembered{$remembered_id})) {
 2951: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2952: 	$accessed{$remembered_id}=[&gettimeofday()];
 2953: 	$hits++;
 2954: 	return ($remembered{$remembered_id},1);
 2955:     }
 2956:     $id=&make_key($name,$id);
 2957:     my $value = $memcache->get($id);
 2958:     if (!(defined($value))) {
 2959: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2960: 	return (undef,undef);
 2961:     }
 2962:     if ($value eq '__undef__') {
 2963: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2964: 	$value=undef;
 2965:     }
 2966:     &make_room($remembered_id,$value,$debug);
 2967:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2968:     return ($value,1);
 2969: }
 2970: 
 2971: sub do_cache_new {
 2972:     my ($name,$id,$value,$time,$debug) = @_;
 2973:     my $remembered_id=$name.':'.$id;
 2974:     $id=&make_key($name,$id);
 2975:     my $setvalue=$value;
 2976:     if (!defined($setvalue)) {
 2977: 	$setvalue='__undef__';
 2978:     }
 2979:     if (!defined($time) ) {
 2980: 	$time=600;
 2981:     }
 2982:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2983:     my $result = $memcache->set($id,$setvalue,$time);
 2984:     if (! $result) {
 2985: 	&logthis("caching of id -> $id  failed");
 2986: 	$memcache->disconnect_all();
 2987:     }
 2988:     # need to make a copy of $value
 2989:     &make_room($remembered_id,$value,$debug);
 2990:     return $value;
 2991: }
 2992: 
 2993: sub make_room {
 2994:     my ($remembered_id,$value,$debug)=@_;
 2995: 
 2996:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2997:                                     : $value;
 2998:     if ($to_remember<0) { return; }
 2999:     $accessed{$remembered_id}=[&gettimeofday()];
 3000:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3001:     my $to_kick;
 3002:     my $max_time=0;
 3003:     foreach my $other (keys(%accessed)) {
 3004: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3005: 	    $to_kick=$other;
 3006: 	    $max_time=&tv_interval($accessed{$other});
 3007: 	}
 3008:     }
 3009:     delete($remembered{$to_kick});
 3010:     delete($accessed{$to_kick});
 3011:     $kicks++;
 3012:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3013:     return;
 3014: }
 3015: 
 3016: sub purge_remembered {
 3017:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3018:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3019:     undef(%remembered);
 3020:     undef(%accessed);
 3021: }
 3022: # ------------------------------------- Read an entry from a user's environment
 3023: 
 3024: sub userenvironment {
 3025:     my ($udom,$unam,@what)=@_;
 3026:     my $items;
 3027:     foreach my $item (@what) {
 3028:         $items.=&escape($item).'&';
 3029:     }
 3030:     $items=~s/\&$//;
 3031:     my %returnhash=();
 3032:     my $uhome = &homeserver($unam,$udom);
 3033:     unless ($uhome eq 'no_host') {
 3034:         my @answer=split(/\&/, 
 3035:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3036:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3037:             return %returnhash;
 3038:         }
 3039:         my $i;
 3040:         for ($i=0;$i<=$#what;$i++) {
 3041: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3042:         }
 3043:     }
 3044:     return %returnhash;
 3045: }
 3046: 
 3047: # ---------------------------------------------------------- Get a studentphoto
 3048: sub studentphoto {
 3049:     my ($udom,$unam,$ext) = @_;
 3050:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3051:     if (defined($env{'request.course.id'})) {
 3052:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3053:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3054:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3055:             } else {
 3056:                 my ($result,$perm_reqd)=
 3057: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3058:                 if ($result eq 'ok') {
 3059:                     if (!($perm_reqd eq 'yes')) {
 3060:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3061:                     }
 3062:                 }
 3063:             }
 3064:         }
 3065:     } else {
 3066:         my ($result,$perm_reqd) = 
 3067: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3068:         if ($result eq 'ok') {
 3069:             if (!($perm_reqd eq 'yes')) {
 3070:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3071:             }
 3072:         }
 3073:     }
 3074:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3075: }
 3076: 
 3077: sub retrievestudentphoto {
 3078:     my ($udom,$unam,$ext,$type) = @_;
 3079:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3080:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3081:     if ($ret eq 'ok') {
 3082:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3083:         if ($type eq 'thumbnail') {
 3084:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3085:         }
 3086:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3087:         return $tokenurl;
 3088:     } else {
 3089:         if ($type eq 'thumbnail') {
 3090:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3091:         } else { 
 3092:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3093:         }
 3094:     }
 3095: }
 3096: 
 3097: # -------------------------------------------------------------------- New chat
 3098: 
 3099: sub chatsend {
 3100:     my ($newentry,$anon,$group)=@_;
 3101:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3102:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3103:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3104:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3105: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3106: 		   &escape($newentry)).':'.$group,$chome);
 3107: }
 3108: 
 3109: # ------------------------------------------ Find current version of a resource
 3110: 
 3111: sub getversion {
 3112:     my $fname=&clutter(shift);
 3113:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3114:     return &currentversion(&filelocation('',$fname));
 3115: }
 3116: 
 3117: sub currentversion {
 3118:     my $fname=shift;
 3119:     my $author=$fname;
 3120:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3121:     my ($udom,$uname)=split(/\//,$author);
 3122:     my $home=&homeserver($uname,$udom);
 3123:     if ($home eq 'no_host') { 
 3124:         return -1; 
 3125:     }
 3126:     my $answer=&reply("currentversion:$fname",$home);
 3127:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3128: 	return -1;
 3129:     }
 3130:     return $answer;
 3131: }
 3132: 
 3133: #
 3134: # Return special version number of resource if set by override, empty otherwise
 3135: #
 3136: sub usedversion {
 3137:     my $fname=shift;
 3138:     unless ($fname) { $fname=$env{'request.uri'}; }
 3139:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3140:     if ($urlversion) { return $urlversion; }
 3141:     return '';
 3142: }
 3143: 
 3144: # ----------------------------- Subscribe to a resource, return URL if possible
 3145: 
 3146: sub subscribe {
 3147:     my $fname=shift;
 3148:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3149:     $fname=~s/[\n\r]//g;
 3150:     my $author=$fname;
 3151:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3152:     my ($udom,$uname)=split(/\//,$author);
 3153:     my $home=homeserver($uname,$udom);
 3154:     if ($home eq 'no_host') {
 3155:         return 'not_found';
 3156:     }
 3157:     my $answer=reply("sub:$fname",$home);
 3158:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3159: 	$answer.=' by '.$home;
 3160:     }
 3161:     return $answer;
 3162: }
 3163:     
 3164: # -------------------------------------------------------------- Replicate file
 3165: 
 3166: sub repcopy {
 3167:     my $filename=shift;
 3168:     $filename=~s/\/+/\//g;
 3169:     my $londocroot = $perlvar{'lonDocRoot'};
 3170:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3171:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3172:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3173: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3174: 	return &repcopy_userfile($filename);
 3175:     }
 3176:     $filename=~s/[\n\r]//g;
 3177:     my $transname="$filename.in.transfer";
 3178: # FIXME: this should flock
 3179:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3180:     my $remoteurl=subscribe($filename);
 3181:     if ($remoteurl =~ /^con_lost by/) {
 3182: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3183:            return 'unavailable';
 3184:     } elsif ($remoteurl eq 'not_found') {
 3185: 	   #&logthis("Subscribe returned not_found: $filename");
 3186: 	   return 'not_found';
 3187:     } elsif ($remoteurl =~ /^rejected by/) {
 3188: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3189:            return 'forbidden';
 3190:     } elsif ($remoteurl eq 'directory') {
 3191:            return 'ok';
 3192:     } else {
 3193:         my $author=$filename;
 3194:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3195:         my ($udom,$uname)=split(/\//,$author);
 3196:         my $home=homeserver($uname,$udom);
 3197:         unless ($home eq $perlvar{'lonHostID'}) {
 3198:            my @parts=split(/\//,$filename);
 3199:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3200:            if ($path ne "$londocroot/res") {
 3201:                &logthis("Malconfiguration for replication: $filename");
 3202: 	       return 'bad_request';
 3203:            }
 3204:            my $count;
 3205:            for ($count=5;$count<$#parts;$count++) {
 3206:                $path.="/$parts[$count]";
 3207:                if ((-e $path)!=1) {
 3208: 		   mkdir($path,0777);
 3209:                }
 3210:            }
 3211:            my $request=new HTTP::Request('GET',"$remoteurl");
 3212:            my $response;
 3213:            if ($remoteurl =~ m{/raw/}) {
 3214:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3215:            } else {
 3216:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3217:            }
 3218:            if ($response->is_error()) {
 3219: 	       unlink($transname);
 3220:                my $message=$response->status_line;
 3221:                &logthis("<font color=\"blue\">WARNING:"
 3222:                        ." LWP get: $message: $filename</font>");
 3223:                return 'unavailable';
 3224:            } else {
 3225: 	       if ($remoteurl!~/\.meta$/) {
 3226:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3227:                   my $mresponse;
 3228:                   if ($remoteurl =~ m{/raw/}) {
 3229:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3230:                   } else {
 3231:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3232:                   }
 3233:                   if ($mresponse->is_error()) {
 3234: 		      unlink($filename.'.meta');
 3235:                       &logthis(
 3236:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3237:                   }
 3238: 	       }
 3239:                rename($transname,$filename);
 3240:                return 'ok';
 3241:            }
 3242:        }
 3243:     }
 3244: }
 3245: 
 3246: # ------------------------------------------------ Get server side include body
 3247: sub ssi_body {
 3248:     my ($filelink,%form)=@_;
 3249:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3250:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3251:     }
 3252:     my $output='';
 3253:     my $response;
 3254:     if ($filelink=~/^https?\:/) {
 3255:        ($output,$response)=&externalssi($filelink);
 3256:     } else {
 3257:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3258:        $filelink .= 'inhibitmenu=yes';
 3259:        ($output,$response)=&ssi($filelink,%form);
 3260:     }
 3261:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3262:     $output=~s/^.*?\<body[^\>]*\>//si;
 3263:     $output=~s/\<\/body\s*\>.*?$//si;
 3264:     if (wantarray) {
 3265:         return ($output, $response);
 3266:     } else {
 3267:         return $output;
 3268:     }
 3269: }
 3270: 
 3271: # --------------------------------------------------------- Server Side Include
 3272: 
 3273: sub absolute_url {
 3274:     my ($host_name) = @_;
 3275:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3276:     if ($host_name eq '') {
 3277: 	$host_name = $ENV{'SERVER_NAME'};
 3278:     }
 3279:     return $protocol.$host_name;
 3280: }
 3281: 
 3282: #
 3283: #   Server side include.
 3284: # Parameters:
 3285: #  fn     Possibly encrypted resource name/id.
 3286: #  form   Hash that describes how the rendering should be done
 3287: #         and other things.
 3288: # Returns:
 3289: #   Scalar context: The content of the response.
 3290: #   Array context:  2 element list of the content and the full response object.
 3291: #     
 3292: sub ssi {
 3293: 
 3294:     my ($fn,%form)=@_;
 3295:     my $request;
 3296: 
 3297:     $form{'no_update_last_known'}=1;
 3298:     &Apache::lonenc::check_encrypt(\$fn);
 3299:     if (%form) {
 3300:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3301:       $request->content(join('&',map { 
 3302:             my $name = escape($_);
 3303:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3304:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3305:             : &escape($form{$_}) );    
 3306:         } keys(%form)));
 3307:     } else {
 3308:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3309:     }
 3310: 
 3311:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3312:     my $lonhost = $perlvar{'lonHostID'};
 3313:     my $islocal;
 3314:     if (($env{'request.course.id'}) &&
 3315:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3316:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3317:         ($form{'grade_symb'} ne '') &&
 3318:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3319:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3320:         $islocal = 1;
 3321:     }
 3322:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3323:                                                 '','','',$islocal);
 3324: 
 3325:     if (wantarray) {
 3326: 	return ($response->content, $response);
 3327:     } else {
 3328: 	return $response->content;
 3329:     }
 3330: }
 3331: 
 3332: sub externalssi {
 3333:     my ($url)=@_;
 3334:     my $request=new HTTP::Request('GET',$url);
 3335:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3336:     if (wantarray) {
 3337:         return ($response->content, $response);
 3338:     } else {
 3339:         return $response->content;
 3340:     }
 3341: }
 3342: 
 3343: 
 3344: # If the local copy of a replicated resource is outdated, trigger a  
 3345: # connection from the homeserver to flush the delayed queue. If no update 
 3346: # happens, remove local copies of outdated resource (and corresponding
 3347: # metadata file).
 3348: 
 3349: sub remove_stale_resfile {
 3350:     my ($url) = @_;
 3351:     my $removed;
 3352:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3353:         my $audom = $1;
 3354:         my $auname = $2;
 3355:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3356:             my $homeserver = &homeserver($auname,$audom);
 3357:             unless (($homeserver eq 'no_host') ||
 3358:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3359:                 my $fname = &filelocation('',$url);
 3360:                 if (-e $fname) {
 3361:                     my $protocol = $protocol{$homeserver};
 3362:                     $protocol = 'http' if ($protocol ne 'https');
 3363:                     my $hostname = &hostname($homeserver);
 3364:                     if ($hostname) {
 3365:                         my $uri = &declutter($url);
 3366:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3367:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3368:                         if ($response->is_success()) {
 3369:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3370:                             my $locmodtime = (stat($fname))[9];
 3371:                             if ($locmodtime < $remmodtime) {
 3372:                                 my $stale;
 3373:                                 my $answer = &reply('pong',$homeserver);
 3374:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3375:                                     sleep(0.2);
 3376:                                     $locmodtime = (stat($fname))[9];
 3377:                                     if ($locmodtime < $remmodtime) {
 3378:                                         my $posstransfer = $fname.'.in.transfer';
 3379:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3380:                                             $removed = 1;
 3381:                                         } else {
 3382:                                             $stale = 1;
 3383:                                         }
 3384:                                     } else {
 3385:                                         $removed = 1;
 3386:                                     }
 3387:                                 } else {
 3388:                                     $stale = 1;
 3389:                                 }
 3390:                                 if ($stale) {
 3391:                                     unlink($fname);
 3392:                                     if ($uri!~/\.meta$/) {
 3393:                                         unlink($fname.'.meta');
 3394:                                     }
 3395:                                     &reply("unsub:$fname",$homeserver);
 3396:                                     $removed = 1;
 3397:                                 }
 3398:                             }
 3399:                         }
 3400:                     }
 3401:                 }
 3402:             }
 3403:         }
 3404:     }
 3405:     return $removed;
 3406: }
 3407: 
 3408: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3409: 
 3410: sub allowuploaded {
 3411:     my ($srcurl,$url)=@_;
 3412:     $url=&clutter(&declutter($url));
 3413:     my $dir=$url;
 3414:     $dir=~s/\/[^\/]+$//;
 3415:     my %httpref=();
 3416:     my $httpurl=&hreflocation('',$url);
 3417:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3418:     &Apache::lonnet::appenv(\%httpref);
 3419: }
 3420: 
 3421: #
 3422: # Determine if the current user should be able to edit a particular resource,
 3423: # when viewing in course context.
 3424: # (a) When viewing resource used to determine if "Edit" item is included in 
 3425: #     Functions.
 3426: # (b) When displaying folder contents in course editor, used to determine if
 3427: #     "Edit" link will be displayed alongside resource.
 3428: #
 3429: #  input: six args -- filename (decluttered), course number, course domain,
 3430: #                   url, symb (if registered) and group (if this is a group
 3431: #                   item -- e.g., bulletin board, group page etc.).
 3432: #  output: array of five scalars -- 
 3433: #          $cfile -- url for file editing if editable on current server
 3434: #          $home -- homeserver of resource (i.e., for author if published,
 3435: #                                           or course if uploaded.).
 3436: #          $switchserver --  1 if server switch will be needed.
 3437: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3438: #          $forceview -- 1 if icon/link should be to go to view mode
 3439: #
 3440: 
 3441: sub can_edit_resource {
 3442:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3443:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3444: #
 3445: # For aboutme pages user can only edit his/her own.
 3446: #
 3447:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3448:         my ($sdom,$sname) = ($1,$2);
 3449:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3450:             $home = $env{'user.home'};
 3451:             $cfile = $resurl;
 3452:             if ($env{'form.forceedit'}) {
 3453:                 $forceview = 1;
 3454:             } else {
 3455:                 $forceedit = 1;
 3456:             }
 3457:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3458:         } else {
 3459:             return;
 3460:         }
 3461:     }
 3462: 
 3463:     if ($env{'request.course.id'}) {
 3464:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3465:         if ($group ne '') {
 3466: # if this is a group homepage or group bulletin board, check group privs
 3467:             my $allowed = 0;
 3468:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3469:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3470:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3471:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3472:                     $allowed = 1;
 3473:                 }
 3474:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3475:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3476:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3477:                     $allowed = 1;
 3478:                 }
 3479:             }
 3480:             if ($allowed) {
 3481:                 $home=&homeserver($cnum,$cdom);
 3482:                 if ($env{'form.forceedit'}) {
 3483:                     $forceview = 1;
 3484:                 } else {
 3485:                     $forceedit = 1;
 3486:                 }
 3487:                 $cfile = $resurl;
 3488:             } else {
 3489:                 return;
 3490:             }
 3491:         } else {
 3492:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3493:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3494:                     return;
 3495:                 }
 3496:             } elsif (!$crsedit) {
 3497: #
 3498: # No edit allowed where CC has switched to student role.
 3499: #
 3500:                 return;
 3501:             }
 3502:         }
 3503:     }
 3504: 
 3505:     if ($file ne '') {
 3506:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3507:             if (&is_course_upload($file,$cnum,$cdom)) {
 3508:                 $uploaded = 1;
 3509:                 $incourse = 1;
 3510:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3511:                     $cfile = &hreflocation('',$file);
 3512:                     if ($env{'form.forceedit'}) {
 3513:                         $forceview = 1;
 3514:                     } else {
 3515:                         $forceedit = 1;
 3516:                     }
 3517:                 }
 3518:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3519:                 $incourse = 1;
 3520:                 if ($env{'form.forceedit'}) {
 3521:                     $forceview = 1;
 3522:                 } else {
 3523:                     $forceedit = 1;
 3524:                 }
 3525:                 $cfile = $resurl;
 3526:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3527:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3528:                     $incourse = 1;
 3529:                     if ($env{'form.forceedit'}) {
 3530:                         $forceview = 1;
 3531:                     } else {
 3532:                         $forceedit = 1;
 3533:                     }
 3534:                     $cfile = $resurl;
 3535:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3536:                     $incourse = 1;
 3537:                     $cfile = $resurl.'/smpedit';
 3538:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3539:                     $incourse = 1;
 3540:                     if ($env{'form.forceedit'}) {
 3541:                         $forceview = 1;
 3542:                     } else {
 3543:                         $forceedit = 1;
 3544:                     }
 3545:                     $cfile = $resurl;
 3546:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3547:                     $incourse = 1;
 3548:                     if ($env{'form.forceedit'}) {
 3549:                         $forceview = 1;
 3550:                     } else {
 3551:                         $forceedit = 1;
 3552:                     }
 3553:                     $cfile = $resurl;
 3554:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3555:                     $incourse = 1;
 3556:                     if ($env{'form.forceedit'}) {
 3557:                         $forceview = 1;
 3558:                     } else {
 3559:                         $forceedit = 1;
 3560:                     }
 3561:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3562:                 }
 3563:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3564:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3565:                 if (&is_on_map($template)) { 
 3566:                     $incourse = 1;
 3567:                     $forceview = 1;
 3568:                     $cfile = $template;
 3569:                 }
 3570:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3571:                     $incourse = 1;
 3572:                     if ($env{'form.forceedit'}) {
 3573:                         $forceview = 1;
 3574:                     } else {
 3575:                         $forceedit = 1;
 3576:                     }
 3577:                     $cfile = $resurl;
 3578:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3579:                 $incourse = 1;
 3580:                 if ($env{'form.forceedit'}) {
 3581:                     $forceview = 1;
 3582:                 } else {
 3583:                     $forceedit = 1;
 3584:                 }
 3585:                 $cfile = $resurl;
 3586:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3587:                 $incourse = 1;
 3588:                 $forceview = 1;
 3589:                 if ($symb) {
 3590:                     my ($map,$id,$res)=&decode_symb($symb);
 3591:                     $env{'request.symb'} = $symb;
 3592:                     $cfile = &clutter($res);
 3593:                 } else {
 3594:                     $cfile = $env{'form.suppurl'};
 3595:                     my $escfile = &unescape($cfile);
 3596:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3597:                         $cfile = '/adm/wrapper'.$escfile;
 3598:                     } else {
 3599:                         $escfile =~ s{^http://}{};
 3600:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3601:                     }
 3602:                 }
 3603:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3604:                 if ($env{'form.forceedit'}) {
 3605:                     $forceview = 1;
 3606:                 } else {
 3607:                     $forceedit = 1;
 3608:                 }
 3609:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3610:             }
 3611:         }
 3612:         if ($uploaded || $incourse) {
 3613:             $home=&homeserver($cnum,$cdom);
 3614:         } elsif ($file !~ m{/$}) {
 3615:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3616:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3617:             # Check that the user has permission to edit this resource
 3618:             my $setpriv = 1;
 3619:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3620:             if (defined($cfudom)) {
 3621:                 $home=&homeserver($cfuname,$cfudom);
 3622:                 $cfile=$file;
 3623:             }
 3624:         }
 3625:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3626:             (($home ne '') && ($home ne 'no_host'))) {
 3627:             my @ids=&current_machine_ids();
 3628:             unless (grep(/^\Q$home\E$/,@ids)) {
 3629:                 $switchserver=1;
 3630:             }
 3631:         }
 3632:     }
 3633:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3634: }
 3635: 
 3636: sub is_course_upload {
 3637:     my ($file,$cnum,$cdom) = @_;
 3638:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3639:     $uploadpath =~ s{^\/}{};
 3640:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3641:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3642:         return 1;
 3643:     }
 3644:     return;
 3645: }
 3646: 
 3647: sub in_course {
 3648:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3649:     if ($hideprivileged) {
 3650:         my $skipuser;
 3651:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3652:         my @possdoms = ($cdom);  
 3653:         if ($coursehash{'checkforpriv'}) { 
 3654:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3655:         }
 3656:         if (&privileged($uname,$udom,\@possdoms)) {
 3657:             $skipuser = 1;
 3658:             if ($coursehash{'nothideprivileged'}) {
 3659:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3660:                     my $user;
 3661:                     if ($item =~ /:/) {
 3662:                         $user = $item;
 3663:                     } else {
 3664:                         $user = join(':',split(/[\@]/,$item));
 3665:                     }
 3666:                     if ($user eq $uname.':'.$udom) {
 3667:                         undef($skipuser);
 3668:                         last;
 3669:                     }
 3670:                 }
 3671:             }
 3672:             if ($skipuser) {
 3673:                 return 0;
 3674:             }
 3675:         }
 3676:     }
 3677:     $type ||= 'any';
 3678:     if (!defined($cdom) || !defined($cnum)) {
 3679:         my $cid  = $env{'request.course.id'};
 3680:         $cdom = $env{'course.'.$cid.'.domain'};
 3681:         $cnum = $env{'course.'.$cid.'.num'};
 3682:     }
 3683:     my $typesref;
 3684:     if (($type eq 'any') || ($type eq 'all')) {
 3685:         $typesref = ['active','previous','future'];
 3686:     } elsif ($type eq 'previous' || $type eq 'future') {
 3687:         $typesref = [$type];
 3688:     }
 3689:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3690:                               $typesref,undef,[$cdom]);
 3691:     my ($tmp) = keys(%roles);
 3692:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3693:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3694:     if (@course_roles > 0) {
 3695:         return 1;
 3696:     }
 3697:     return 0;
 3698: }
 3699: 
 3700: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3701: # input: action, courseID, current domain, intended
 3702: #        path to file, source of file, instruction to parse file for objects,
 3703: #        ref to hash for embedded objects,
 3704: #        ref to hash for codebase of java objects.
 3705: #        reference to scalar to accommodate mime type determined
 3706: #          from File::MMagic if $parser = parse.
 3707: #
 3708: # output: url to file (if action was uploaddoc), 
 3709: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3710: #
 3711: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3712: # course.
 3713: #
 3714: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3715: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3716: #          course's home server.
 3717: #
 3718: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3719: #          be copied from $source (current location) to 
 3720: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3721: #         and will then be copied to
 3722: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3723: #         course's home server.
 3724: #
 3725: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3726: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3727: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3728: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3729: #         in course's home server.
 3730: #
 3731: 
 3732: sub process_coursefile {
 3733:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3734:         $mimetype)=@_;
 3735:     my $fetchresult;
 3736:     my $home=&homeserver($docuname,$docudom);
 3737:     if ($action eq 'propagate') {
 3738:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3739: 			     $home);
 3740:     } else {
 3741:         my $fpath = '';
 3742:         my $fname = $file;
 3743:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3744:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3745:         my $filepath = &build_filepath($fpath);
 3746:         if ($action eq 'copy') {
 3747:             if ($source eq '') {
 3748:                 $fetchresult = 'no source file';
 3749:                 return $fetchresult;
 3750:             } else {
 3751:                 my $destination = $filepath.'/'.$fname;
 3752:                 rename($source,$destination);
 3753:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3754:                                  $home);
 3755:             }
 3756:         } elsif ($action eq 'uploaddoc') {
 3757:             open(my $fh,'>',$filepath.'/'.$fname);
 3758:             print $fh $env{'form.'.$source};
 3759:             close($fh);
 3760:             if ($parser eq 'parse') {
 3761:                 my $mm = new File::MMagic;
 3762:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3763:                 if ($type eq 'text/html') {
 3764:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3765:                     unless ($parse_result eq 'ok') {
 3766:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3767:                     }
 3768:                 }
 3769:                 if (ref($mimetype)) {
 3770:                     $$mimetype = $type;
 3771:                 } 
 3772:             }
 3773:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3774:                                  $home);
 3775:             if ($fetchresult eq 'ok') {
 3776:                 return '/uploaded/'.$fpath.'/'.$fname;
 3777:             } else {
 3778:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3779:                         ' to host '.$home.': '.$fetchresult);
 3780:                 return '/adm/notfound.html';
 3781:             }
 3782:         }
 3783:     }
 3784:     unless ( $fetchresult eq 'ok') {
 3785:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3786:              ' to host '.$home.': '.$fetchresult);
 3787:     }
 3788:     return $fetchresult;
 3789: }
 3790: 
 3791: sub build_filepath {
 3792:     my ($fpath) = @_;
 3793:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3794:     unless ($fpath eq '') {
 3795:         my @parts=split('/',$fpath);
 3796:         foreach my $part (@parts) {
 3797:             $filepath.= '/'.$part;
 3798:             if ((-e $filepath)!=1) {
 3799:                 mkdir($filepath,0777);
 3800:             }
 3801:         }
 3802:     }
 3803:     return $filepath;
 3804: }
 3805: 
 3806: sub store_edited_file {
 3807:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3808:     my $file = $primary_url;
 3809:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3810:     my $fpath = '';
 3811:     my $fname = $file;
 3812:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3813:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3814:     my $filepath = &build_filepath($fpath);
 3815:     open(my $fh,'>',$filepath.'/'.$fname);
 3816:     print $fh $content;
 3817:     close($fh);
 3818:     my $home=&homeserver($docuname,$docudom);
 3819:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3820: 			  $home);
 3821:     if ($$fetchresult eq 'ok') {
 3822:         return '/uploaded/'.$fpath.'/'.$fname;
 3823:     } else {
 3824:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3825: 		 ' to host '.$home.': '.$$fetchresult);
 3826:         return '/adm/notfound.html';
 3827:     }
 3828: }
 3829: 
 3830: sub clean_filename {
 3831:     my ($fname,$args)=@_;
 3832: # Replace Windows backslashes by forward slashes
 3833:     $fname=~s/\\/\//g;
 3834:     if (!$args->{'keep_path'}) {
 3835:         # Get rid of everything but the actual filename
 3836: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3837:     }
 3838: # Replace spaces by underscores
 3839:     $fname=~s/\s+/\_/g;
 3840: # Replace all other weird characters by nothing
 3841:     $fname=~s{[^/\w\.\-]}{}g;
 3842: # Replace all .\d. sequences with _\d. so they no longer look like version
 3843: # numbers
 3844:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3845:     return $fname;
 3846: }
 3847: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3848: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3849: # image with the same aspect ratio as the original, but with dimensions which do 
 3850: # not exceed $resizewidth and $resizeheight.
 3851:  
 3852: sub resizeImage {
 3853:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3854:     my $ima = Image::Magick->new;
 3855:     my $resized;
 3856:     if (-e $img_path) {
 3857:         $ima->Read($img_path);
 3858:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3859:             my $width = $ima->Get('width');
 3860:             my $height = $ima->Get('height');
 3861:             if ($width > $resizewidth) {
 3862: 	        my $factor = $width/$resizewidth;
 3863:                 my $newheight = $height/$factor;
 3864:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3865:                 $resized = 1;
 3866:             }
 3867:         }
 3868:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3869:             my $width = $ima->Get('width');
 3870:             my $height = $ima->Get('height');
 3871:             if ($height > $resizeheight) {
 3872:                 my $factor = $height/$resizeheight;
 3873:                 my $newwidth = $width/$factor;
 3874:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3875:                 $resized = 1;
 3876:             }
 3877:         }
 3878:         if ($resized) {
 3879:             $ima->Write($img_path);
 3880:         }
 3881:     }
 3882:     return;
 3883: }
 3884: 
 3885: # --------------- Take an uploaded file and put it into the userfiles directory
 3886: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3887: #                    the desired filename is in $env{"form.$formname.filename"}
 3888: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3889: #                                    canceloverwrite, or ''. 
 3890: #                   if 'coursedoc': upload to the current course
 3891: #                   if 'existingfile': write file to tmp/overwrites directory 
 3892: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3893: #                   $context is passed as argument to &finishuserfileupload
 3894: #        $subdir - directory in userfile to store the file into
 3895: #        $parser - instruction to parse file for objects ($parser = parse)    
 3896: #        $allfiles - reference to hash for embedded objects
 3897: #        $codebase - reference to hash for codebase of java objects
 3898: #        $desuname - username for permanent storage of uploaded file
 3899: #        $dsetudom - domain for permanaent storage of uploaded file
 3900: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3901: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3902: #        $resizewidth - width (pixels) to which to resize uploaded image
 3903: #        $resizeheight - height (pixels) to which to resize uploaded image
 3904: #        $mimetype - reference to scalar to accommodate mime type determined
 3905: #                    from File::MMagic.
 3906: # 
 3907: # output: url of file in userspace, or error: <message> 
 3908: #             or /adm/notfound.html if failure to upload occurse
 3909: 
 3910: sub userfileupload {
 3911:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3912:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3913:     if (!defined($subdir)) { $subdir='unknown'; }
 3914:     my $fname=$env{'form.'.$formname.'.filename'};
 3915:     $fname=&clean_filename($fname);
 3916:     # See if there is anything left
 3917:     unless ($fname) { return 'error: no uploaded file'; }
 3918:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3919:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3920:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3921:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3922:         my $now = time;
 3923:         my $filepath;
 3924:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3925:              $filepath = 'tmp/helprequests/'.$now;
 3926:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3927:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3928:                          '_'.$env{'user.domain'}.'/pending';
 3929:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3930:             my ($docuname,$docudom);
 3931:             if ($destudom =~ /^$match_domain$/) {
 3932:                 $docudom = $destudom;
 3933:             } else {
 3934:                 $docudom = $env{'user.domain'};
 3935:             }
 3936:             if ($destuname =~ /^$match_username$/) {
 3937:                 $docuname = $destuname;
 3938:             } else {
 3939:                 $docuname = $env{'user.name'};
 3940:             }
 3941:             if (exists($env{'form.group'})) {
 3942:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3943:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3944:             }
 3945:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3946:             if ($context eq 'canceloverwrite') {
 3947:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3948:                 if (-e  $tempfile) {
 3949:                     my @info = stat($tempfile);
 3950:                     if ($info[9] eq $env{'form.timestamp'}) {
 3951:                         unlink($tempfile);
 3952:                     }
 3953:                 }
 3954:                 return;
 3955:             }
 3956:         }
 3957:         # Create the directory if not present
 3958:         my @parts=split(/\//,$filepath);
 3959:         my $fullpath = $perlvar{'lonDaemons'};
 3960:         for (my $i=0;$i<@parts;$i++) {
 3961:             $fullpath .= '/'.$parts[$i];
 3962:             if ((-e $fullpath)!=1) {
 3963:                 mkdir($fullpath,0777);
 3964:             }
 3965:         }
 3966:         open(my $fh,'>',$fullpath.'/'.$fname);
 3967:         print $fh $env{'form.'.$formname};
 3968:         close($fh);
 3969:         if ($context eq 'existingfile') {
 3970:             my @info = stat($fullpath.'/'.$fname);
 3971:             return ($fullpath.'/'.$fname,$info[9]);
 3972:         } else {
 3973:             return $fullpath.'/'.$fname;
 3974:         }
 3975:     }
 3976:     if ($subdir eq 'scantron') {
 3977:         $fname = 'scantron_orig_'.$fname;
 3978:     } else {
 3979:         $fname="$subdir/$fname";
 3980:     }
 3981:     if ($context eq 'coursedoc') {
 3982: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3983: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3984:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3985:             return &finishuserfileupload($docuname,$docudom,
 3986: 					 $formname,$fname,$parser,$allfiles,
 3987: 					 $codebase,$thumbwidth,$thumbheight,
 3988:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3989:         } else {
 3990:             if ($env{'form.folder'}) {
 3991:                 $fname=$env{'form.folder'}.'/'.$fname;
 3992:             }
 3993:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3994: 				       $fname,$formname,$parser,
 3995: 				       $allfiles,$codebase,$mimetype);
 3996:         }
 3997:     } elsif (defined($destuname)) {
 3998:         my $docuname=$destuname;
 3999:         my $docudom=$destudom;
 4000: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4001: 				     $parser,$allfiles,$codebase,
 4002:                                      $thumbwidth,$thumbheight,
 4003:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4004:     } else {
 4005:         my $docuname=$env{'user.name'};
 4006:         my $docudom=$env{'user.domain'};
 4007:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4008:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4009:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4010:         }
 4011: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4012: 				     $parser,$allfiles,$codebase,
 4013:                                      $thumbwidth,$thumbheight,
 4014:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4015:     }
 4016: }
 4017: 
 4018: sub finishuserfileupload {
 4019:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4020:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4021:     my $path=$docudom.'/'.$docuname.'/';
 4022:     my $filepath=$perlvar{'lonDocRoot'};
 4023:   
 4024:     my ($fnamepath,$file,$fetchthumb);
 4025:     $file=$fname;
 4026:     if ($fname=~m|/|) {
 4027:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4028: 	$path.=$fnamepath.'/';
 4029:     }
 4030:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4031:     my $count;
 4032:     for ($count=4;$count<=$#parts;$count++) {
 4033:         $filepath.="/$parts[$count]";
 4034:         if ((-e $filepath)!=1) {
 4035: 	    mkdir($filepath,0777);
 4036:         }
 4037:     }
 4038: 
 4039: # Save the file
 4040:     {
 4041: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4042: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4043: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4044: 	    return '/adm/notfound.html';
 4045: 	}
 4046:         if ($context eq 'overwrite') {
 4047:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4048:             my $target = $filepath.'/'.$file;
 4049:             if (-e $source) {
 4050:                 my @info = stat($source);
 4051:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4052:                     unless (&File::Copy::move($source,$target)) {
 4053:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4054:                         return "Moving from $source failed";
 4055:                     }
 4056:                 } else {
 4057:                     return "Temporary file: $source had unexpected date/time for last modification";
 4058:                 }
 4059:             } else {
 4060:                 return "Temporary file: $source missing";
 4061:             }
 4062:         } elsif (!print FH ($env{'form.'.$formname})) {
 4063: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4064: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4065: 	    return '/adm/notfound.html';
 4066: 	}
 4067: 	close(FH);
 4068:         if ($resizewidth && $resizeheight) {
 4069:             my $mm = new File::MMagic;
 4070:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4071:             if ($mime_type =~ m{^image/}) {
 4072: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4073:             }  
 4074: 	}
 4075:     }
 4076:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4077:         if (ref($mimetype)) {
 4078:             if ($$mimetype eq '') {
 4079:                 my $mm = new File::MMagic;
 4080:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4081:                 $$mimetype = $type;
 4082:             }
 4083:         }
 4084:     }
 4085:     if ($parser eq 'parse') {
 4086:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4087:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4088:                                                        $allfiles,$codebase);
 4089:             unless ($parse_result eq 'ok') {
 4090:                 &logthis('Failed to parse '.$filepath.$file.
 4091: 	   	         ' for embedded media: '.$parse_result); 
 4092:             }
 4093:         }
 4094:     }
 4095:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4096:         my $input = $filepath.'/'.$file;
 4097:         my $output = $filepath.'/'.'tn-'.$file;
 4098:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4099:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4100:         system({$args[0]} @args);
 4101:         if (-e $filepath.'/'.'tn-'.$file) {
 4102:             $fetchthumb  = 1; 
 4103:         }
 4104:     }
 4105:  
 4106: # Notify homeserver to grep it
 4107: #
 4108:     my $docuhome=&homeserver($docuname,$docudom);	
 4109:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4110:     if ($fetchresult eq 'ok') {
 4111:         if ($fetchthumb) {
 4112:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4113:             if ($thumbresult ne 'ok') {
 4114:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4115:                          $docuhome.': '.$thumbresult);
 4116:             }
 4117:         }
 4118: #
 4119: # Return the URL to it
 4120:         return '/uploaded/'.$path.$file;
 4121:     } else {
 4122:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4123: 		 ': '.$fetchresult);
 4124:         return '/adm/notfound.html';
 4125:     }
 4126: }
 4127: 
 4128: sub extract_embedded_items {
 4129:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4130:     my @state = ();
 4131:     my (%lastids,%related,%shockwave,%flashvars);
 4132:     my %javafiles = (
 4133:                       codebase => '',
 4134:                       code => '',
 4135:                       archive => ''
 4136:                     );
 4137:     my %mediafiles = (
 4138:                       src => '',
 4139:                       movie => '',
 4140:                      );
 4141:     my $p;
 4142:     if ($content) {
 4143:         $p = HTML::LCParser->new($content);
 4144:     } else {
 4145:         $p = HTML::LCParser->new($fullpath);
 4146:     }
 4147:     while (my $t=$p->get_token()) {
 4148: 	if ($t->[0] eq 'S') {
 4149: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4150: 	    push(@state, $tagname);
 4151:             if (lc($tagname) eq 'allow') {
 4152:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4153:             }
 4154: 	    if (lc($tagname) eq 'img') {
 4155: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4156: 	    }
 4157: 	    if (lc($tagname) eq 'a') {
 4158:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4159:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4160:                 }
 4161: 	    }
 4162:             if (lc($tagname) eq 'script') {
 4163:                 my $src;
 4164:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4165:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4166:                 } else {
 4167:                     if ($attr->{'src'} ne '') {
 4168:                         $src = $attr->{'src'};
 4169:                         &add_filetype($allfiles,$src,'src');
 4170:                     }
 4171:                 }
 4172:                 my $text = $p->get_trimmed_text();
 4173:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4174:                     my @swfargs = split(/,/,$1);
 4175:                     foreach my $item (@swfargs) {
 4176:                         $item =~ s/["']//g;
 4177:                         $item =~ s/^\s+//;
 4178:                         $item =~ s/\s+$//;
 4179:                     }
 4180:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4181:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4182:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4183:                         } else {
 4184:                             $related{$swfargs[0]} = [$swfargs[2]];
 4185:                         }
 4186:                     }
 4187:                 }
 4188:             }
 4189:             if (lc($tagname) eq 'link') {
 4190:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4191:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4192:                 }
 4193:             }
 4194: 	    if (lc($tagname) eq 'object' ||
 4195: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4196: 		foreach my $item (keys(%javafiles)) {
 4197: 		    $javafiles{$item} = '';
 4198: 		}
 4199:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4200:                     $lastids{lc($tagname)} = $attr->{'id'};
 4201:                 }
 4202: 	    }
 4203: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4204: 		my $name = lc($attr->{'name'});
 4205: 		foreach my $item (keys(%javafiles)) {
 4206: 		    if ($name eq $item) {
 4207: 			$javafiles{$item} = $attr->{'value'};
 4208: 			last;
 4209: 		    }
 4210: 		}
 4211:                 my $pathfrom;
 4212: 		foreach my $item (keys(%mediafiles)) {
 4213: 		    if ($name eq $item) {
 4214:                         $pathfrom = $attr->{'value'};
 4215:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4216: 			&add_filetype($allfiles,$pathfrom,$name);
 4217: 			last;
 4218: 		    }
 4219: 		}
 4220:                 if ($name eq 'flashvars') {
 4221:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4222:                 }
 4223:                 if ($pathfrom ne '') {
 4224:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4225:                                          $pathfrom);
 4226:                 }
 4227: 	    }
 4228: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4229: 		foreach my $item (keys(%javafiles)) {
 4230: 		    if ($attr->{$item}) {
 4231: 			$javafiles{$item} = $attr->{$item};
 4232: 			last;
 4233: 		    }
 4234: 		}
 4235: 		foreach my $item (keys(%mediafiles)) {
 4236: 		    if ($attr->{$item}) {
 4237: 			&add_filetype($allfiles,$attr->{$item},$item);
 4238: 			last;
 4239: 		    }
 4240: 		}
 4241:                 if (lc($tagname) eq 'embed') {
 4242:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4243:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4244:                                              $attr->{'src'});
 4245:                     }
 4246:                 }
 4247: 	    }
 4248:             if (lc($tagname) eq 'iframe') {
 4249:                 my $src = $attr->{'src'} ;
 4250:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4251:                     &add_filetype($allfiles,$src,'src');
 4252:                 } elsif ($src =~ m{^/}) {
 4253:                     if ($env{'request.course.id'}) {
 4254:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4255:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4256:                         my $url = &hreflocation('',$fullpath);
 4257:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4258:                             my $relpath = $1;
 4259:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4260:                                 &add_filetype($allfiles,$1,'src');
 4261:                             }
 4262:                         }
 4263:                     }
 4264:                 }
 4265:             }
 4266:             if ($t->[4] =~ m{/>$}) {
 4267:                 pop(@state);
 4268:             }
 4269: 	} elsif ($t->[0] eq 'E') {
 4270: 	    my ($tagname) = ($t->[1]);
 4271: 	    if ($javafiles{'codebase'} ne '') {
 4272: 		$javafiles{'codebase'} .= '/';
 4273: 	    }  
 4274: 	    if (lc($tagname) eq 'applet' ||
 4275: 		lc($tagname) eq 'object' ||
 4276: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4277: 		) {
 4278: 		foreach my $item (keys(%javafiles)) {
 4279: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4280: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4281: 			&add_filetype($allfiles,$file,$item);
 4282: 		    }
 4283: 		}
 4284: 	    } 
 4285: 	    pop @state;
 4286: 	}
 4287:     }
 4288:     foreach my $id (sort(keys(%flashvars))) {
 4289:         if ($shockwave{$id} ne '') {
 4290:             my @pairs = split(/\&/,$flashvars{$id});
 4291:             foreach my $pair (@pairs) {
 4292:                 my ($key,$value) = split(/\=/,$pair);
 4293:                 if ($key eq 'thumb') {
 4294:                     &add_filetype($allfiles,$value,$key);
 4295:                 } elsif ($key eq 'content') {
 4296:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4297:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4298:                     if ($ext ne '') {
 4299:                         &add_filetype($allfiles,$path.$value,$ext);
 4300:                     }
 4301:                 }
 4302:             }
 4303:         }
 4304:     }
 4305:     return 'ok';
 4306: }
 4307: 
 4308: sub add_filetype {
 4309:     my ($allfiles,$file,$type)=@_;
 4310:     if (exists($allfiles->{$file})) {
 4311: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4312: 	    push(@{$allfiles->{$file}}, &escape($type));
 4313: 	}
 4314:     } else {
 4315: 	@{$allfiles->{$file}} = (&escape($type));
 4316:     }
 4317: }
 4318: 
 4319: sub embedded_dependency {
 4320:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4321:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4322:         if (($identifier ne '') &&
 4323:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4324:             ($pathfrom ne '')) {
 4325:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4326:             foreach my $dep (@{$related->{$identifier}}) {
 4327:                 &add_filetype($allfiles,$path.$dep,'object');
 4328:             }
 4329:         }
 4330:     }
 4331:     return;
 4332: }
 4333: 
 4334: sub removeuploadedurl {
 4335:     my ($url)=@_;	
 4336:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4337:     return &removeuserfile($uname,$udom,$fname);
 4338: }
 4339: 
 4340: sub removeuserfile {
 4341:     my ($docuname,$docudom,$fname)=@_;
 4342:     my $home=&homeserver($docuname,$docudom);    
 4343:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4344:     if ($result eq 'ok') {	
 4345:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4346:             my $metafile = $fname.'.meta';
 4347:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4348: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4349:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4350:             my $sqlresult = 
 4351:                 &update_portfolio_table($docuname,$docudom,$file,
 4352:                                         'portfolio_metadata',$group,
 4353:                                         'delete');
 4354:         }
 4355:     }
 4356:     return $result;
 4357: }
 4358: 
 4359: sub mkdiruserfile {
 4360:     my ($docuname,$docudom,$dir)=@_;
 4361:     my $home=&homeserver($docuname,$docudom);
 4362:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4363: }
 4364: 
 4365: sub renameuserfile {
 4366:     my ($docuname,$docudom,$old,$new)=@_;
 4367:     my $home=&homeserver($docuname,$docudom);
 4368:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4369:                         &escape("$old").':'.&escape("$new"),$home);
 4370:     if ($result eq 'ok') {
 4371:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4372:             my $oldmeta = $old.'.meta';
 4373:             my $newmeta = $new.'.meta';
 4374:             my $metaresult = 
 4375:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4376: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4377:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4378:             my $sqlresult = 
 4379:                 &update_portfolio_table($docuname,$docudom,$file,
 4380:                                         'portfolio_metadata',$group,
 4381:                                         'delete');
 4382:         }
 4383:     }
 4384:     return $result;
 4385: }
 4386: 
 4387: # ------------------------------------------------------------------------- Log
 4388: 
 4389: sub log {
 4390:     my ($dom,$nam,$hom,$what)=@_;
 4391:     return critical("log:$dom:$nam:$what",$hom);
 4392: }
 4393: 
 4394: # ------------------------------------------------------------------ Course Log
 4395: #
 4396: # This routine flushes several buffers of non-mission-critical nature
 4397: #
 4398: 
 4399: sub flushcourselogs {
 4400:     &logthis('Flushing log buffers');
 4401: #
 4402: # course logs
 4403: # This is a log of all transactions in a course, which can be used
 4404: # for data mining purposes
 4405: #
 4406: # It also collects the courseid database, which lists last transaction
 4407: # times and course titles for all courseids
 4408: #
 4409:     my %courseidbuffer=();
 4410:     foreach my $crsid (keys(%courselogs)) {
 4411:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4412: 		          &escape($courselogs{$crsid}),
 4413: 		          $coursehombuf{$crsid}) eq 'ok') {
 4414: 	    delete $courselogs{$crsid};
 4415:         } else {
 4416:             &logthis('Failed to flush log buffer for '.$crsid);
 4417:             if (length($courselogs{$crsid})>40000) {
 4418:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4419:                         " exceeded maximum size, deleting.</font>");
 4420:                delete $courselogs{$crsid};
 4421:             }
 4422:         }
 4423:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4424:             'description' => $coursedescrbuf{$crsid},
 4425:             'inst_code'    => $courseinstcodebuf{$crsid},
 4426:             'type'        => $coursetypebuf{$crsid},
 4427:             'owner'       => $courseownerbuf{$crsid},
 4428:         };
 4429:     }
 4430: #
 4431: # Write course id database (reverse lookup) to homeserver of courses 
 4432: # Is used in pickcourse
 4433: #
 4434:     foreach my $crs_home (keys(%courseidbuffer)) {
 4435:         my $response = &courseidput(&host_domain($crs_home),
 4436:                                     $courseidbuffer{$crs_home},
 4437:                                     $crs_home,'timeonly');
 4438:     }
 4439: #
 4440: # File accesses
 4441: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4442: #
 4443:     foreach my $entry (keys(%accesshash)) {
 4444:         if ($entry =~ /___count$/) {
 4445:             my ($dom,$name);
 4446:             ($dom,$name,undef)=
 4447: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4448:             if (! defined($dom) || $dom eq '' || 
 4449:                 ! defined($name) || $name eq '') {
 4450:                 my $cid = $env{'request.course.id'};
 4451:                 $dom  = $env{'request.'.$cid.'.domain'};
 4452:                 $name = $env{'request.'.$cid.'.num'};
 4453:             }
 4454:             my $value = $accesshash{$entry};
 4455:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4456:             my %temphash=($url => $value);
 4457:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4458:             if ($result eq 'ok') {
 4459:                 delete $accesshash{$entry};
 4460:             }
 4461:         } else {
 4462:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4463:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4464:             my %temphash=($entry => $accesshash{$entry});
 4465:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4466:                 delete $accesshash{$entry};
 4467:             }
 4468:         }
 4469:     }
 4470: #
 4471: # Roles
 4472: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4473: #
 4474:     foreach my $entry (keys(%userrolehash)) {
 4475:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4476: 	    split(/\:/,$entry);
 4477:         if (&Apache::lonnet::put('nohist_userroles',
 4478:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4479:                 $rudom,$runame) eq 'ok') {
 4480: 	    delete $userrolehash{$entry};
 4481:         }
 4482:     }
 4483: #
 4484: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4485: #
 4486:     my %domrolebuffer = ();
 4487:     foreach my $entry (keys(%domainrolehash)) {
 4488:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4489:         if ($domrolebuffer{$rudom}) {
 4490:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4491:                       '='.&escape($domainrolehash{$entry});
 4492:         } else {
 4493:             $domrolebuffer{$rudom}.=&escape($entry).
 4494:                       '='.&escape($domainrolehash{$entry});
 4495:         }
 4496:         delete $domainrolehash{$entry};
 4497:     }
 4498:     foreach my $dom (keys(%domrolebuffer)) {
 4499: 	my %servers;
 4500: 	if (defined(&domain($dom,'primary'))) {
 4501: 	    my $primary=&domain($dom,'primary');
 4502: 	    my $hostname=&hostname($primary);
 4503: 	    $servers{$primary} = $hostname;
 4504: 	} else { 
 4505: 	    %servers = &get_servers($dom,'library');
 4506: 	}
 4507: 	foreach my $tryserver (keys(%servers)) {
 4508: 	    if (&reply('domroleput:'.$dom.':'.
 4509: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4510: 		last;
 4511: 	    } else {  
 4512: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4513: 	    }
 4514:         }
 4515:     }
 4516:     $dumpcount++;
 4517: }
 4518: 
 4519: sub courselog {
 4520:     my $what=shift;
 4521:     $what=time.':'.$what;
 4522:     unless ($env{'request.course.id'}) { return ''; }
 4523:     $coursedombuf{$env{'request.course.id'}}=
 4524:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4525:     $coursenumbuf{$env{'request.course.id'}}=
 4526:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4527:     $coursehombuf{$env{'request.course.id'}}=
 4528:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4529:     $coursedescrbuf{$env{'request.course.id'}}=
 4530:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4531:     $courseinstcodebuf{$env{'request.course.id'}}=
 4532:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4533:     $courseownerbuf{$env{'request.course.id'}}=
 4534:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4535:     $coursetypebuf{$env{'request.course.id'}}=
 4536:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4537:     if (defined $courselogs{$env{'request.course.id'}}) {
 4538: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4539:     } else {
 4540: 	$courselogs{$env{'request.course.id'}}.=$what;
 4541:     }
 4542:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4543: 	&flushcourselogs();
 4544:     }
 4545: }
 4546: 
 4547: sub courseacclog {
 4548:     my $fnsymb=shift;
 4549:     unless ($env{'request.course.id'}) { return ''; }
 4550:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4551:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4552:         $what.=':POST';
 4553:         # FIXME: Probably ought to escape things....
 4554: 	foreach my $key (keys(%env)) {
 4555:             if ($key=~/^form\.(.*)/) {
 4556:                 my $formitem = $1;
 4557:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4558:                     $what.=':'.$formitem.'='.$env{$key};
 4559:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4560:                     $what.=':'.$formitem.'='.$env{$key};
 4561:                 }
 4562:             }
 4563:         }
 4564:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4565:         # FIXME: We should not be depending on a form parameter that someone
 4566:         # editing lonsearchcat.pm might change in the future.
 4567:         if ($env{'form.phase'} eq 'course_search') {
 4568:             $what.= ':POST';
 4569:             # FIXME: Probably ought to escape things....
 4570:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4571:                                  'crsdiscuss') {
 4572:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4573:             }
 4574:         }
 4575:     }
 4576:     &courselog($what);
 4577: }
 4578: 
 4579: sub countacc {
 4580:     my $url=&declutter(shift);
 4581:     return if (! defined($url) || $url eq '');
 4582:     unless ($env{'request.course.id'}) { return ''; }
 4583: #
 4584: # Mark that this url was used in this course
 4585: #
 4586:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4587: #
 4588: # Increase the access count for this resource in this child process
 4589: #
 4590:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4591:     $accesshash{$key}++;
 4592: }
 4593: 
 4594: sub linklog {
 4595:     my ($from,$to)=@_;
 4596:     $from=&declutter($from);
 4597:     $to=&declutter($to);
 4598:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4599:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4600: }
 4601: 
 4602: sub statslog {
 4603:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4604:     if ($users<2) { return; }
 4605:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4606:             'course'       => $env{'request.course.id'},
 4607:             'sections'     => '"all"',
 4608:             'num_students' => $users,
 4609:             'part'         => $part,
 4610:             'symb'         => $symb,
 4611:             'mean_tries'   => $av_attempts,
 4612:             'deg_of_diff'  => $degdiff});
 4613:     foreach my $key (keys(%dynstore)) {
 4614:         $accesshash{$key}=$dynstore{$key};
 4615:     }
 4616: }
 4617:   
 4618: sub userrolelog {
 4619:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4620:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4621:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4622:        $userrolehash
 4623:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4624:                     =$tend.':'.$tstart;
 4625:     }
 4626:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4627:        $userrolehash
 4628:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4629:                     =$tend.':'.$tstart;
 4630:     }
 4631:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4632:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4633:        $domainrolehash
 4634:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4635:                     = $tend.':'.$tstart;
 4636:     }
 4637: }
 4638: 
 4639: sub courserolelog {
 4640:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4641:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4642:         my $cdom = $1;
 4643:         my $cnum = $2;
 4644:         my $sec = $3;
 4645:         my $namespace = 'rolelog';
 4646:         my %storehash = (
 4647:                            role    => $trole,
 4648:                            start   => $tstart,
 4649:                            end     => $tend,
 4650:                            selfenroll => $selfenroll,
 4651:                            context    => $context,
 4652:                         );
 4653:         if ($trole eq 'gr') {
 4654:             $namespace = 'groupslog';
 4655:             $storehash{'group'} = $sec;
 4656:         } else {
 4657:             $storehash{'section'} = $sec;
 4658:         }
 4659:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4660:                    $domain,$cnum,$cdom);
 4661:         if (($trole ne 'st') || ($sec ne '')) {
 4662:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4663:         }
 4664:     }
 4665:     return;
 4666: }
 4667: 
 4668: sub domainrolelog {
 4669:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4670:     if ($area =~ m{^/($match_domain)/$}) {
 4671:         my $cdom = $1;
 4672:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4673:         my $namespace = 'rolelog';
 4674:         my %storehash = (
 4675:                            role    => $trole,
 4676:                            start   => $tstart,
 4677:                            end     => $tend,
 4678:                            context => $context,
 4679:                         );
 4680:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4681:                    $domain,$domconfiguser,$cdom);
 4682:     }
 4683:     return;
 4684: 
 4685: }
 4686: 
 4687: sub coauthorrolelog {
 4688:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4689:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4690:         my $audom = $1;
 4691:         my $auname = $2;
 4692:         my $namespace = 'rolelog';
 4693:         my %storehash = (
 4694:                            role    => $trole,
 4695:                            start   => $tstart,
 4696:                            end     => $tend,
 4697:                            context => $context,
 4698:                         );
 4699:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4700:                    $domain,$auname,$audom);
 4701:     }
 4702:     return;
 4703: }
 4704: 
 4705: sub get_course_adv_roles {
 4706:     my ($cid,$codes) = @_;
 4707:     $cid=$env{'request.course.id'} unless (defined($cid));
 4708:     my %coursehash=&coursedescription($cid);
 4709:     my $crstype = &Apache::loncommon::course_type($cid);
 4710:     my %nothide=();
 4711:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4712:         if ($user !~ /:/) {
 4713: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4714:         } else {
 4715:             $nothide{$user}=1;
 4716:         }
 4717:     }
 4718:     my @possdoms = ($coursehash{'domain'});
 4719:     if ($coursehash{'checkforpriv'}) {
 4720:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4721:     }
 4722:     my %returnhash=();
 4723:     my %dumphash=
 4724:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4725:     my $now=time;
 4726:     my %privileged;
 4727:     foreach my $entry (keys(%dumphash)) {
 4728: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4729:         if (($tstart) && ($tstart<0)) { next; }
 4730:         if (($tend) && ($tend<$now)) { next; }
 4731:         if (($tstart) && ($now<$tstart)) { next; }
 4732:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4733: 	if ($username eq '' || $domain eq '') { next; }
 4734:         if ((&privileged($username,$domain,\@possdoms)) &&
 4735:             (!$nothide{$username.':'.$domain})) { next; }
 4736: 	if ($role eq 'cr') { next; }
 4737:         if ($codes) {
 4738:             if ($section) { $role .= ':'.$section; }
 4739:             if ($returnhash{$role}) {
 4740:                 $returnhash{$role}.=','.$username.':'.$domain;
 4741:             } else {
 4742:                 $returnhash{$role}=$username.':'.$domain;
 4743:             }
 4744:         } else {
 4745:             my $key=&plaintext($role,$crstype);
 4746:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4747:             if ($returnhash{$key}) {
 4748: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4749:             } else {
 4750:                 $returnhash{$key}=$username.':'.$domain;
 4751:             }
 4752:         }
 4753:     }
 4754:     return %returnhash;
 4755: }
 4756: 
 4757: sub get_my_roles {
 4758:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4759:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4760:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4761:     my (%dumphash,%nothide);
 4762:     if ($context eq 'userroles') {
 4763:         %dumphash = &dump('roles',$udom,$uname);
 4764:     } else {
 4765:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4766:         if ($hidepriv) {
 4767:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4768:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4769:                 if ($user !~ /:/) {
 4770:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4771:                 } else {
 4772:                     $nothide{$user} = 1;
 4773:                 }
 4774:             }
 4775:         }
 4776:     }
 4777:     my %returnhash=();
 4778:     my $now=time;
 4779:     my %privileged;
 4780:     foreach my $entry (keys(%dumphash)) {
 4781:         my ($role,$tend,$tstart);
 4782:         if ($context eq 'userroles') {
 4783:             next if ($entry =~ /^rolesdef/);
 4784: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4785:         } else {
 4786:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4787:         }
 4788:         if (($tstart) && ($tstart<0)) { next; }
 4789:         my $status = 'active';
 4790:         if (($tend) && ($tend<=$now)) {
 4791:             $status = 'previous';
 4792:         } 
 4793:         if (($tstart) && ($now<$tstart)) {
 4794:             $status = 'future';
 4795:         }
 4796:         if (ref($types) eq 'ARRAY') {
 4797:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4798:                 next;
 4799:             } 
 4800:         } else {
 4801:             if ($status ne 'active') {
 4802:                 next;
 4803:             }
 4804:         }
 4805:         my ($rolecode,$username,$domain,$section,$area);
 4806:         if ($context eq 'userroles') {
 4807:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4808:             (undef,$domain,$username,$section) = split(/\//,$area);
 4809:         } else {
 4810:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4811:         }
 4812:         if (ref($roledoms) eq 'ARRAY') {
 4813:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4814:                 next;
 4815:             }
 4816:         }
 4817:         if (ref($roles) eq 'ARRAY') {
 4818:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4819:                 if ($role =~ /^cr\//) {
 4820:                     if (!grep(/^cr$/,@{$roles})) {
 4821:                         next;
 4822:                     }
 4823:                 } elsif ($role =~ /^gr\//) {
 4824:                     if (!grep(/^gr$/,@{$roles})) {
 4825:                         next;
 4826:                     }
 4827:                 } else {
 4828:                     next;
 4829:                 }
 4830:             }
 4831:         }
 4832:         if ($hidepriv) {
 4833:             my @privroles = ('dc','su');
 4834:             if ($context eq 'userroles') {
 4835:                 next if (grep(/^\Q$role\E$/,@privroles));
 4836:             } else {
 4837:                 my $possdoms = [$domain];
 4838:                 if (ref($roledoms) eq 'ARRAY') {
 4839:                    push(@{$possdoms},@{$roledoms}); 
 4840:                 }
 4841:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4842:                     if (!$nothide{$username.':'.$domain}) {
 4843:                         next;
 4844:                     }
 4845:                 }
 4846:             }
 4847:         }
 4848:         if ($withsec) {
 4849:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4850:                 $tstart.':'.$tend;
 4851:         } else {
 4852:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4853:         }
 4854:     }
 4855:     return %returnhash;
 4856: }
 4857: 
 4858: sub get_all_adhocroles {
 4859:     my ($dom) = @_;
 4860:     my @roles_by_num = ();
 4861:     my %domdefaults = &get_domain_defaults($dom);
 4862:     my (%description,%access_in_dom,%access_info);
 4863:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4864:         my $count = 0;
 4865:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4866:         my %ordered;
 4867:         foreach my $role (sort(keys(%domcurrent))) {
 4868:             my ($order,$desc,$access_in_dom);
 4869:             if (ref($domcurrent{$role}) eq 'HASH') {
 4870:                 $order = $domcurrent{$role}{'order'};
 4871:                 $desc = $domcurrent{$role}{'desc'};
 4872:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4873:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4874:             }
 4875:             if ($order eq '') {
 4876:                 $order = $count;
 4877:             }
 4878:             $ordered{$order} = $role;
 4879:             if ($desc ne '') {
 4880:                 $description{$role} = $desc;
 4881:             } else {
 4882:                 $description{$role}= $role;
 4883:             }
 4884:             $count++;
 4885:         }
 4886:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4887:             push(@roles_by_num,$ordered{$item});
 4888:         }
 4889:     }
 4890:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4891: }
 4892: 
 4893: sub get_my_adhocroles {
 4894:     my ($cid,$checkreg) = @_;
 4895:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4896:     if ($env{'request.course.id'} eq $cid) {
 4897:         $cdom = $env{'course.'.$cid.'.domain'};
 4898:         $cnum = $env{'course.'.$cid.'.num'};
 4899:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4900:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4901:         $cdom = $1;
 4902:         $cnum = $2;
 4903:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4904:                                      $cdom,$cnum);
 4905:     }
 4906:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4907:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4908:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4909:         if ($rosterhash{$user} ne '') {
 4910:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4911:             return ([],{}) if ($type eq 'auto');
 4912:         }
 4913:     }
 4914:     if (($cdom ne '') && ($cnum ne ''))  {
 4915:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4916:             my $then=$env{'user.login.time'};
 4917:             my $update=$env{'user.update.time'};
 4918:             if (!$update) {
 4919:                 $update = $then;
 4920:             }
 4921:             my @liveroles;
 4922:             foreach my $role ('dh','da') {
 4923:                 if ($env{"user.role.$role./$cdom/"}) {
 4924:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4925:                     my $limit = $update;
 4926:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4927:                         $limit = $then;
 4928:                     }
 4929:                     my $activerole = 1;
 4930:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4931:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4932:                     if ($activerole) {
 4933:                         push(@liveroles,$role);
 4934:                     }
 4935:                 }
 4936:             }
 4937:             if (@liveroles) {
 4938:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4939:                     my ($accessref,$accessinfo,%access_in_dom);
 4940:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4941:                     if (ref($roles_by_num) eq 'ARRAY') {
 4942:                         if (@{$roles_by_num}) {
 4943:                             my %settings;
 4944:                             if ($env{'request.course.id'} eq $cid) {
 4945:                                 foreach my $envkey (keys(%env)) {
 4946:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4947:                                         $settings{$1} = $env{$envkey};
 4948:                                     }
 4949:                                 }
 4950:                             } else {
 4951:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4952:                             }
 4953:                             my %setincrs;
 4954:                             if ($settings{'internal.adhocaccess'}) {
 4955:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4956:                             }
 4957:                             my @statuses;
 4958:                             if ($env{'environment.inststatus'}) {
 4959:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4960:                             }
 4961:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4962:                             if (ref($accessref) eq 'HASH') {
 4963:                                 %access_in_dom = %{$accessref};
 4964:                             }
 4965:                             foreach my $role (@{$roles_by_num}) {
 4966:                                 my ($curraccess,@okstatus,@personnel);
 4967:                                 if ($setincrs{$role}) {
 4968:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4969:                                     if ($curraccess eq 'status') {
 4970:                                         @okstatus = split(/\&/,$rest);
 4971:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4972:                                         @personnel = split(/\&/,$rest);
 4973:                                     }
 4974:                                 } else {
 4975:                                     $curraccess = $access_in_dom{$role};
 4976:                                     if (ref($accessinfo) eq 'HASH') {
 4977:                                         if ($curraccess eq 'status') {
 4978:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4979:                                                 @okstatus = @{$accessinfo->{$role}};
 4980:                                             }
 4981:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4982:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4983:                                                 @personnel = @{$accessinfo->{$role}};
 4984:                                             }
 4985:                                         }
 4986:                                     }
 4987:                                 }
 4988:                                 if ($curraccess eq 'none') {
 4989:                                     next;
 4990:                                 } elsif ($curraccess eq 'all') {
 4991:                                     push(@possroles,$role);
 4992:                                 } elsif ($curraccess eq 'dh') {
 4993:                                     if (grep(/^dh$/,@liveroles)) {
 4994:                                         push(@possroles,$role);
 4995:                                     } else {
 4996:                                         next;
 4997:                                     }
 4998:                                 } elsif ($curraccess eq 'da') {
 4999:                                     if (grep(/^da$/,@liveroles)) {
 5000:                                         push(@possroles,$role);
 5001:                                     } else {
 5002:                                         next;
 5003:                                     }
 5004:                                 } elsif ($curraccess eq 'status') {
 5005:                                     if (@okstatus) {
 5006:                                         if (!@statuses) {
 5007:                                             if (grep(/^default$/,@okstatus)) {
 5008:                                                 push(@possroles,$role);
 5009:                                             }
 5010:                                         } else {
 5011:                                             foreach my $status (@okstatus) {
 5012:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5013:                                                     push(@possroles,$role);
 5014:                                                     last;
 5015:                                                 }
 5016:                                             }
 5017:                                         }
 5018:                                     }
 5019:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5020:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5021:                                         if ($curraccess eq 'exc') {
 5022:                                             push(@possroles,$role);
 5023:                                         }
 5024:                                     } elsif ($curraccess eq 'inc') {
 5025:                                         push(@possroles,$role);
 5026:                                     }
 5027:                                 }
 5028:                             }
 5029:                         }
 5030:                     }
 5031:                 }
 5032:             }
 5033:         }
 5034:     }
 5035:     unless (ref($description) eq 'HASH') {
 5036:         if (ref($roles_by_num) eq 'ARRAY') {
 5037:             my %desc;
 5038:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5039:             $description = \%desc;
 5040:         } else {
 5041:             $description = {};
 5042:         }
 5043:     }
 5044:     return (\@possroles,$description);
 5045: }
 5046: 
 5047: # ----------------------------------------------------- Frontpage Announcements
 5048: #
 5049: #
 5050: 
 5051: sub postannounce {
 5052:     my ($server,$text)=@_;
 5053:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5054:     unless ($text=~/\w/) { $text=''; }
 5055:     return &reply('setannounce:'.&escape($text),$server);
 5056: }
 5057: 
 5058: sub getannounce {
 5059: 
 5060:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5061: 	my $announcement='';
 5062: 	while (my $line = <$fh>) { $announcement .= $line; }
 5063: 	close($fh);
 5064: 	if ($announcement=~/\w/) { 
 5065: 	    return 
 5066:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5067:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5068: 	} else {
 5069: 	    return '';
 5070: 	}
 5071:     } else {
 5072: 	return '';
 5073:     }
 5074: }
 5075: 
 5076: # ---------------------------------------------------------- Course ID routines
 5077: # Deal with domain's nohist_courseid.db files
 5078: #
 5079: 
 5080: sub courseidput {
 5081:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5082:     return unless (ref($storehash) eq 'HASH');
 5083:     my $outcome;
 5084:     if ($caller eq 'timeonly') {
 5085:         my $cids = '';
 5086:         foreach my $item (keys(%$storehash)) {
 5087:             $cids.=&escape($item).'&';
 5088:         }
 5089:         $cids=~s/\&$//;
 5090:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5091:                           $coursehome);       
 5092:     } else {
 5093:         my $items = '';
 5094:         foreach my $item (keys(%$storehash)) {
 5095:             $items.= &escape($item).'='.
 5096:                      &freeze_escape($$storehash{$item}).'&';
 5097:         }
 5098:         $items=~s/\&$//;
 5099:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5100:                           $coursehome);
 5101:     }
 5102:     if ($outcome eq 'unknown_cmd') {
 5103:         my $what;
 5104:         foreach my $cid (keys(%$storehash)) {
 5105:             $what .= &escape($cid).'=';
 5106:             foreach my $item ('description','inst_code','owner','type') {
 5107:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5108:             }
 5109:             $what =~ s/\:$/&/;
 5110:         }
 5111:         $what =~ s/\&$//;  
 5112:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5113:     } else {
 5114:         return $outcome;
 5115:     }
 5116: }
 5117: 
 5118: sub courseiddump {
 5119:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5120:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5121:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5122:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5123:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5124:     my $as_hash = 1;
 5125:     my %returnhash;
 5126:     if (!$domfilter) { $domfilter=''; }
 5127:     my %libserv = &all_library();
 5128:     foreach my $tryserver (keys(%libserv)) {
 5129:         if ( (  $hostidflag == 1 
 5130: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5131: 	     || (!defined($hostidflag)) ) {
 5132: 
 5133: 	    if (($domfilter eq '') ||
 5134: 		(&host_domain($tryserver) eq $domfilter)) {
 5135:                 my $rep;
 5136:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5137:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5138:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5139:                                 &escape($descfilter), &escape($instcodefilter), 
 5140:                                 &escape($ownerfilter), &escape($coursefilter),
 5141:                                 &escape($typefilter), &escape($regexp_ok), 
 5142:                                 $as_hash, &escape($selfenrollonly), 
 5143:                                 &escape($catfilter), $showhidden, $caller, 
 5144:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5145:                                 &escape($createdbefore), &escape($createdafter), 
 5146:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5147:                                 $reqcrsdom,&escape($reqinstcode))));
 5148:                 } else {
 5149:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5150:                              $sincefilter.':'.&escape($descfilter).':'.
 5151:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5152:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5153:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5154:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5155:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5156:                              &escape($cc_clone).':'.$cloneonly.':'.
 5157:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5158:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5159:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5160:                 }
 5161:                      
 5162:                 my @pairs=split(/\&/,$rep);
 5163:                 foreach my $item (@pairs) {
 5164:                     my ($key,$value)=split(/\=/,$item,2);
 5165:                     $key = &unescape($key);
 5166:                     next if ($key =~ /^error: 2 /);
 5167:                     my $result = &thaw_unescape($value);
 5168:                     if (ref($result) eq 'HASH') {
 5169:                         $returnhash{$key}=$result;
 5170:                     } else {
 5171:                         my @responses = split(/:/,$value);
 5172:                         my @items = ('description','inst_code','owner','type');
 5173:                         for (my $i=0; $i<@responses; $i++) {
 5174:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5175:                         }
 5176:                     }
 5177:                 }
 5178:             }
 5179:         }
 5180:     }
 5181:     return %returnhash;
 5182: }
 5183: 
 5184: sub courselastaccess {
 5185:     my ($cdom,$cnum,$hostidref) = @_;
 5186:     my %returnhash;
 5187:     if ($cdom && $cnum) {
 5188:         my $chome = &homeserver($cnum,$cdom);
 5189:         if ($chome ne 'no_host') {
 5190:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5191:             &extract_lastaccess(\%returnhash,$rep);
 5192:         }
 5193:     } else {
 5194:         if (!$cdom) { $cdom=''; }
 5195:         my %libserv = &all_library();
 5196:         foreach my $tryserver (keys(%libserv)) {
 5197:             if (ref($hostidref) eq 'ARRAY') {
 5198:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5199:             } 
 5200:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5201:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5202:                 &extract_lastaccess(\%returnhash,$rep);
 5203:             }
 5204:         }
 5205:     }
 5206:     return %returnhash;
 5207: }
 5208: 
 5209: sub extract_lastaccess {
 5210:     my ($returnhash,$rep) = @_;
 5211:     if (ref($returnhash) eq 'HASH') {
 5212:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5213:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5214:                  $rep eq '') {
 5215:             my @pairs=split(/\&/,$rep);
 5216:             foreach my $item (@pairs) {
 5217:                 my ($key,$value)=split(/\=/,$item,2);
 5218:                 $key = &unescape($key);
 5219:                 next if ($key =~ /^error: 2 /);
 5220:                 $returnhash->{$key} = &thaw_unescape($value);
 5221:             }
 5222:         }
 5223:     }
 5224:     return;
 5225: }
 5226: 
 5227: # ---------------------------------------------------------- DC e-mail
 5228: 
 5229: sub dcmailput {
 5230:     my ($domain,$msgid,$message,$server)=@_;
 5231:     my $status = &Apache::lonnet::critical(
 5232:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5233:        &escape($message),$server);
 5234:     return $status;
 5235: }
 5236: 
 5237: sub dcmaildump {
 5238:     my ($dom,$startdate,$enddate,$senders) = @_;
 5239:     my %returnhash=();
 5240: 
 5241:     if (defined(&domain($dom,'primary'))) {
 5242:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5243:                                                          &escape($enddate).':';
 5244: 	my @esc_senders=map { &escape($_)} @$senders;
 5245: 	$cmd.=&escape(join('&',@esc_senders));
 5246: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5247:             my ($key,$value) = split(/\=/,$line,2);
 5248:             if (($key) && ($value)) {
 5249:                 $returnhash{&unescape($key)} = &unescape($value);
 5250:             }
 5251:         }
 5252:     }
 5253:     return %returnhash;
 5254: }
 5255: # ---------------------------------------------------------- Domain roles
 5256: 
 5257: sub get_domain_roles {
 5258:     my ($dom,$roles,$startdate,$enddate)=@_;
 5259:     if ((!defined($startdate)) || ($startdate eq '')) {
 5260:         $startdate = '.';
 5261:     }
 5262:     if ((!defined($enddate)) || ($enddate eq '')) {
 5263:         $enddate = '.';
 5264:     }
 5265:     my $rolelist;
 5266:     if (ref($roles) eq 'ARRAY') {
 5267:         $rolelist = join('&',@{$roles});
 5268:     }
 5269:     my %personnel = ();
 5270: 
 5271:     my %servers = &get_servers($dom,'library');
 5272:     foreach my $tryserver (keys(%servers)) {
 5273: 	%{$personnel{$tryserver}}=();
 5274: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5275: 					    &escape($startdate).':'.
 5276: 					    &escape($enddate).':'.
 5277: 					    &escape($rolelist), $tryserver))) {
 5278: 	    my ($key,$value) = split(/\=/,$line,2);
 5279: 	    if (($key) && ($value)) {
 5280: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5281: 	    }
 5282: 	}
 5283:     }
 5284:     return %personnel;
 5285: }
 5286: 
 5287: sub get_active_domroles {
 5288:     my ($dom,$roles) = @_;
 5289:     return () unless (ref($roles) eq 'ARRAY');
 5290:     my $now = time;
 5291:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5292:     my %domroles;
 5293:     foreach my $server (keys(%dompersonnel)) {
 5294:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5295:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5296:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5297:         }
 5298:     }
 5299:     return %domroles;
 5300: }
 5301: 
 5302: # ----------------------------------------------------------- Interval timing 
 5303: 
 5304: {
 5305: # Caches needed for speedup of navmaps
 5306: # We don't want to cache this for very long at all (5 seconds at most)
 5307: # 
 5308: # The user for whom we cache
 5309: my $cachedkey='';
 5310: # The cached times for this user
 5311: my %cachedtimes=();
 5312: # When this was last done
 5313: my $cachedtime='';
 5314: 
 5315: sub load_all_first_access {
 5316:     my ($uname,$udom,$ignorecache)=@_;
 5317:     if (($cachedkey eq $uname.':'.$udom) &&
 5318:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5319:         (!$ignorecache)) {
 5320:         return;
 5321:     }
 5322:     $cachedtime=time;
 5323:     $cachedkey=$uname.':'.$udom;
 5324:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5325: }
 5326: 
 5327: sub get_first_access {
 5328:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5329:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5330:     if ($argsymb) { $symb=$argsymb; }
 5331:     my ($map,$id,$res)=&decode_symb($symb);
 5332:     if ($argmap) { $map = $argmap; }
 5333:     if ($type eq 'course') {
 5334: 	$res='course';
 5335:     } elsif ($type eq 'map') {
 5336: 	$res=&symbread($map);
 5337:     } else {
 5338: 	$res=$symb;
 5339:     }
 5340:     &load_all_first_access($uname,$udom,$ignorecache);
 5341:     return $cachedtimes{"$courseid\0$res"};
 5342: }
 5343: 
 5344: sub set_first_access {
 5345:     my ($type,$interval)=@_;
 5346:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5347:     my ($map,$id,$res)=&decode_symb($symb);
 5348:     if ($type eq 'course') {
 5349: 	$res='course';
 5350:     } elsif ($type eq 'map') {
 5351: 	$res=&symbread($map);
 5352:     } else {
 5353: 	$res=$symb;
 5354:     }
 5355:     $cachedkey='';
 5356:     my $firstaccess=&get_first_access($type,$symb,$map);
 5357:     if ($firstaccess) {
 5358:         &logthis("First access time already set ($firstaccess) when attempting ".
 5359:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5360:                  "in $courseid");
 5361:         return 'already_set';
 5362:     } else {
 5363:         my $start = time;
 5364: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5365:                           $udom,$uname);
 5366:         if ($putres eq 'ok') {
 5367:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5368:                  $udom,$uname); 
 5369:             &appenv(
 5370:                      {
 5371:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5372:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5373:                      }
 5374:                   );
 5375:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5376:                 $cachedtimes{"$courseid\0$res"} = $start;
 5377:             }
 5378:         } elsif ($putres ne 'refused') {
 5379:             &logthis("Result: $putres when attempting to set first access time ".
 5380:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5381:         }
 5382:         return $putres;
 5383:     }
 5384:     return 'already_set';
 5385: }
 5386: }
 5387: 
 5388: # --------------------------------------------- Set Expire Date for Spreadsheet
 5389: 
 5390: sub expirespread {
 5391:     my ($uname,$udom,$stype,$usymb)=@_;
 5392:     my $cid=$env{'request.course.id'}; 
 5393:     if ($cid) {
 5394:        my $now=time;
 5395:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5396:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5397:                             $env{'course.'.$cid.'.num'}.
 5398: 	        	    ':nohist_expirationdates:'.
 5399:                             &escape($key).'='.$now,
 5400:                             $env{'course.'.$cid.'.home'})
 5401:     }
 5402:     return 'ok';
 5403: }
 5404: 
 5405: # ----------------------------------------------------- Devalidate Spreadsheets
 5406: 
 5407: sub devalidate {
 5408:     my ($symb,$uname,$udom)=@_;
 5409:     my $cid=$env{'request.course.id'}; 
 5410:     if ($cid) {
 5411:         # delete the stored spreadsheets for
 5412:         # - the student level sheet of this user in course's homespace
 5413:         # - the assessment level sheet for this resource 
 5414:         #   for this user in user's homespace
 5415: 	# - current conditional state info
 5416: 	my $key=$uname.':'.$udom.':';
 5417:         my $status=
 5418: 	    &del('nohist_calculatedsheets',
 5419: 		 [$key.'studentcalc:'],
 5420: 		 $env{'course.'.$cid.'.domain'},
 5421: 		 $env{'course.'.$cid.'.num'})
 5422: 		.' '.
 5423: 	    &del('nohist_calculatedsheets_'.$cid,
 5424: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5425:         unless ($status eq 'ok ok') {
 5426:            &logthis('Could not devalidate spreadsheet '.
 5427:                     $uname.' at '.$udom.' for '.
 5428: 		    $symb.': '.$status);
 5429:         }
 5430: 	&delenv('user.state.'.$cid);
 5431:     }
 5432: }
 5433: 
 5434: sub get_scalar {
 5435:     my ($string,$end) = @_;
 5436:     my $value;
 5437:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5438: 	$value = $1;
 5439:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5440: 	$value = $1;
 5441:     }
 5442:     return &unescape($value);
 5443: }
 5444: 
 5445: sub array2str {
 5446:   my (@array) = @_;
 5447:   my $result=&arrayref2str(\@array);
 5448:   $result=~s/^__ARRAY_REF__//;
 5449:   $result=~s/__END_ARRAY_REF__$//;
 5450:   return $result;
 5451: }
 5452: 
 5453: sub arrayref2str {
 5454:   my ($arrayref) = @_;
 5455:   my $result='__ARRAY_REF__';
 5456:   foreach my $elem (@$arrayref) {
 5457:     if(ref($elem) eq 'ARRAY') {
 5458:       $result.=&arrayref2str($elem).'&';
 5459:     } elsif(ref($elem) eq 'HASH') {
 5460:       $result.=&hashref2str($elem).'&';
 5461:     } elsif(ref($elem)) {
 5462:       #print("Got a ref of ".(ref($elem))." skipping.");
 5463:     } else {
 5464:       $result.=&escape($elem).'&';
 5465:     }
 5466:   }
 5467:   $result=~s/\&$//;
 5468:   $result .= '__END_ARRAY_REF__';
 5469:   return $result;
 5470: }
 5471: 
 5472: sub hash2str {
 5473:   my (%hash) = @_;
 5474:   my $result=&hashref2str(\%hash);
 5475:   $result=~s/^__HASH_REF__//;
 5476:   $result=~s/__END_HASH_REF__$//;
 5477:   return $result;
 5478: }
 5479: 
 5480: sub hashref2str {
 5481:   my ($hashref)=@_;
 5482:   my $result='__HASH_REF__';
 5483:   foreach my $key (sort(keys(%$hashref))) {
 5484:     if (ref($key) eq 'ARRAY') {
 5485:       $result.=&arrayref2str($key).'=';
 5486:     } elsif (ref($key) eq 'HASH') {
 5487:       $result.=&hashref2str($key).'=';
 5488:     } elsif (ref($key)) {
 5489:       $result.='=';
 5490:       #print("Got a ref of ".(ref($key))." skipping.");
 5491:     } else {
 5492: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5493:     }
 5494: 
 5495:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5496:       $result.=&arrayref2str($hashref->{$key}).'&';
 5497:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5498:       $result.=&hashref2str($hashref->{$key}).'&';
 5499:     } elsif(ref($hashref->{$key})) {
 5500:        $result.='&';
 5501:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5502:     } else {
 5503:       $result.=&escape($hashref->{$key}).'&';
 5504:     }
 5505:   }
 5506:   $result=~s/\&$//;
 5507:   $result .= '__END_HASH_REF__';
 5508:   return $result;
 5509: }
 5510: 
 5511: sub str2hash {
 5512:     my ($string)=@_;
 5513:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5514:     return %$hash;
 5515: }
 5516: 
 5517: sub str2hashref {
 5518:   my ($string) = @_;
 5519: 
 5520:   my %hash;
 5521: 
 5522:   if($string !~ /^__HASH_REF__/) {
 5523:       if (! ($string eq '' || !defined($string))) {
 5524: 	  $hash{'error'}='Not hash reference';
 5525:       }
 5526:       return (\%hash, $string);
 5527:   }
 5528: 
 5529:   $string =~ s/^__HASH_REF__//;
 5530: 
 5531:   while($string !~ /^__END_HASH_REF__/) {
 5532:       #key
 5533:       my $key='';
 5534:       if($string =~ /^__HASH_REF__/) {
 5535:           ($key, $string)=&str2hashref($string);
 5536:           if(defined($key->{'error'})) {
 5537:               $hash{'error'}='Bad data';
 5538:               return (\%hash, $string);
 5539:           }
 5540:       } elsif($string =~ /^__ARRAY_REF__/) {
 5541:           ($key, $string)=&str2arrayref($string);
 5542:           if($key->[0] eq 'Array reference error') {
 5543:               $hash{'error'}='Bad data';
 5544:               return (\%hash, $string);
 5545:           }
 5546:       } else {
 5547:           $string =~ s/^(.*?)=//;
 5548: 	  $key=&unescape($1);
 5549:       }
 5550:       $string =~ s/^=//;
 5551: 
 5552:       #value
 5553:       my $value='';
 5554:       if($string =~ /^__HASH_REF__/) {
 5555:           ($value, $string)=&str2hashref($string);
 5556:           if(defined($value->{'error'})) {
 5557:               $hash{'error'}='Bad data';
 5558:               return (\%hash, $string);
 5559:           }
 5560:       } elsif($string =~ /^__ARRAY_REF__/) {
 5561:           ($value, $string)=&str2arrayref($string);
 5562:           if($value->[0] eq 'Array reference error') {
 5563:               $hash{'error'}='Bad data';
 5564:               return (\%hash, $string);
 5565:           }
 5566:       } else {
 5567: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5568:       }
 5569:       $string =~ s/^&//;
 5570: 
 5571:       $hash{$key}=$value;
 5572:   }
 5573: 
 5574:   $string =~ s/^__END_HASH_REF__//;
 5575: 
 5576:   return (\%hash, $string);
 5577: }
 5578: 
 5579: sub str2array {
 5580:     my ($string)=@_;
 5581:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5582:     return @$array;
 5583: }
 5584: 
 5585: sub str2arrayref {
 5586:   my ($string) = @_;
 5587:   my @array;
 5588: 
 5589:   if($string !~ /^__ARRAY_REF__/) {
 5590:       if (! ($string eq '' || !defined($string))) {
 5591: 	  $array[0]='Array reference error';
 5592:       }
 5593:       return (\@array, $string);
 5594:   }
 5595: 
 5596:   $string =~ s/^__ARRAY_REF__//;
 5597: 
 5598:   while($string !~ /^__END_ARRAY_REF__/) {
 5599:       my $value='';
 5600:       if($string =~ /^__HASH_REF__/) {
 5601:           ($value, $string)=&str2hashref($string);
 5602:           if(defined($value->{'error'})) {
 5603:               $array[0] ='Array reference error';
 5604:               return (\@array, $string);
 5605:           }
 5606:       } elsif($string =~ /^__ARRAY_REF__/) {
 5607:           ($value, $string)=&str2arrayref($string);
 5608:           if($value->[0] eq 'Array reference error') {
 5609:               $array[0] ='Array reference error';
 5610:               return (\@array, $string);
 5611:           }
 5612:       } else {
 5613: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5614:       }
 5615:       $string =~ s/^&//;
 5616: 
 5617:       push(@array, $value);
 5618:   }
 5619: 
 5620:   $string =~ s/^__END_ARRAY_REF__//;
 5621: 
 5622:   return (\@array, $string);
 5623: }
 5624: 
 5625: # -------------------------------------------------------------------Temp Store
 5626: 
 5627: sub tmpreset {
 5628:   my ($symb,$namespace,$domain,$stuname) = @_;
 5629:   if (!$symb) {
 5630:     $symb=&symbread();
 5631:     if (!$symb) { $symb= $env{'request.url'}; }
 5632:   }
 5633:   $symb=escape($symb);
 5634: 
 5635:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5636:   $namespace=~s/\//\_/g;
 5637:   $namespace=~s/\W//g;
 5638: 
 5639:   if (!$domain) { $domain=$env{'user.domain'}; }
 5640:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5641:   if ($domain eq 'public' && $stuname eq 'public') {
 5642:       $stuname=$ENV{'REMOTE_ADDR'};
 5643:   }
 5644:   my $path=LONCAPA::tempdir();
 5645:   my %hash;
 5646:   if (tie(%hash,'GDBM_File',
 5647: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5648: 	  &GDBM_WRCREAT(),0640)) {
 5649:     foreach my $key (keys(%hash)) {
 5650:       if ($key=~ /:$symb/) {
 5651: 	delete($hash{$key});
 5652:       }
 5653:     }
 5654:   }
 5655: }
 5656: 
 5657: sub tmpstore {
 5658:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5659: 
 5660:   if (!$symb) {
 5661:     $symb=&symbread();
 5662:     if (!$symb) { $symb= $env{'request.url'}; }
 5663:   }
 5664:   $symb=escape($symb);
 5665: 
 5666:   if (!$namespace) {
 5667:     # I don't think we would ever want to store this for a course.
 5668:     # it seems this will only be used if we don't have a course.
 5669:     #$namespace=$env{'request.course.id'};
 5670:     #if (!$namespace) {
 5671:       $namespace=$env{'request.state'};
 5672:     #}
 5673:   }
 5674:   $namespace=~s/\//\_/g;
 5675:   $namespace=~s/\W//g;
 5676:   if (!$domain) { $domain=$env{'user.domain'}; }
 5677:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5678:   if ($domain eq 'public' && $stuname eq 'public') {
 5679:       $stuname=$ENV{'REMOTE_ADDR'};
 5680:   }
 5681:   my $now=time;
 5682:   my %hash;
 5683:   my $path=LONCAPA::tempdir();
 5684:   if (tie(%hash,'GDBM_File',
 5685: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5686: 	  &GDBM_WRCREAT(),0640)) {
 5687:     $hash{"version:$symb"}++;
 5688:     my $version=$hash{"version:$symb"};
 5689:     my $allkeys=''; 
 5690:     foreach my $key (keys(%$storehash)) {
 5691:       $allkeys.=$key.':';
 5692:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5693:     }
 5694:     $hash{"$version:$symb:timestamp"}=$now;
 5695:     $allkeys.='timestamp';
 5696:     $hash{"$version:keys:$symb"}=$allkeys;
 5697:     if (untie(%hash)) {
 5698:       return 'ok';
 5699:     } else {
 5700:       return "error:$!";
 5701:     }
 5702:   } else {
 5703:     return "error:$!";
 5704:   }
 5705: }
 5706: 
 5707: # -----------------------------------------------------------------Temp Restore
 5708: 
 5709: sub tmprestore {
 5710:   my ($symb,$namespace,$domain,$stuname) = @_;
 5711: 
 5712:   if (!$symb) {
 5713:     $symb=&symbread();
 5714:     if (!$symb) { $symb= $env{'request.url'}; }
 5715:   }
 5716:   $symb=escape($symb);
 5717: 
 5718:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5719: 
 5720:   if (!$domain) { $domain=$env{'user.domain'}; }
 5721:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5722:   if ($domain eq 'public' && $stuname eq 'public') {
 5723:       $stuname=$ENV{'REMOTE_ADDR'};
 5724:   }
 5725:   my %returnhash;
 5726:   $namespace=~s/\//\_/g;
 5727:   $namespace=~s/\W//g;
 5728:   my %hash;
 5729:   my $path=LONCAPA::tempdir();
 5730:   if (tie(%hash,'GDBM_File',
 5731: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5732: 	  &GDBM_READER(),0640)) {
 5733:     my $version=$hash{"version:$symb"};
 5734:     $returnhash{'version'}=$version;
 5735:     my $scope;
 5736:     for ($scope=1;$scope<=$version;$scope++) {
 5737:       my $vkeys=$hash{"$scope:keys:$symb"};
 5738:       my @keys=split(/:/,$vkeys);
 5739:       my $key;
 5740:       $returnhash{"$scope:keys"}=$vkeys;
 5741:       foreach $key (@keys) {
 5742: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5743: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5744:       }
 5745:     }
 5746:     if (!(untie(%hash))) {
 5747:       return "error:$!";
 5748:     }
 5749:   } else {
 5750:     return "error:$!";
 5751:   }
 5752:   return %returnhash;
 5753: }
 5754: 
 5755: # ----------------------------------------------------------------------- Store
 5756: 
 5757: sub store {
 5758:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5759:     my $home='';
 5760: 
 5761:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5762: 
 5763:     $symb=&symbclean($symb);
 5764:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5765: 
 5766:     if (!$domain) { $domain=$env{'user.domain'}; }
 5767:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5768: 
 5769:     &devalidate($symb,$stuname,$domain);
 5770: 
 5771:     $symb=escape($symb);
 5772:     if (!$namespace) { 
 5773:        unless ($namespace=$env{'request.course.id'}) { 
 5774:           return ''; 
 5775:        } 
 5776:     }
 5777:     if (!$home) { $home=$env{'user.home'}; }
 5778: 
 5779:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5780:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5781: 
 5782:     my $namevalue='';
 5783:     foreach my $key (keys(%$storehash)) {
 5784:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5785:     }
 5786:     $namevalue=~s/\&$//;
 5787:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5788:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5789: }
 5790: 
 5791: # -------------------------------------------------------------- Critical Store
 5792: 
 5793: sub cstore {
 5794:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5795:     my $home='';
 5796: 
 5797:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5798: 
 5799:     $symb=&symbclean($symb);
 5800:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5801: 
 5802:     if (!$domain) { $domain=$env{'user.domain'}; }
 5803:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5804: 
 5805:     &devalidate($symb,$stuname,$domain);
 5806: 
 5807:     $symb=escape($symb);
 5808:     if (!$namespace) { 
 5809:        unless ($namespace=$env{'request.course.id'}) { 
 5810:           return ''; 
 5811:        } 
 5812:     }
 5813:     if (!$home) { $home=$env{'user.home'}; }
 5814: 
 5815:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5816:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5817: 
 5818:     my $namevalue='';
 5819:     foreach my $key (keys(%$storehash)) {
 5820:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5821:     }
 5822:     $namevalue=~s/\&$//;
 5823:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5824:     return critical
 5825:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5826: }
 5827: 
 5828: # --------------------------------------------------------------------- Restore
 5829: 
 5830: sub restore {
 5831:     my ($symb,$namespace,$domain,$stuname) = @_;
 5832:     my $home='';
 5833: 
 5834:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5835: 
 5836:     if (!$symb) {
 5837:         return if ($namespace eq 'courserequests');
 5838:         unless ($symb=escape(&symbread())) { return ''; }
 5839:     } else {
 5840:         unless ($namespace eq 'courserequests') {
 5841:             $symb=&escape(&symbclean($symb));
 5842:         }
 5843:     }
 5844:     if (!$namespace) { 
 5845:        unless ($namespace=$env{'request.course.id'}) { 
 5846:           return ''; 
 5847:        } 
 5848:     }
 5849:     if (!$domain) { $domain=$env{'user.domain'}; }
 5850:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5851:     if (!$home) { $home=$env{'user.home'}; }
 5852:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5853: 
 5854:     my %returnhash=();
 5855:     foreach my $line (split(/\&/,$answer)) {
 5856: 	my ($name,$value)=split(/\=/,$line);
 5857:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5858:     }
 5859:     my $version;
 5860:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5861:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5862:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5863:        }
 5864:     }
 5865:     return %returnhash;
 5866: }
 5867: 
 5868: # ---------------------------------------------------------- Course Description
 5869: #
 5870: #  
 5871: 
 5872: sub coursedescription {
 5873:     my ($courseid,$args)=@_;
 5874:     $courseid=~s/^\///;
 5875:     $courseid=~s/\_/\//g;
 5876:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5877:     my $chome=&homeserver($cnum,$cdomain);
 5878:     my $normalid=$cdomain.'_'.$cnum;
 5879:     # need to always cache even if we get errors otherwise we keep 
 5880:     # trying and trying and trying to get the course description.
 5881:     my %envhash=();
 5882:     my %returnhash=();
 5883:     
 5884:     my $expiretime=600;
 5885:     if ($env{'request.course.id'} eq $normalid) {
 5886: 	$expiretime=120;
 5887:     }
 5888: 
 5889:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5890:     if (!$args->{'freshen_cache'}
 5891: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5892: 	foreach my $key (keys(%env)) {
 5893: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5894: 	    my ($setting) = $1;
 5895: 	    $returnhash{$setting} = $env{$key};
 5896: 	}
 5897: 	return %returnhash;
 5898:     }
 5899: 
 5900:     # get the data again
 5901: 
 5902:     if (!$args->{'one_time'}) {
 5903: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5904:     }
 5905: 
 5906:     if ($chome ne 'no_host') {
 5907:        %returnhash=&dump('environment',$cdomain,$cnum);
 5908:        if (!exists($returnhash{'con_lost'})) {
 5909: 	   my $username = $env{'user.name'}; # Defult username
 5910: 	   if(defined $args->{'user'}) {
 5911: 	       $username = $args->{'user'};
 5912: 	   }
 5913:            $returnhash{'home'}= $chome;
 5914: 	   $returnhash{'domain'} = $cdomain;
 5915: 	   $returnhash{'num'} = $cnum;
 5916:            if (!defined($returnhash{'type'})) {
 5917:                $returnhash{'type'} = 'Course';
 5918:            }
 5919:            while (my ($name,$value) = each %returnhash) {
 5920:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5921:            }
 5922:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5923:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5924: 	       $username.'_'.$cdomain.'_'.$cnum;
 5925:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5926:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5927:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5928:        }
 5929:     }
 5930:     if (!$args->{'one_time'}) {
 5931: 	&appenv(\%envhash);
 5932:     }
 5933:     return %returnhash;
 5934: }
 5935: 
 5936: sub update_released_required {
 5937:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5938:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5939:         $cid = $env{'request.course.id'};
 5940:         $cdom = $env{'course.'.$cid.'.domain'};
 5941:         $cnum = $env{'course.'.$cid.'.num'};
 5942:         $chome = $env{'course.'.$cid.'.home'};
 5943:     }
 5944:     if ($needsrelease) {
 5945:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5946:         my $needsupdate;
 5947:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5948:             $needsupdate = 1;
 5949:         } else {
 5950:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5951:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5952:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5953:                 $needsupdate = 1;
 5954:             }
 5955:         }
 5956:         if ($needsupdate) {
 5957:             my %needshash = (
 5958:                              'internal.releaserequired' => $needsrelease,
 5959:                             );
 5960:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5961:             if ($putresult eq 'ok') {
 5962:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5963:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5964:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5965:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5966:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5967:                 }
 5968:             }
 5969:         }
 5970:     }
 5971:     return;
 5972: }
 5973: 
 5974: # -------------------------------------------------See if a user is privileged
 5975: 
 5976: sub privileged {
 5977:     my ($username,$domain,$possdomains,$possroles)=@_;
 5978:     my $now = time;
 5979:     my $roles;
 5980:     if (ref($possroles) eq 'ARRAY') {
 5981:         $roles = $possroles; 
 5982:     } else {
 5983:         $roles = ['dc','su'];
 5984:     }
 5985:     if (ref($possdomains) eq 'ARRAY') {
 5986:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5987:         foreach my $dom (@{$possdomains}) {
 5988:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5989:                 (ref($privileged{$dom}) eq 'HASH')) {
 5990:                 foreach my $role (@{$roles}) {
 5991:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5992:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5993:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5994:                             return 1 unless (($end && $end < $now) ||
 5995:                                              ($start && $start > $now));
 5996:                         }
 5997:                     }
 5998:                 }
 5999:             }
 6000:         }
 6001:     } else {
 6002:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6003:         my $now = time;
 6004: 
 6005:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6006:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6007:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6008:                 return 1 unless ($tend && $tend < $now) 
 6009:                         or ($tstart && $tstart > $now);
 6010:             }
 6011:         }
 6012:     }
 6013:     return 0;
 6014: }
 6015: 
 6016: sub privileged_by_domain {
 6017:     my ($domains,$roles) = @_;
 6018:     my %privileged = ();
 6019:     my $cachetime = 60*60*24;
 6020:     my $now = time;
 6021:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6022:         return %privileged;
 6023:     }
 6024:     foreach my $dom (@{$domains}) {
 6025:         next if (ref($privileged{$dom}) eq 'HASH');
 6026:         my $needroles;
 6027:         foreach my $role (@{$roles}) {
 6028:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6029:             if (defined($cached)) {
 6030:                 if (ref($result) eq 'HASH') {
 6031:                     $privileged{$dom}{$role} = $result;
 6032:                 }
 6033:             } else {
 6034:                 $needroles = 1;
 6035:             }
 6036:         }
 6037:         if ($needroles) {
 6038:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6039:             $privileged{$dom} = {};
 6040:             foreach my $server (keys(%dompersonnel)) {
 6041:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6042:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6043:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6044:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6045:                         next if ($end && $end < $now);
 6046:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6047:                             $dompersonnel{$server}{$item};
 6048:                     }
 6049:                 }
 6050:             }
 6051:             if (ref($privileged{$dom}) eq 'HASH') {
 6052:                 foreach my $role (@{$roles}) {
 6053:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6054:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6055:                     } else {
 6056:                         my %hash = ();
 6057:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6058:                     }
 6059:                 }
 6060:             }
 6061:         }
 6062:     }
 6063:     return %privileged;
 6064: }
 6065: 
 6066: # -------------------------------------------------------- Get user privileges
 6067: 
 6068: sub rolesinit {
 6069:     my ($domain, $username) = @_;
 6070:     my %userroles = ('user.login.time' => time);
 6071:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6072: 
 6073:     # firstaccess and timerinterval are related to timed maps/resources. 
 6074:     # also, blocking can be triggered by an activating timer
 6075:     # it's saved in the user's %env.
 6076:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6077:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6078:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6079:         %timerintchk, %timerintenv);
 6080: 
 6081:     foreach my $key (keys(%firstaccess)) {
 6082:         my ($cid, $rest) = split(/\0/, $key);
 6083:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6084:     }
 6085: 
 6086:     foreach my $key (keys(%timerinterval)) {
 6087:         my ($cid,$rest) = split(/\0/,$key);
 6088:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6089:     }
 6090: 
 6091:     my %allroles=();
 6092:     my %allgroups=();
 6093: 
 6094:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6095:         my $role = $rolesdump{$area};
 6096:         $area =~ s/\_\w\w$//;
 6097: 
 6098:         my ($trole, $tend, $tstart, $group_privs);
 6099: 
 6100:         if ($role =~ /^cr/) {
 6101:         # Custom role, defined by a user 
 6102:         # e.g., user.role.cr/msu/smith/mynewrole
 6103:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6104:                 $trole = $1;
 6105:                 ($tend, $tstart) = split('_', $2);
 6106:             } else {
 6107:                 $trole = $role;
 6108:             }
 6109:         } elsif ($role =~ m|^gr/|) {
 6110:         # Role of member in a group, defined within a course/community
 6111:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6112:             ($trole, $tend, $tstart) = split(/_/, $role);
 6113:             next if $tstart eq '-1';
 6114:             ($trole, $group_privs) = split(/\//, $trole);
 6115:             $group_privs = &unescape($group_privs);
 6116:         } else {
 6117:         # Just a normal role, defined in roles.tab
 6118:             ($trole, $tend, $tstart) = split(/_/,$role);
 6119:         }
 6120: 
 6121:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6122:                  $username);
 6123:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6124: 
 6125:         # role expired or not available yet?
 6126:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6127:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6128: 
 6129:         next if $area eq '' or $trole eq '';
 6130: 
 6131:         my $spec = "$trole.$area";
 6132:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6133: 
 6134:         if ($trole =~ /^cr\//) {
 6135:         # Custom role, defined by a user
 6136:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6137:         } elsif ($trole eq 'gr') {
 6138:         # Role of a member in a group, defined within a course/community
 6139:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6140:             next;
 6141:         } else {
 6142:         # Normal role, defined in roles.tab
 6143:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6144:         }
 6145: 
 6146:         my $cid = $tdomain.'_'.$trest;
 6147:         unless ($firstaccchk{$cid}) {
 6148:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6149:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6150:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6151:                         $coursetimerstarts{$cid}{$item}; 
 6152:                 }
 6153:             }
 6154:             $firstaccchk{$cid} = 1;
 6155:         }
 6156:         unless ($timerintchk{$cid}) {
 6157:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6158:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6159:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6160:                        $coursetimerintervals{$cid}{$item};
 6161:                 }
 6162:             }
 6163:             $timerintchk{$cid} = 1;
 6164:         }
 6165:     }
 6166: 
 6167:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6168:                                                           \%allroles, \%allgroups);
 6169:     $env{'user.adv'} = $userroles{'user.adv'};
 6170:     $env{'user.rar'} = $userroles{'user.rar'};
 6171: 
 6172:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6173: }
 6174: 
 6175: sub set_arearole {
 6176:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6177:     unless ($nolog) {
 6178: # log the associated role with the area
 6179:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6180:     }
 6181:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6182: }
 6183: 
 6184: sub custom_roleprivs {
 6185:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6186:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6187:     my $homsvr = &homeserver($rauthor,$rdomain);
 6188:     if (&hostname($homsvr) ne '') {
 6189:         my ($rdummy,$roledef)=
 6190:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6191:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6192:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6193:             if (defined($syspriv)) {
 6194:                 if ($trest =~ /^$match_community$/) {
 6195:                     $syspriv =~ s/bre\&S//; 
 6196:                 }
 6197:                 $$allroles{'cm./'}.=':'.$syspriv;
 6198:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6199:             }
 6200:             if ($tdomain ne '') {
 6201:                 if (defined($dompriv)) {
 6202:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6203:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6204:                 }
 6205:                 if (($trest ne '') && (defined($coursepriv))) {
 6206:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6207:                         my $rolename = $1;
 6208:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6209:                     }
 6210:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6211:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6212:                 }
 6213:             }
 6214:         }
 6215:     }
 6216: }
 6217: 
 6218: sub course_adhocrole_privs {
 6219:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6220:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6221:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6222:         my (%currprivs,%storeprivs);
 6223:         foreach my $item (split(/:/,$coursepriv)) {
 6224:             my ($priv,$restrict) = split(/\&/,$item);
 6225:             $currprivs{$priv} = $restrict;
 6226:         }
 6227:         my (%possadd,%possremove,%full);
 6228:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6229:             my ($priv,$restrict)=split(/\&/,$item);
 6230:             $full{$priv} = $restrict;
 6231:         }
 6232:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6233:              next if ($item eq '');
 6234:              my ($rule,$rest) = split(/=/,$item);
 6235:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6236:              foreach my $priv (split(/:/,$rest)) {
 6237:                  if ($priv ne '') {
 6238:                      if ($rule eq 'off') {
 6239:                          $possremove{$priv} = 1;
 6240:                      } else {
 6241:                          $possadd{$priv} = 1;
 6242:                      }
 6243:                  }
 6244:              }
 6245:          }
 6246:          foreach my $priv (sort(keys(%full))) {
 6247:              if (exists($currprivs{$priv})) {
 6248:                  unless (exists($possremove{$priv})) {
 6249:                      $storeprivs{$priv} = $currprivs{$priv};
 6250:                  }
 6251:              } elsif (exists($possadd{$priv})) {
 6252:                  $storeprivs{$priv} = $full{$priv};
 6253:              }
 6254:          }
 6255:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6256:      }
 6257:      return $coursepriv;
 6258: }
 6259: 
 6260: sub group_roleprivs {
 6261:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6262:     my $access = 1;
 6263:     my $now = time;
 6264:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6265:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6266:     if ($access) {
 6267:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6268:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6269:     }
 6270: }
 6271: 
 6272: sub standard_roleprivs {
 6273:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6274:     if (defined($pr{$trole.':s'})) {
 6275:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6276:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6277:     }
 6278:     if ($tdomain ne '') {
 6279:         if (defined($pr{$trole.':d'})) {
 6280:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6281:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6282:         }
 6283:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6284:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6285:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6286:         }
 6287:     }
 6288: }
 6289: 
 6290: sub set_userprivs {
 6291:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6292:     my $author=0;
 6293:     my $adv=0;
 6294:     my $rar=0;
 6295:     my %grouproles = ();
 6296:     if (keys(%{$allgroups}) > 0) {
 6297:         my @groupkeys; 
 6298:         foreach my $role (keys(%{$allroles})) {
 6299:             push(@groupkeys,$role);
 6300:         }
 6301:         if (ref($groups_roles) eq 'HASH') {
 6302:             foreach my $key (keys(%{$groups_roles})) {
 6303:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6304:                     push(@groupkeys,$key);
 6305:                 }
 6306:             }
 6307:         }
 6308:         if (@groupkeys > 0) {
 6309:             foreach my $role (@groupkeys) {
 6310:                 my ($trole,$area,$sec,$extendedarea);
 6311:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6312:                     $trole = $1;
 6313:                     $area = $2;
 6314:                     $sec = $3;
 6315:                     $extendedarea = $area.$sec;
 6316:                     if (exists($$allgroups{$area})) {
 6317:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6318:                             my $spec = $trole.'.'.$extendedarea;
 6319:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6320:                                                 $$allgroups{$area}{$group};
 6321:                         }
 6322:                     }
 6323:                 }
 6324:             }
 6325:         }
 6326:     }
 6327:     foreach my $group (keys(%grouproles)) {
 6328:         $$allroles{$group} = $grouproles{$group};
 6329:     }
 6330:     foreach my $role (keys(%{$allroles})) {
 6331:         my %thesepriv;
 6332:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6333:         foreach my $item (split(/:/,$$allroles{$role})) {
 6334:             if ($item ne '') {
 6335:                 my ($privilege,$restrictions)=split(/&/,$item);
 6336:                 if ($restrictions eq '') {
 6337:                     $thesepriv{$privilege}='F';
 6338:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6339:                     $thesepriv{$privilege}.=$restrictions;
 6340:                 }
 6341:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6342:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6343:             }
 6344:         }
 6345:         my $thesestr='';
 6346:         foreach my $priv (sort(keys(%thesepriv))) {
 6347: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6348: 	}
 6349:         $userroles->{'user.priv.'.$role} = $thesestr;
 6350:     }
 6351:     return ($author,$adv,$rar);
 6352: }
 6353: 
 6354: sub role_status {
 6355:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6356:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6357:         my ($one,$two) = split(m{\./},$rolekey,2);
 6358:         (undef,undef,$$role) = split(/\./,$one,3);
 6359:         unless (!defined($$role) || $$role eq '') {
 6360:             $$where = '/'.$two;
 6361:             $$trolecode=$$role.'.'.$$where;
 6362:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6363:             $$tstatus='is';
 6364:             if ($$tstart && $$tstart>$update) {
 6365:                 $$tstatus='future';
 6366:                 if ($$tstart<$now) {
 6367:                     if ($$tstart && $$tstart>$refresh) {
 6368:                         if (($$where ne '') && ($$role ne '')) {
 6369:                             my (%allroles,%allgroups,$group_privs,
 6370:                                 %groups_roles,@rolecodes);
 6371:                             my %userroles = (
 6372:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6373:                             );
 6374:                             @rolecodes = ('cm'); 
 6375:                             my $spec=$$role.'.'.$$where;
 6376:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6377:                             if ($$role =~ /^cr\//) {
 6378:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6379:                                 push(@rolecodes,'cr');
 6380:                             } elsif ($$role eq 'gr') {
 6381:                                 push(@rolecodes,$$role);
 6382:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6383:                                                     $env{'user.name'});
 6384:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6385:                                 (undef,my $group_privs) = split(/\//,$trole);
 6386:                                 $group_privs = &unescape($group_privs);
 6387:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6388:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6389:                                 &get_groups_roles($tdomain,$trest,
 6390:                                                   \%course_roles,\@rolecodes,
 6391:                                                   \%groups_roles);
 6392:                             } else {
 6393:                                 push(@rolecodes,$$role);
 6394:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6395:                             }
 6396:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6397:                                                                    \%groups_roles);
 6398:                             &appenv(\%userroles,\@rolecodes);
 6399:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6400:                         }
 6401:                     }
 6402:                     $$tstatus = 'is';
 6403:                 }
 6404:             }
 6405:             if ($$tend) {
 6406:                 if ($$tend<$update) {
 6407:                     $$tstatus='expired';
 6408:                 } elsif ($$tend<$now) {
 6409:                     $$tstatus='will_not';
 6410:                 }
 6411:             }
 6412:         }
 6413:     }
 6414: }
 6415: 
 6416: sub get_groups_roles {
 6417:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6418:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6419:                   (ref($rolecodes) eq 'ARRAY') && 
 6420:                   (ref($groups_roles) eq 'HASH')); 
 6421:     if (keys(%{$cdom_courseroles}) > 0) {
 6422:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6423:         if ($cdom ne '' && $cnum ne '') {
 6424:             foreach my $key (keys(%{$cdom_courseroles})) {
 6425:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6426:                     my $crsrole = $1;
 6427:                     my $crssec = $2;
 6428:                     if ($crsrole =~ /^cr/) {
 6429:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6430:                             push(@{$rolecodes},'cr');
 6431:                         }
 6432:                     } else {
 6433:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6434:                             push(@{$rolecodes},$crsrole);
 6435:                         }
 6436:                     }
 6437:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6438:                     if ($crssec ne '') {
 6439:                         $rolekey .= "/$crssec";
 6440:                     }
 6441:                     $rolekey .= './';
 6442:                     $groups_roles->{$rolekey} = $rolecodes;
 6443:                 }
 6444:             }
 6445:         }
 6446:     }
 6447:     return;
 6448: }
 6449: 
 6450: sub delete_env_groupprivs {
 6451:     my ($where,$courseroles,$possroles) = @_;
 6452:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6453:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6454:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6455:         %{$courseroles->{$udom}} =
 6456:             &get_my_roles('','','userroles',['active'],
 6457:                           $possroles,[$udom],1);
 6458:     }
 6459:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6460:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6461:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6462:             my $area = '/'.$cdom.'/'.$cnum;
 6463:             my $privkey = "user.priv.$crsrole.$area";
 6464:             if ($crssec ne '') {
 6465:                 $privkey .= '/'.$crssec;
 6466:             }
 6467:             $privkey .= ".$area/$group";
 6468:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6469:         }
 6470:     }
 6471:     return;
 6472: }
 6473: 
 6474: sub check_adhoc_privs {
 6475:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6476:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6477:     if ($sec) {
 6478:         $cckey .= '/'.$sec;
 6479:     } 
 6480:     my $setprivs;
 6481:     if ($env{$cckey}) {
 6482:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6483:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6484:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6485:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6486:             $setprivs = 1;
 6487:         }
 6488:     } else {
 6489:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6490:         $setprivs = 1;
 6491:     }
 6492:     return $setprivs;
 6493: }
 6494: 
 6495: sub set_adhoc_privileges {
 6496: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6497:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6498:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6499:     if ($sec ne '') {
 6500:         $area .= '/'.$sec;
 6501:     }
 6502:     my $spec = $role.'.'.$area;
 6503:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6504:                                   $env{'user.name'},1);
 6505:     my %rolehash = ();
 6506:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6507:         my $rolename = $1;
 6508:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6509:         my %domdef = &get_domain_defaults($dcdom);
 6510:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6511:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6512:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6513:             }
 6514:         }
 6515:     } else {
 6516:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6517:     }
 6518:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6519:     &appenv(\%userroles,[$role,'cm']);
 6520:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6521:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6522:         &appenv( {'request.role'        => $spec,
 6523:                   'request.role.domain' => $dcdom,
 6524:                   'request.course.sec'  => $sec,
 6525:                  }
 6526:                );
 6527:         my $tadv=0;
 6528:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6529:         &appenv({'request.role.adv'    => $tadv});
 6530:     }
 6531: }
 6532: 
 6533: # --------------------------------------------------------------- get interface
 6534: 
 6535: sub get {
 6536:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6537:    my $items='';
 6538:    foreach my $item (@$storearr) {
 6539:        $items.=&escape($item).'&';
 6540:    }
 6541:    $items=~s/\&$//;
 6542:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6543:    if (!$uname) { $uname=$env{'user.name'}; }
 6544:    my $uhome=&homeserver($uname,$udomain);
 6545: 
 6546:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6547:    my @pairs=split(/\&/,$rep);
 6548:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6549:      return @pairs;
 6550:    }
 6551:    my %returnhash=();
 6552:    my $i=0;
 6553:    foreach my $item (@$storearr) {
 6554:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6555:       $i++;
 6556:    }
 6557:    return %returnhash;
 6558: }
 6559: 
 6560: # --------------------------------------------------------------- del interface
 6561: 
 6562: sub del {
 6563:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6564:    my $items='';
 6565:    foreach my $item (@$storearr) {
 6566:        $items.=&escape($item).'&';
 6567:    }
 6568: 
 6569:    $items=~s/\&$//;
 6570:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6571:    if (!$uname) { $uname=$env{'user.name'}; }
 6572:    my $uhome=&homeserver($uname,$udomain);
 6573:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6574: }
 6575: 
 6576: # -------------------------------------------------------------- dump interface
 6577: 
 6578: sub unserialize {
 6579:     my ($rep, $escapedkeys) = @_;
 6580: 
 6581:     return {} if $rep =~ /^error/;
 6582: 
 6583:     my %returnhash=();
 6584: 	foreach my $item (split(/\&/,$rep)) {
 6585: 	    my ($key, $value) = split(/=/, $item, 2);
 6586: 	    $key = unescape($key) unless $escapedkeys;
 6587: 	    next if $key =~ /^error: 2 /;
 6588: 	    $returnhash{$key} = &thaw_unescape($value);
 6589: 	}
 6590:     #return %returnhash;
 6591:     return \%returnhash;
 6592: }        
 6593: 
 6594: # see Lond::dump_with_regexp
 6595: # if $escapedkeys hash keys won't get unescaped.
 6596: sub dump {
 6597:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6598:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6599:     if (!$uname) { $uname=$env{'user.name'}; }
 6600:     my $uhome=&homeserver($uname,$udomain);
 6601: 
 6602:     if ($regexp) {
 6603:         $regexp=&escape($regexp);
 6604:     } else {
 6605:         $regexp='.';
 6606:     }
 6607:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6608:         # user is hosted on this machine
 6609:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6610:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6611:         return %{unserialize($reply, $escapedkeys)};
 6612:     }
 6613:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6614:     my @pairs=split(/\&/,$rep);
 6615:     my %returnhash=();
 6616:     if (!($rep =~ /^error/ )) {
 6617: 	foreach my $item (@pairs) {
 6618: 	    my ($key,$value)=split(/=/,$item,2);
 6619:         $key = unescape($key) unless $escapedkeys;
 6620:         #$key = &unescape($key);
 6621: 	    next if ($key =~ /^error: 2 /);
 6622: 	    $returnhash{$key}=&thaw_unescape($value);
 6623: 	}
 6624:     }
 6625:     return %returnhash;
 6626: }
 6627: 
 6628: 
 6629: # --------------------------------------------------------- dumpstore interface
 6630: 
 6631: sub dumpstore {
 6632:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6633:    # same as dump but keys must be escaped. They may contain colon separated
 6634:    # lists of values that may themself contain colons (e.g. symbs).
 6635:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6636: }
 6637: 
 6638: # -------------------------------------------------------------- keys interface
 6639: 
 6640: sub getkeys {
 6641:    my ($namespace,$udomain,$uname)=@_;
 6642:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6643:    if (!$uname) { $uname=$env{'user.name'}; }
 6644:    my $uhome=&homeserver($uname,$udomain);
 6645:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6646:    my @keyarray=();
 6647:    foreach my $key (split(/\&/,$rep)) {
 6648:       next if ($key =~ /^error: 2 /);
 6649:       push(@keyarray,&unescape($key));
 6650:    }
 6651:    return @keyarray;
 6652: }
 6653: 
 6654: # --------------------------------------------------------------- currentdump
 6655: sub currentdump {
 6656:    my ($courseid,$sdom,$sname)=@_;
 6657:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6658:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6659:    $sname    = $env{'user.name'}         if (! defined($sname));
 6660:    my $uhome = &homeserver($sname,$sdom);
 6661:    my $rep;
 6662: 
 6663:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6664:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6665:                    $courseid)));
 6666:    } else {
 6667:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6668:    }
 6669: 
 6670:    return if ($rep =~ /^(error:|no_such_host)/);
 6671:    #
 6672:    my %returnhash=();
 6673:    #
 6674:    if ($rep eq 'unknown_cmd') {
 6675:        # an old lond will not know currentdump
 6676:        # Do a dump and make it look like a currentdump
 6677:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6678:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6679:        my %hash = @tmp;
 6680:        @tmp=();
 6681:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6682:    } else {
 6683:        my @pairs=split(/\&/,$rep);
 6684:        foreach my $pair (@pairs) {
 6685:            my ($key,$value)=split(/=/,$pair,2);
 6686:            my ($symb,$param) = split(/:/,$key);
 6687:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6688:                                                         &thaw_unescape($value);
 6689:        }
 6690:    }
 6691:    return %returnhash;
 6692: }
 6693: 
 6694: sub convert_dump_to_currentdump{
 6695:     my %hash = %{shift()};
 6696:     my %returnhash;
 6697:     # Code ripped from lond, essentially.  The only difference
 6698:     # here is the unescaping done by lonnet::dump().  Conceivably
 6699:     # we might run in to problems with parameter names =~ /^v\./
 6700:     while (my ($key,$value) = each(%hash)) {
 6701:         my ($v,$symb,$param) = split(/:/,$key);
 6702: 	$symb  = &unescape($symb);
 6703: 	$param = &unescape($param);
 6704:         next if ($v eq 'version' || $symb eq 'keys');
 6705:         next if (exists($returnhash{$symb}) &&
 6706:                  exists($returnhash{$symb}->{$param}) &&
 6707:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6708:         $returnhash{$symb}->{$param}=$value;
 6709:         $returnhash{$symb}->{'v.'.$param}=$v;
 6710:     }
 6711:     #
 6712:     # Remove all of the keys in the hashes which keep track of
 6713:     # the version of the parameter.
 6714:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6715:         # use a foreach because we are going to delete from the hash.
 6716:         foreach my $key (keys(%$param_hash)) {
 6717:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6718:         }
 6719:     }
 6720:     return \%returnhash;
 6721: }
 6722: 
 6723: # ------------------------------------------------------ critical inc interface
 6724: 
 6725: sub cinc {
 6726:     return &inc(@_,'critical');
 6727: }
 6728: 
 6729: # --------------------------------------------------------------- inc interface
 6730: 
 6731: sub inc {
 6732:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6733:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6734:     if (!$uname) { $uname=$env{'user.name'}; }
 6735:     my $uhome=&homeserver($uname,$udomain);
 6736:     my $items='';
 6737:     if (! ref($store)) {
 6738:         # got a single value, so use that instead
 6739:         $items = &escape($store).'=&';
 6740:     } elsif (ref($store) eq 'SCALAR') {
 6741:         $items = &escape($$store).'=&';        
 6742:     } elsif (ref($store) eq 'ARRAY') {
 6743:         $items = join('=&',map {&escape($_);} @{$store});
 6744:     } elsif (ref($store) eq 'HASH') {
 6745:         while (my($key,$value) = each(%{$store})) {
 6746:             $items.= &escape($key).'='.&escape($value).'&';
 6747:         }
 6748:     }
 6749:     $items=~s/\&$//;
 6750:     if ($critical) {
 6751: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6752:     } else {
 6753: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6754:     }
 6755: }
 6756: 
 6757: # --------------------------------------------------------------- put interface
 6758: 
 6759: sub put {
 6760:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6761:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6762:    if (!$uname) { $uname=$env{'user.name'}; }
 6763:    my $uhome=&homeserver($uname,$udomain);
 6764:    my $items='';
 6765:    foreach my $item (keys(%$storehash)) {
 6766:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6767:    }
 6768:    $items=~s/\&$//;
 6769:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6770: }
 6771: 
 6772: # ------------------------------------------------------------ newput interface
 6773: 
 6774: sub newput {
 6775:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6776:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6777:    if (!$uname) { $uname=$env{'user.name'}; }
 6778:    my $uhome=&homeserver($uname,$udomain);
 6779:    my $items='';
 6780:    foreach my $key (keys(%$storehash)) {
 6781:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6782:    }
 6783:    $items=~s/\&$//;
 6784:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6785: }
 6786: 
 6787: # ---------------------------------------------------------  putstore interface
 6788: 
 6789: sub putstore {
 6790:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6791:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6792:    if (!$uname) { $uname=$env{'user.name'}; }
 6793:    my $uhome=&homeserver($uname,$udomain);
 6794:    my $items='';
 6795:    foreach my $key (keys(%$storehash)) {
 6796:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6797:    }
 6798:    $items=~s/\&$//;
 6799:    my $esc_symb=&escape($symb);
 6800:    my $esc_v=&escape($version);
 6801:    my $reply =
 6802:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6803: 	      $uhome);
 6804:    if (($tolog) && ($reply eq 'ok')) {
 6805:        my $namevalue='';
 6806:        foreach my $key (keys(%{$storehash})) {
 6807:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6808:        }
 6809:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6810:                      '&host='.&escape($perlvar{'lonHostID'}).
 6811:                      '&version='.$esc_v.
 6812:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6813:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6814:    }
 6815:    if ($reply eq 'unknown_cmd') {
 6816:        # gfall back to way things use to be done
 6817:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6818: 			    $uname);
 6819:    }
 6820:    return $reply;
 6821: }
 6822: 
 6823: sub old_putstore {
 6824:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6825:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6826:     if (!$uname) { $uname=$env{'user.name'}; }
 6827:     my $uhome=&homeserver($uname,$udomain);
 6828:     my %newstorehash;
 6829:     foreach my $item (keys(%$storehash)) {
 6830: 	my $key = $version.':'.&escape($symb).':'.$item;
 6831: 	$newstorehash{$key} = $storehash->{$item};
 6832:     }
 6833:     my $items='';
 6834:     my %allitems = ();
 6835:     foreach my $item (keys(%newstorehash)) {
 6836: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6837: 	    my $key = $1.':keys:'.$2;
 6838: 	    $allitems{$key} .= $3.':';
 6839: 	}
 6840: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6841:     }
 6842:     foreach my $item (keys(%allitems)) {
 6843: 	$allitems{$item} =~ s/\:$//;
 6844: 	$items.= $item.'='.$allitems{$item}.'&';
 6845:     }
 6846:     $items=~s/\&$//;
 6847:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6848: }
 6849: 
 6850: # ------------------------------------------------------ critical put interface
 6851: 
 6852: sub cput {
 6853:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6854:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6855:    if (!$uname) { $uname=$env{'user.name'}; }
 6856:    my $uhome=&homeserver($uname,$udomain);
 6857:    my $items='';
 6858:    foreach my $item (keys(%$storehash)) {
 6859:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6860:    }
 6861:    $items=~s/\&$//;
 6862:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6863: }
 6864: 
 6865: # -------------------------------------------------------------- eget interface
 6866: 
 6867: sub eget {
 6868:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6869:    my $items='';
 6870:    foreach my $item (@$storearr) {
 6871:        $items.=&escape($item).'&';
 6872:    }
 6873:    $items=~s/\&$//;
 6874:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6875:    if (!$uname) { $uname=$env{'user.name'}; }
 6876:    my $uhome=&homeserver($uname,$udomain);
 6877:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6878:    my @pairs=split(/\&/,$rep);
 6879:    my %returnhash=();
 6880:    my $i=0;
 6881:    foreach my $item (@$storearr) {
 6882:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6883:       $i++;
 6884:    }
 6885:    return %returnhash;
 6886: }
 6887: 
 6888: # ------------------------------------------------------------ tmpput interface
 6889: sub tmpput {
 6890:     my ($storehash,$server,$context)=@_;
 6891:     my $items='';
 6892:     foreach my $item (keys(%$storehash)) {
 6893: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6894:     }
 6895:     $items=~s/\&$//;
 6896:     if (defined($context)) {
 6897:         $items .= ':'.&escape($context);
 6898:     }
 6899:     return &reply("tmpput:$items",$server);
 6900: }
 6901: 
 6902: # ------------------------------------------------------------ tmpget interface
 6903: sub tmpget {
 6904:     my ($token,$server)=@_;
 6905:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6906:     my $rep=&reply("tmpget:$token",$server);
 6907:     my %returnhash;
 6908:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6909:         return %returnhash;
 6910:     }
 6911:     foreach my $item (split(/\&/,$rep)) {
 6912: 	my ($key,$value)=split(/=/,$item);
 6913: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6914:     }
 6915:     return %returnhash;
 6916: }
 6917: 
 6918: # ------------------------------------------------------------ tmpdel interface
 6919: sub tmpdel {
 6920:     my ($token,$server)=@_;
 6921:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6922:     return &reply("tmpdel:$token",$server);
 6923: }
 6924: 
 6925: # ------------------------------------------------------------ get_timebased_id 
 6926: 
 6927: sub get_timebased_id {
 6928:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6929:         $maxtries) = @_;
 6930:     my ($newid,$error,$dellock);
 6931:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6932:         return ('','ok','invalid call to get suffix');
 6933:     }
 6934: 
 6935: # set defaults for any optional args for which values were not supplied
 6936:     if ($who eq '') {
 6937:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6938:     }
 6939:     if (!$locktries) {
 6940:         $locktries = 3;
 6941:     }
 6942:     if (!$maxtries) {
 6943:         $maxtries = 10;
 6944:     }
 6945:     
 6946:     if (($cdom eq '') || ($cnum eq '')) {
 6947:         if ($env{'request.course.id'}) {
 6948:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6949:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6950:         }
 6951:         if (($cdom eq '') || ($cnum eq '')) {
 6952:             return ('','ok','call to get suffix not in course context');
 6953:         }
 6954:     }
 6955: 
 6956: # construct locking item
 6957:     my $lockhash = {
 6958:                       $prefix."\0".'locked_'.$keyid => $who,
 6959:                    };
 6960:     my $tries = 0;
 6961: 
 6962: # attempt to get lock on nohist_$namespace file
 6963:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6964:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6965:         $tries ++;
 6966:         sleep 1;
 6967:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6968:     }
 6969: 
 6970: # attempt to get unique identifier, based on current timestamp
 6971:     if ($gotlock eq 'ok') {
 6972:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6973:         my $id = time;
 6974:         $newid = $id;
 6975:         if ($idtype eq 'addcode') {
 6976:             $newid .= &sixnum_code();
 6977:         }
 6978:         my $idtries = 0;
 6979:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6980:             if ($idtype eq 'concat') {
 6981:                 $newid = $id.$idtries;
 6982:             } elsif ($idtype eq 'addcode') {
 6983:                 $newid = $newid.&sixnum_code();
 6984:             } else {
 6985:                 $newid ++;
 6986:             }
 6987:             $idtries ++;
 6988:         }
 6989:         if (!exists($inuse{$prefix."\0".$newid})) {
 6990:             my %new_item =  (
 6991:                               $prefix."\0".$newid => $who,
 6992:                             );
 6993:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6994:                                                  $cdom,$cnum);
 6995:             if ($putresult ne 'ok') {
 6996:                 undef($newid);
 6997:                 $error = 'error saving new item: '.$putresult;
 6998:             }
 6999:         } else {
 7000:              undef($newid);
 7001:              $error = ('error: no unique suffix available for the new item ');
 7002:         }
 7003: #  remove lock
 7004:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7005:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7006:     } else {
 7007:         $error = "error: could not obtain lockfile\n";
 7008:         $dellock = 'ok';
 7009:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7010:             $dellock = 'nolock';
 7011:         }
 7012:     }
 7013:     return ($newid,$dellock,$error);
 7014: }
 7015: 
 7016: sub sixnum_code {
 7017:     my $code;
 7018:     for (0..6) {
 7019:         $code .= int( rand(9) );
 7020:     }
 7021:     return $code;
 7022: }
 7023: 
 7024: # -------------------------------------------------- portfolio access checking
 7025: 
 7026: sub portfolio_access {
 7027:     my ($requrl,$clientip) = @_;
 7028:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7029:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7030:     if ($result) {
 7031:         my %setters;
 7032:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7033:             my ($startblock,$endblock) =
 7034:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7035:             if ($startblock && $endblock) {
 7036:                 return 'B';
 7037:             }
 7038:         } else {
 7039:             my ($startblock,$endblock) =
 7040:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7041:             if ($startblock && $endblock) {
 7042:                 return 'B';
 7043:             }
 7044:         }
 7045:     }
 7046:     if ($result eq 'ok') {
 7047:        return 'F';
 7048:     } elsif ($result =~ /^[^:]+:guest_/) {
 7049:        return 'A';
 7050:     }
 7051:     return '';
 7052: }
 7053: 
 7054: sub get_portfolio_access {
 7055:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7056: 
 7057:     if (!ref($access_hash)) {
 7058: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7059: 	my %access_controls = &get_access_controls($current_perms,$group,
 7060: 						   $file_name);
 7061: 	$access_hash = $access_controls{$file_name};
 7062:     }
 7063: 
 7064:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7065:     my $now = time;
 7066:     if (ref($access_hash) eq 'HASH') {
 7067:         foreach my $key (keys(%{$access_hash})) {
 7068:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7069:             if ($start > $now) {
 7070:                 next;
 7071:             }
 7072:             if ($end && $end<$now) {
 7073:                 next;
 7074:             }
 7075:             if ($scope eq 'public') {
 7076:                 $public = $key;
 7077:                 last;
 7078:             } elsif ($scope eq 'guest') {
 7079:                 $guest = $key;
 7080:             } elsif ($scope eq 'domains') {
 7081:                 push(@domains,$key);
 7082:             } elsif ($scope eq 'users') {
 7083:                 push(@users,$key);
 7084:             } elsif ($scope eq 'course') {
 7085:                 push(@courses,$key);
 7086:             } elsif ($scope eq 'group') {
 7087:                 push(@groups,$key);
 7088:             } elsif ($scope eq 'ip') {
 7089:                 push(@ips,$key);
 7090:             }
 7091:         }
 7092:         if ($public) {
 7093:             return 'ok';
 7094:         } elsif (@ips > 0) {
 7095:             my $allowed;
 7096:             foreach my $ipkey (@ips) {
 7097:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7098:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7099:                         $allowed = 1;
 7100:                         last; 
 7101:                     }
 7102:                 }
 7103:             }
 7104:             if ($allowed) {
 7105:                 return 'ok';
 7106:             }
 7107:         }
 7108:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7109:             if ($guest) {
 7110:                 return $guest;
 7111:             }
 7112:         } else {
 7113:             if (@domains > 0) {
 7114:                 foreach my $domkey (@domains) {
 7115:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7116:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7117:                             return 'ok';
 7118:                         }
 7119:                     }
 7120:                 }
 7121:             }
 7122:             if (@users > 0) {
 7123:                 foreach my $userkey (@users) {
 7124:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7125:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7126:                             if (ref($item) eq 'HASH') {
 7127:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7128:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7129:                                     return 'ok';
 7130:                                 }
 7131:                             }
 7132:                         }
 7133:                     } 
 7134:                 }
 7135:             }
 7136:             my %roleshash;
 7137:             my @courses_and_groups = @courses;
 7138:             push(@courses_and_groups,@groups); 
 7139:             if (@courses_and_groups > 0) {
 7140:                 my (%allgroups,%allroles); 
 7141:                 my ($start,$end,$role,$sec,$group);
 7142:                 foreach my $envkey (%env) {
 7143:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7144:                         my $cid = $2.'_'.$3; 
 7145:                         if ($1 eq 'gr') {
 7146:                             $group = $4;
 7147:                             $allgroups{$cid}{$group} = $env{$envkey};
 7148:                         } else {
 7149:                             if ($4 eq '') {
 7150:                                 $sec = 'none';
 7151:                             } else {
 7152:                                 $sec = $4;
 7153:                             }
 7154:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7155:                         }
 7156:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7157:                         my $cid = $2.'_'.$3;
 7158:                         if ($4 eq '') {
 7159:                             $sec = 'none';
 7160:                         } else {
 7161:                             $sec = $4;
 7162:                         }
 7163:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7164:                     }
 7165:                 }
 7166:                 if (keys(%allroles) == 0) {
 7167:                     return;
 7168:                 }
 7169:                 foreach my $key (@courses_and_groups) {
 7170:                     my %content = %{$$access_hash{$key}};
 7171:                     my $cnum = $content{'number'};
 7172:                     my $cdom = $content{'domain'};
 7173:                     my $cid = $cdom.'_'.$cnum;
 7174:                     if (!exists($allroles{$cid})) {
 7175:                         next;
 7176:                     }    
 7177:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7178:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7179:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7180:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7181:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7182:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7183:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7184:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7185:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7186:                                         if (grep/^all$/,@sections) {
 7187:                                             return 'ok';
 7188:                                         } else {
 7189:                                             if (grep/^$sec$/,@sections) {
 7190:                                                 return 'ok';
 7191:                                             }
 7192:                                         }
 7193:                                     }
 7194:                                 }
 7195:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7196:                                     if (grep/^none$/,@groups) {
 7197:                                         return 'ok';
 7198:                                     }
 7199:                                 } else {
 7200:                                     if (grep/^all$/,@groups) {
 7201:                                         return 'ok';
 7202:                                     } 
 7203:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7204:                                         if (grep/^$group$/,@groups) {
 7205:                                             return 'ok';
 7206:                                         }
 7207:                                     }
 7208:                                 } 
 7209:                             }
 7210:                         }
 7211:                     }
 7212:                 }
 7213:             }
 7214:             if ($guest) {
 7215:                 return $guest;
 7216:             }
 7217:         }
 7218:     }
 7219:     return;
 7220: }
 7221: 
 7222: sub course_group_datechecker {
 7223:     my ($dates,$now,$status) = @_;
 7224:     my ($start,$end) = split(/\./,$dates);
 7225:     if (!$start && !$end) {
 7226:         return 'ok';
 7227:     }
 7228:     if (grep/^active$/,@{$status}) {
 7229:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7230:             return 'ok';
 7231:         }
 7232:     }
 7233:     if (grep/^previous$/,@{$status}) {
 7234:         if ($end > $now ) {
 7235:             return 'ok';
 7236:         }
 7237:     }
 7238:     if (grep/^future$/,@{$status}) {
 7239:         if ($start > $now) {
 7240:             return 'ok';
 7241:         }
 7242:     }
 7243:     return; 
 7244: }
 7245: 
 7246: sub parse_portfolio_url {
 7247:     my ($url) = @_;
 7248: 
 7249:     my ($type,$udom,$unum,$group,$file_name);
 7250:     
 7251:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7252: 	$type = 1;
 7253:         $udom = $1;
 7254:         $unum = $2;
 7255:         $file_name = $3;
 7256:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7257: 	$type = 2;
 7258:         $udom = $1;
 7259:         $unum = $2;
 7260:         $group = $3;
 7261:         $file_name = $3.'/'.$4;
 7262:     }
 7263:     if (wantarray) {
 7264: 	return ($type,$udom,$unum,$file_name,$group);
 7265:     }
 7266:     return $type;
 7267: }
 7268: 
 7269: sub is_portfolio_url {
 7270:     my ($url) = @_;
 7271:     return scalar(&parse_portfolio_url($url));
 7272: }
 7273: 
 7274: sub is_portfolio_file {
 7275:     my ($file) = @_;
 7276:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7277:         return 1;
 7278:     }
 7279:     return;
 7280: }
 7281: 
 7282: sub usertools_access {
 7283:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7284:     my ($access,%tools);
 7285:     if ($context eq '') {
 7286:         $context = 'tools';
 7287:     }
 7288:     if ($context eq 'requestcourses') {
 7289:         %tools = (
 7290:                       official   => 1,
 7291:                       unofficial => 1,
 7292:                       community  => 1,
 7293:                       textbook   => 1,
 7294:                       placement  => 1,
 7295:                       lti        => 1,
 7296:                  );
 7297:     } elsif ($context eq 'requestauthor') {
 7298:         %tools = (
 7299:                       requestauthor => 1,
 7300:                  );
 7301:     } else {
 7302:         %tools = (
 7303:                       aboutme   => 1,
 7304:                       blog      => 1,
 7305:                       webdav    => 1,
 7306:                       portfolio => 1,
 7307:                  );
 7308:     }
 7309:     return if (!defined($tools{$tool}));
 7310: 
 7311:     if (($udom eq '') || ($uname eq '')) {
 7312:         $udom = $env{'user.domain'};
 7313:         $uname = $env{'user.name'};
 7314:     }
 7315: 
 7316:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7317:         if ($action ne 'reload') {
 7318:             if ($context eq 'requestcourses') {
 7319:                 return $env{'environment.canrequest.'.$tool};
 7320:             } elsif ($context eq 'requestauthor') {
 7321:                 return $env{'environment.canrequest.author'};
 7322:             } else {
 7323:                 return $env{'environment.availabletools.'.$tool};
 7324:             }
 7325:         }
 7326:     }
 7327: 
 7328:     my ($toolstatus,$inststatus,$envkey);
 7329:     if ($context eq 'requestauthor') {
 7330:         $envkey = $context; 
 7331:     } else {
 7332:         $envkey = $context.'.'.$tool;
 7333:     }
 7334: 
 7335:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7336:          ($action ne 'reload')) {
 7337:         $toolstatus = $env{'environment.'.$envkey};
 7338:         $inststatus = $env{'environment.inststatus'};
 7339:     } else {
 7340:         if (ref($userenvref) eq 'HASH') {
 7341:             $toolstatus = $userenvref->{$envkey};
 7342:             $inststatus = $userenvref->{'inststatus'};
 7343:         } else {
 7344:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7345:             $toolstatus = $userenv{$envkey};
 7346:             $inststatus = $userenv{'inststatus'};
 7347:         }
 7348:     }
 7349: 
 7350:     if ($toolstatus ne '') {
 7351:         if ($toolstatus) {
 7352:             $access = 1;
 7353:         } else {
 7354:             $access = 0;
 7355:         }
 7356:         return $access;
 7357:     }
 7358: 
 7359:     my ($is_adv,%domdef);
 7360:     if (ref($is_advref) eq 'HASH') {
 7361:         $is_adv = $is_advref->{'is_adv'};
 7362:     } else {
 7363:         $is_adv = &is_advanced_user($udom,$uname);
 7364:     }
 7365:     if (ref($domdefref) eq 'HASH') {
 7366:         %domdef = %{$domdefref};
 7367:     } else {
 7368:         %domdef = &get_domain_defaults($udom);
 7369:     }
 7370:     if (ref($domdef{$tool}) eq 'HASH') {
 7371:         if ($is_adv) {
 7372:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7373:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7374:                     $access = 1;
 7375:                 } else {
 7376:                     $access = 0;
 7377:                 }
 7378:                 return $access;
 7379:             }
 7380:         }
 7381:         if ($inststatus ne '') {
 7382:             my ($hasaccess,$hasnoaccess);
 7383:             foreach my $affiliation (split(/:/,$inststatus)) {
 7384:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7385:                     if ($domdef{$tool}{$affiliation}) {
 7386:                         $hasaccess = 1;
 7387:                     } else {
 7388:                         $hasnoaccess = 1;
 7389:                     }
 7390:                 }
 7391:             }
 7392:             if ($hasaccess || $hasnoaccess) {
 7393:                 if ($hasaccess) {
 7394:                     $access = 1;
 7395:                 } elsif ($hasnoaccess) {
 7396:                     $access = 0; 
 7397:                 }
 7398:                 return $access;
 7399:             }
 7400:         } else {
 7401:             if ($domdef{$tool}{'default'} ne '') {
 7402:                 if ($domdef{$tool}{'default'}) {
 7403:                     $access = 1;
 7404:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7405:                     $access = 0;
 7406:                 }
 7407:                 return $access;
 7408:             }
 7409:         }
 7410:     } else {
 7411:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7412:             $access = 1;
 7413:         } else {
 7414:             $access = 0;
 7415:         }
 7416:         return $access;
 7417:     }
 7418: }
 7419: 
 7420: sub is_course_owner {
 7421:     my ($cdom,$cnum,$udom,$uname) = @_;
 7422:     if (($udom eq '') || ($uname eq '')) {
 7423:         $udom = $env{'user.domain'};
 7424:         $uname = $env{'user.name'};
 7425:     }
 7426:     unless (($udom eq '') || ($uname eq '')) {
 7427:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7428:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7429:                 return 1;
 7430:             } else {
 7431:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7432:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7433:                     return 1;
 7434:                 }
 7435:             }
 7436:         }
 7437:     }
 7438:     return;
 7439: }
 7440: 
 7441: sub is_advanced_user {
 7442:     my ($udom,$uname) = @_;
 7443:     if ($udom ne '' && $uname ne '') {
 7444:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7445:             if (wantarray) {
 7446:                 return ($env{'user.adv'},$env{'user.author'});
 7447:             } else {
 7448:                 return $env{'user.adv'};
 7449:             }
 7450:         }
 7451:     }
 7452:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7453:     my %allroles;
 7454:     my ($is_adv,$is_author);
 7455:     foreach my $role (keys(%roleshash)) {
 7456:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7457:         my $area = '/'.$tdomain.'/'.$trest;
 7458:         if ($sec ne '') {
 7459:             $area .= '/'.$sec;
 7460:         }
 7461:         if (($area ne '') && ($trole ne '')) {
 7462:             my $spec=$trole.'.'.$area;
 7463:             if ($trole =~ /^cr\//) {
 7464:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7465:             } elsif ($trole ne 'gr') {
 7466:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7467:             }
 7468:             if ($trole eq 'au') {
 7469:                 $is_author = 1;
 7470:             }
 7471:         }
 7472:     }
 7473:     foreach my $role (keys(%allroles)) {
 7474:         last if ($is_adv);
 7475:         foreach my $item (split(/:/,$allroles{$role})) {
 7476:             if ($item ne '') {
 7477:                 my ($privilege,$restrictions)=split(/&/,$item);
 7478:                 if ($privilege eq 'adv') {
 7479:                     $is_adv = 1;
 7480:                     last;
 7481:                 }
 7482:             }
 7483:         }
 7484:     }
 7485:     if (wantarray) {
 7486:         return ($is_adv,$is_author);
 7487:     }
 7488:     return $is_adv;
 7489: }
 7490: 
 7491: sub check_can_request {
 7492:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7493:     my $canreq = 0;
 7494:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7495:         $uname = $env{'user.name'};
 7496:         $udom = $env{'user.domain'};
 7497:     }
 7498:     my ($types,$typename) = &Apache::loncommon::course_types();
 7499:     my @options = ('approval','validate','autolimit');
 7500:     my $optregex = join('|',@options);
 7501:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7502:         foreach my $type (@{$types}) {
 7503:             if (&usertools_access($uname,$udom,$type,undef,
 7504:                                   'requestcourses')) {
 7505:                 $canreq ++;
 7506:                 if (ref($request_domains) eq 'HASH') {
 7507:                     push(@{$request_domains->{$type}},$udom);
 7508:                 }
 7509:                 if ($dom eq $udom) {
 7510:                     $can_request->{$type} = 1;
 7511:                 }
 7512:             }
 7513:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7514:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7515:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7516:                 if (@curr > 0) {
 7517:                     foreach my $item (@curr) {
 7518:                         if (ref($request_domains) eq 'HASH') {
 7519:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7520:                             if ($otherdom ne '') {
 7521:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7522:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7523:                                         push(@{$request_domains->{$type}},$otherdom);
 7524:                                     }
 7525:                                 } else {
 7526:                                     push(@{$request_domains->{$type}},$otherdom);
 7527:                                 }
 7528:                             }
 7529:                         }
 7530:                     }
 7531:                     unless ($dom eq $env{'user.domain'}) {
 7532:                         $canreq ++;
 7533:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7534:                             $can_request->{$type} = 1;
 7535:                         }
 7536:                     }
 7537:                 }
 7538:             }
 7539:         }
 7540:     }
 7541:     return $canreq;
 7542: }
 7543: 
 7544: # ---------------------------------------------- Custom access rule evaluation
 7545: 
 7546: sub customaccess {
 7547:     my ($priv,$uri)=@_;
 7548:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7549:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7550:     $udom = &LONCAPA::clean_domain($udom);
 7551:     $ucrs = &LONCAPA::clean_username($ucrs);
 7552:     my $access=0;
 7553:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7554: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7555: 	if ($type eq 'user') {
 7556: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7557: 		my ($tdom,$tuname)=split(m{/},$scope);
 7558: 		if ($tdom) {
 7559: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7560: 		}
 7561: 		if ($tuname) {
 7562: 		    if ($tuname ne $env{'user.name'}) { next; }
 7563: 		}
 7564: 		$access=($effect eq 'allow');
 7565: 		last;
 7566: 	    }
 7567: 	} else {
 7568: 	    if ($role) {
 7569: 		if ($role ne $urole) { next; }
 7570: 	    }
 7571: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7572: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7573: 		if ($tdom) {
 7574: 		    if ($tdom ne $udom) { next; }
 7575: 		}
 7576: 		if ($tcrs) {
 7577: 		    if ($tcrs ne $ucrs) { next; }
 7578: 		}
 7579: 		if ($tsec) {
 7580: 		    if ($tsec ne $usec) { next; }
 7581: 		}
 7582: 		$access=($effect eq 'allow');
 7583: 		last;
 7584: 	    }
 7585: 	    if ($realm eq '' && $role eq '') {
 7586: 		$access=($effect eq 'allow');
 7587: 	    }
 7588: 	}
 7589:     }
 7590:     return $access;
 7591: }
 7592: 
 7593: # ------------------------------------------------- Check for a user privilege
 7594: 
 7595: sub allowed {
 7596:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7597:     my $ver_orguri=$uri;
 7598:     $uri=&deversion($uri);
 7599:     my $orguri=$uri;
 7600:     $uri=&declutter($uri);
 7601: 
 7602:     if ($priv eq 'evb') {
 7603: # Evade communication block restrictions for specified role in a course
 7604:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7605:             return $1;
 7606:         } else {
 7607:             return;
 7608:         }
 7609:     }
 7610: 
 7611:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7612: # Free bre access to adm and meta resources
 7613:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7614: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7615: 	&& ($priv eq 'bre')) {
 7616: 	return 'F';
 7617:     }
 7618: 
 7619: # Free bre access to user's own portfolio contents
 7620:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7621:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7622: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7623:         my %setters;
 7624:         my ($startblock,$endblock) = 
 7625:             &Apache::loncommon::blockcheck(\%setters,'port');
 7626:         if ($startblock && $endblock) {
 7627:             return 'B';
 7628:         } else {
 7629:             return 'F';
 7630:         }
 7631:     }
 7632: 
 7633: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7634:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7635:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7636:         if (exists($env{'request.course.id'})) {
 7637:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7638:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7639:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7640:                 my $courseprivid=$env{'request.course.id'};
 7641:                 $courseprivid=~s/\_/\//;
 7642:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7643:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7644:                     return $1; 
 7645:                 } else {
 7646:                     if ($env{'request.course.sec'}) {
 7647:                         $courseprivid.='/'.$env{'request.course.sec'};
 7648:                     }
 7649:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7650:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7651:                         return $2;
 7652:                     }
 7653:                 }
 7654:             }
 7655:         }
 7656:     }
 7657: 
 7658: # Free bre to public access
 7659: 
 7660:     if ($priv eq 'bre') {
 7661:         my $copyright;
 7662:         unless ($uri =~ /ext\.tool/) {
 7663:             $copyright=&metadata($uri,'copyright');
 7664:         }
 7665: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7666:            return 'F'; 
 7667:         }
 7668:         if ($copyright eq 'priv') {
 7669:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7670: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7671: 		return '';
 7672:             }
 7673:         }
 7674:         if ($copyright eq 'domain') {
 7675:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7676: 	    unless (($env{'user.domain'} eq $1) ||
 7677:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7678: 		return '';
 7679:             }
 7680:         }
 7681:         if ($env{'request.role'}=~ /li\.\//) {
 7682:             # Library role, so allow browsing of resources in this domain.
 7683:             return 'F';
 7684:         }
 7685:         if ($copyright eq 'custom') {
 7686: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7687:         }
 7688:     }
 7689:     # Domain coordinator is trying to create a course
 7690:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7691:         # uri is the requested domain in this case.
 7692:         # comparison to 'request.role.domain' shows if the user has selected
 7693:         # a role of dc for the domain in question.
 7694:         return 'F' if ($uri eq $env{'request.role.domain'});
 7695:     }
 7696: 
 7697:     my $thisallowed='';
 7698:     my $statecond=0;
 7699:     my $courseprivid='';
 7700: 
 7701:     my $ownaccess;
 7702:     # Community Coordinator or Assistant Co-author browsing resource space.
 7703:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7704:         if ($uri eq '') {
 7705:             $ownaccess = 1;
 7706:         } else {
 7707:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7708:                 my $udom = $env{'user.domain'};
 7709:                 my $uname = $env{'user.name'};
 7710:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7711:                     $ownaccess = 1;
 7712:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7713:                     unless ($uri =~ m{\.\./}) {
 7714:                         $ownaccess = 1;
 7715:                     }
 7716:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7717:                     my $now = time;
 7718:                     if ($uri =~ m{^([^/]+)/?$}) {
 7719:                         my $adom = $1;
 7720:                         foreach my $key (keys(%env)) {
 7721:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7722:                                 my ($start,$end) = split('.',$env{$key});
 7723:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7724:                                     $ownaccess = 1;
 7725:                                     last;
 7726:                                 }
 7727:                             }
 7728:                         }
 7729:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7730:                         my $adom = $1;
 7731:                         my $aname = $2;
 7732:                         foreach my $role ('ca','aa') { 
 7733:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7734:                                 my ($start,$end) =
 7735:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7736:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7737:                                     $ownaccess = 1;
 7738:                                     last;
 7739:                                 }
 7740:                             }
 7741:                         }
 7742:                     }
 7743:                 }
 7744:             }
 7745:         }
 7746:     }
 7747: 
 7748: # Course
 7749: 
 7750:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7751:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7752:             $thisallowed.=$1;
 7753:         }
 7754:     }
 7755: 
 7756: # Domain
 7757: 
 7758:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7759:        =~/\Q$priv\E\&([^\:]*)/) {
 7760:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7761:             $thisallowed.=$1;
 7762:         }
 7763:     }
 7764: 
 7765: # User who is not author or co-author might still be able to edit
 7766: # resource of an author in the domain (e.g., if Domain Coordinator).
 7767:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7768:         (&allowed('mdc',$env{'request.course.id'}))) {
 7769:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7770:             $thisallowed.=$1;
 7771:         }
 7772:     }
 7773: 
 7774: # Course: uri itself is a course
 7775:     my $courseuri=$uri;
 7776:     $courseuri=~s/\_(\d)/\/$1/;
 7777:     $courseuri=~s/^([^\/])/\/$1/;
 7778: 
 7779:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7780:        =~/\Q$priv\E\&([^\:]*)/) {
 7781:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7782:             $thisallowed.=$1;
 7783:         }
 7784:     }
 7785: 
 7786: # URI is an uploaded document for this course, default permissions don't matter
 7787: # not allowing 'edit' access (editupload) to uploaded course docs
 7788:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7789: 	$thisallowed='';
 7790:         my ($match)=&is_on_map($uri);
 7791:         if ($match) {
 7792:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7793:                   =~/\Q$priv\E\&([^\:]*)/) {
 7794:                 my $value = $1;
 7795:                 if ($noblockcheck) {
 7796:                     $thisallowed.=$value;
 7797:                 } else {
 7798:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7799:                     if (@blockers > 0) {
 7800:                         $thisallowed = 'B';
 7801:                     } else {
 7802:                         $thisallowed.=$value;
 7803:                     }
 7804:                 }
 7805:             }
 7806:         } else {
 7807:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7808:             if ($refuri) {
 7809:                 if ($refuri =~ m|^/adm/|) {
 7810:                     $thisallowed='F';
 7811:                 } else {
 7812:                     $refuri=&declutter($refuri);
 7813:                     my ($match) = &is_on_map($refuri);
 7814:                     if ($match) {
 7815:                         if ($noblockcheck) {
 7816:                             $thisallowed='F';
 7817:                         } else {
 7818:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7819:                             if (@blockers > 0) {
 7820:                                 $thisallowed = 'B';
 7821:                             } else {
 7822:                                 $thisallowed='F';
 7823:                             }
 7824:                         }
 7825:                     }
 7826:                 }
 7827:             }
 7828:         }
 7829:     }
 7830: 
 7831:     if ($priv eq 'bre'
 7832: 	&& $thisallowed ne 'F' 
 7833: 	&& $thisallowed ne '2'
 7834: 	&& &is_portfolio_url($uri)) {
 7835: 	$thisallowed = &portfolio_access($uri,$clientip);
 7836:     }
 7837: 
 7838: # Full access at system, domain or course-wide level? Exit.
 7839:     if ($thisallowed=~/F/) {
 7840: 	return 'F';
 7841:     }
 7842: 
 7843: # If this is generating or modifying users, exit with special codes
 7844: 
 7845:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7846: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7847: 	    my ($audom,$auname)=split('/',$uri);
 7848: # no author name given, so this just checks on the general right to make a co-author in this domain
 7849: 	    unless ($auname) { return $thisallowed; }
 7850: # an author name is given, so we are about to actually make a co-author for a certain account
 7851: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7852: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7853: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7854: 	}
 7855: 	return $thisallowed;
 7856:     }
 7857: #
 7858: # Gathered so far: system, domain and course wide privileges
 7859: #
 7860: # Course: See if uri or referer is an individual resource that is part of 
 7861: # the course
 7862: 
 7863:     if ($env{'request.course.id'}) {
 7864: 
 7865:        $courseprivid=$env{'request.course.id'};
 7866:        if ($env{'request.course.sec'}) {
 7867:           $courseprivid.='/'.$env{'request.course.sec'};
 7868:        }
 7869:        $courseprivid=~s/\_/\//;
 7870:        my $checkreferer=1;
 7871:        my ($match,$cond)=&is_on_map($uri);
 7872:        if ($match) {
 7873:            $statecond=$cond;
 7874:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7875:                =~/\Q$priv\E\&([^\:]*)/) {
 7876:                my $value = $1;
 7877:                if ($priv eq 'bre') {
 7878:                    if ($noblockcheck) {
 7879:                        $thisallowed.=$value;
 7880:                    } else {
 7881:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7882:                        if (@blockers > 0) {
 7883:                            $thisallowed = 'B';
 7884:                        } else {
 7885:                            $thisallowed.=$value;
 7886:                        }
 7887:                    }
 7888:                } else {
 7889:                    $thisallowed.=$value;
 7890:                }
 7891:                $checkreferer=0;
 7892:            }
 7893:        }
 7894:        
 7895:        if ($checkreferer) {
 7896: 	  my $refuri=$env{'httpref.'.$orguri};
 7897:             unless ($refuri) {
 7898:                 foreach my $key (keys(%env)) {
 7899: 		    if ($key=~/^httpref\..*\*/) {
 7900: 			my $pattern=$key;
 7901:                         $pattern=~s/^httpref\.\/res\///;
 7902:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7903:                         $pattern=~s/\//\\\//g;
 7904:                         if ($orguri=~/$pattern/) {
 7905: 			    $refuri=$env{$key};
 7906:                         }
 7907:                     }
 7908:                 }
 7909:             }
 7910: 
 7911:          if ($refuri) { 
 7912: 	  $refuri=&declutter($refuri);
 7913:           my ($match,$cond)=&is_on_map($refuri);
 7914:             if ($match) {
 7915:               my $refstatecond=$cond;
 7916:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7917:                   =~/\Q$priv\E\&([^\:]*)/) {
 7918:                   my $value = $1;
 7919:                   if ($priv eq 'bre') {
 7920:                       if ($noblockcheck) {
 7921:                           $thisallowed.=$value;
 7922:                       } else {
 7923:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7924:                           if (@blockers > 0) {
 7925:                               $thisallowed = 'B';
 7926:                           } else {
 7927:                               $thisallowed.=$value;
 7928:                           }
 7929:                       }
 7930:                   } else {
 7931:                       $thisallowed.=$value;
 7932:                   }
 7933:                   $uri=$refuri;
 7934:                   $statecond=$refstatecond;
 7935:               }
 7936:           }
 7937:         }
 7938:        }
 7939:    }
 7940: 
 7941: #
 7942: # Gathered now: all privileges that could apply, and condition number
 7943: # 
 7944: #
 7945: # Full or no access?
 7946: #
 7947: 
 7948:     if ($thisallowed=~/F/) {
 7949: 	return 'F';
 7950:     }
 7951: 
 7952:     unless ($thisallowed) {
 7953:         return '';
 7954:     }
 7955: 
 7956: # Restrictions exist, deal with them
 7957: #
 7958: #   C:according to course preferences
 7959: #   R:according to resource settings
 7960: #   L:unless locked
 7961: #   X:according to user session state
 7962: #
 7963: 
 7964: # Possibly locked functionality, check all courses
 7965: # Locks might take effect only after 10 minutes cache expiration for other
 7966: # courses, and 2 minutes for current course
 7967: 
 7968:     my $envkey;
 7969:     if ($thisallowed=~/L/) {
 7970:         foreach $envkey (keys(%env)) {
 7971:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7972:                my $courseid=$2;
 7973:                my $roleid=$1.'.'.$2;
 7974:                $courseid=~s/^\///;
 7975:                my $expiretime=600;
 7976:                if ($env{'request.role'} eq $roleid) {
 7977: 		  $expiretime=120;
 7978:                }
 7979: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7980:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7981:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7982: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7983:                }
 7984:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7985:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7986: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7987:                        &log($env{'user.domain'},$env{'user.name'},
 7988:                             $env{'user.home'},
 7989:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7990:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7991:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7992: 		       return '';
 7993:                    }
 7994:                }
 7995:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7996:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7997: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7998:                        &log($env{'user.domain'},$env{'user.name'},
 7999:                             $env{'user.home'},
 8000:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8001:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8002:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8003: 		       return '';
 8004:                    }
 8005:                }
 8006: 	   }
 8007:        }
 8008:     }
 8009:    
 8010: #
 8011: # Rest of the restrictions depend on selected course
 8012: #
 8013: 
 8014:     unless ($env{'request.course.id'}) {
 8015: 	if ($thisallowed eq 'A') {
 8016: 	    return 'A';
 8017:         } elsif ($thisallowed eq 'B') {
 8018:             return 'B';
 8019: 	} else {
 8020: 	    return '1';
 8021: 	}
 8022:     }
 8023: 
 8024: #
 8025: # Now user is definitely in a course
 8026: #
 8027: 
 8028: 
 8029: # Course preferences
 8030: 
 8031:    if ($thisallowed=~/C/) {
 8032:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8033:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8034:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8035: 	   =~/\Q$rolecode\E/) {
 8036: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8037: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8038: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8039: 			$env{'request.course.id'});
 8040: 	   }
 8041:            return '';
 8042:        }
 8043: 
 8044:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8045: 	   =~/\Q$unamedom\E/) {
 8046: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8047: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8048: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8049: 			$env{'request.course.id'});
 8050: 	   }
 8051:            return '';
 8052:        }
 8053:    }
 8054: 
 8055: # Resource preferences
 8056: 
 8057:    if ($thisallowed=~/R/) {
 8058:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8059:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8060: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8061: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8062: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8063: 	   }
 8064: 	   return '';
 8065:        }
 8066:    }
 8067: 
 8068: # Restricted by state or randomout?
 8069: 
 8070:    if ($thisallowed=~/X/) {
 8071:       if ($env{'acc.randomout'}) {
 8072: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8073:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8074:             return ''; 
 8075:          }
 8076:       }
 8077:       if (&condval($statecond)) {
 8078: 	 return '2';
 8079:       } else {
 8080:          return '';
 8081:       }
 8082:    }
 8083: 
 8084:     if ($thisallowed eq 'A') {
 8085: 	return 'A';
 8086:     } elsif ($thisallowed eq 'B') {
 8087:         return 'B';
 8088:     }
 8089:    return 'F';
 8090: }
 8091: 
 8092: # ------------------------------------------- Check construction space access
 8093: 
 8094: sub constructaccess {
 8095:     my ($url,$setpriv)=@_;
 8096: 
 8097: # We do not allow editing of previous versions of files
 8098:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8099: 
 8100: # Get username and domain from URL
 8101:     my ($ownername,$ownerdomain,$ownerhome);
 8102: 
 8103:     ($ownerdomain,$ownername) =
 8104:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8105: 
 8106: # The URL does not really point to any authorspace, forget it
 8107:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8108: 
 8109: # Now we need to see if the user has access to the authorspace of
 8110: # $ownername at $ownerdomain
 8111: 
 8112:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8113: # Real author for this?
 8114:        $ownerhome = $env{'user.home'};
 8115:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8116:           return ($ownername,$ownerdomain,$ownerhome);
 8117:        }
 8118:     } else {
 8119: # Co-author for this?
 8120:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8121:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8122:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8123:             return ($ownername,$ownerdomain,$ownerhome);
 8124:         }
 8125:         if ($env{'request.course.id'}) {
 8126:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8127:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8128:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8129:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8130:                     return ($ownername,$ownerdomain,$ownerhome);
 8131:                 }
 8132:             }
 8133:         }
 8134:     }
 8135: 
 8136: # We don't have any access right now. If we are not possibly going to do anything about this,
 8137: # we might as well leave
 8138:    unless ($setpriv) { return ''; }
 8139: 
 8140: # Backdoor access?
 8141:     my $allowed=&allowed('eco',$ownerdomain);
 8142: # Nope
 8143:     unless ($allowed) { return ''; }
 8144: # Looks like we may have access, but could be locked by the owner of the construction space
 8145:     if ($allowed eq 'U') {
 8146:         my %blocked=&get('environment',['domcoord.author'],
 8147:                          $ownerdomain,$ownername);
 8148: # Is blocked by owner
 8149:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8150:     }
 8151:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8152: # Grant temporary access
 8153:         my $then=$env{'user.login.time'};
 8154:         my $update=$env{'user.update.time'};
 8155:         if (!$update) { $update = $then; }
 8156:         my $refresh=$env{'user.refresh.time'};
 8157:         if (!$refresh) { $refresh = $update; }
 8158:         my $now = time;
 8159:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8160:                            $now,'ca','constructaccess');
 8161:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8162:         return($ownername,$ownerdomain,$ownerhome);
 8163:     }
 8164: # No business here
 8165:     return '';
 8166: }
 8167: 
 8168: # ----------------------------------------------------------- Content Blocking
 8169: 
 8170: {
 8171: # Caches for faster Course Contents display where content blocking
 8172: # is in operation (i.e., interval param set) for timed quiz.
 8173: #
 8174: # User for whom data are being temporarily cached.
 8175: my $cacheduser='';
 8176: # Cached blockers for this user (a hash of blocking items). 
 8177: my %cachedblockers=();
 8178: # When the data were last cached.
 8179: my $cachedlast='';
 8180: 
 8181: sub load_all_blockers {
 8182:     my ($uname,$udom,$blocks)=@_;
 8183:     if (($uname ne '') && ($udom ne '')) { 
 8184:         if (($cacheduser eq $uname.':'.$udom) &&
 8185:             (abs($cachedlast-time)<5)) {
 8186:             return;
 8187:         }
 8188:     }
 8189:     $cachedlast=time;
 8190:     $cacheduser=$uname.':'.$udom;
 8191:     %cachedblockers = &get_commblock_resources($blocks);
 8192: }
 8193: 
 8194: sub get_comm_blocks {
 8195:     my ($cdom,$cnum) = @_;
 8196:     if ($cdom eq '' || $cnum eq '') {
 8197:         return unless ($env{'request.course.id'});
 8198:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8199:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8200:     }
 8201:     my %commblocks;
 8202:     my $hashid=$cdom.'_'.$cnum;
 8203:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8204:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8205:         %commblocks = %{$blocksref};
 8206:     } else {
 8207:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8208:         my $cachetime = 600;
 8209:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8210:     }
 8211:     return %commblocks;
 8212: }
 8213: 
 8214: sub get_commblock_resources {
 8215:     my ($blocks) = @_;
 8216:     my %blockers = ();
 8217:     return %blockers unless ($env{'request.course.id'});
 8218:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8219:     my %commblocks;
 8220:     if (ref($blocks) eq 'HASH') {
 8221:         %commblocks = %{$blocks};
 8222:     } else {
 8223:         %commblocks = &get_comm_blocks();
 8224:     }
 8225:     return %blockers unless (keys(%commblocks) > 0); 
 8226:     my $navmap = Apache::lonnavmaps::navmap->new();
 8227:     return %blockers unless (ref($navmap));
 8228:     my $now = time;
 8229:     foreach my $block (keys(%commblocks)) {
 8230:         if ($block =~ /^(\d+)____(\d+)$/) {
 8231:             my ($start,$end) = ($1,$2);
 8232:             if ($start <= $now && $end >= $now) {
 8233:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8234:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8235:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8236:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8237:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8238:                             }
 8239:                         }
 8240:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8241:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8242:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8243:                             }
 8244:                         }
 8245:                     }
 8246:                 }
 8247:             }
 8248:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8249:             my $item = $1;
 8250:             my @to_test;
 8251:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8252:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8253:                     my @interval;
 8254:                     my $type = 'map';
 8255:                     if ($item eq 'course') {
 8256:                         $type = 'course';
 8257:                         @interval=&EXT("resource.0.interval");
 8258:                     } else {
 8259:                         if ($item =~ /___\d+___/) {
 8260:                             $type = 'resource';
 8261:                             @interval=&EXT("resource.0.interval",$item);
 8262:                             if (ref($navmap)) {                        
 8263:                                 my $res = $navmap->getBySymb($item); 
 8264:                                 push(@to_test,$res);
 8265:                             }
 8266:                         } else {
 8267:                             my $mapsymb = &symbread($item,1);
 8268:                             if ($mapsymb) {
 8269:                                 if (ref($navmap)) {
 8270:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8271:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8272:                                     foreach my $res (@to_test) {
 8273:                                         my $symb = $res->symb();
 8274:                                         next if ($symb eq $mapsymb);
 8275:                                         if ($symb ne '') {
 8276:                                             @interval=&EXT("resource.0.interval",$symb);
 8277:                                             if ($interval[1] eq 'map') {
 8278:                                                 last;
 8279:                                             }
 8280:                                         }
 8281:                                     }
 8282:                                 }
 8283:                             }
 8284:                         }
 8285:                     }
 8286:                     if ($interval[0] =~ /^(\d+)/) {
 8287:                         my $timelimit = $1; 
 8288:                         my $first_access;
 8289:                         if ($type eq 'resource') {
 8290:                             $first_access=&get_first_access($interval[1],$item);
 8291:                         } elsif ($type eq 'map') {
 8292:                             $first_access=&get_first_access($interval[1],undef,$item);
 8293:                         } else {
 8294:                             $first_access=&get_first_access($interval[1]);
 8295:                         }
 8296:                         if ($first_access) {
 8297:                             my $timesup = $first_access+$timelimit;
 8298:                             if ($timesup > $now) {
 8299:                                 my $activeblock;
 8300:                                 foreach my $res (@to_test) {
 8301:                                     if ($res->answerable()) {
 8302:                                         $activeblock = 1;
 8303:                                         last;
 8304:                                     }
 8305:                                 }
 8306:                                 if ($activeblock) {
 8307:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8308:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8309:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8310:                                          }
 8311:                                     }
 8312:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8313:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8314:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8315:                                         }
 8316:                                     }
 8317:                                 }
 8318:                             }
 8319:                         }
 8320:                     }
 8321:                 }
 8322:             }
 8323:         }
 8324:     }
 8325:     return %blockers;
 8326: }
 8327: 
 8328: sub has_comm_blocking {
 8329:     my ($priv,$symb,$uri,$blocks) = @_;
 8330:     my @blockers;
 8331:     return unless ($env{'request.course.id'});
 8332:     return unless ($priv eq 'bre');
 8333:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8334:     return if ($env{'request.state'} eq 'construct');
 8335:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8336:     return unless (keys(%cachedblockers) > 0);
 8337:     my (%possibles,@symbs);
 8338:     if (!$symb) {
 8339:         $symb = &symbread($uri,1,1,1,\%possibles);
 8340:     }
 8341:     if ($symb) {
 8342:         @symbs = ($symb);
 8343:     } elsif (keys(%possibles)) { 
 8344:         @symbs = keys(%possibles);
 8345:     }
 8346:     my $noblock;
 8347:     foreach my $symb (@symbs) {
 8348:         last if ($noblock);
 8349:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8350:         foreach my $block (keys(%cachedblockers)) {
 8351:             if ($block =~ /^firstaccess____(.+)$/) {
 8352:                 my $item = $1;
 8353:                 if (($item eq $map) || ($item eq $symb)) {
 8354:                     $noblock = 1;
 8355:                     last;
 8356:                 }
 8357:             }
 8358:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8359:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8360:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8361:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8362:                             push(@blockers,$block);
 8363:                         }
 8364:                     }
 8365:                 }
 8366:             }
 8367:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8368:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8369:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8370:                         push(@blockers,$block);
 8371:                     }
 8372:                 }
 8373:             }
 8374:         }
 8375:     }
 8376:     return if ($noblock);
 8377:     return @blockers;
 8378: }
 8379: }
 8380: 
 8381: # -------------------------------- Deversion and split uri into path an filename   
 8382: 
 8383: #
 8384: #   Removes the version from a URI and
 8385: #   splits it in to its filename and path to the filename.
 8386: #   Seems like File::Basename could have done this more clearly.
 8387: #   Parameters:
 8388: #      $uri   - input URI
 8389: #   Returns:
 8390: #     Two element list consisting of 
 8391: #     $pathname  - the URI up to and excluding the trailing /
 8392: #     $filename  - The part of the URI following the last /
 8393: #  NOTE:
 8394: #    Another realization of this is simply:
 8395: #    use File::Basename;
 8396: #    ...
 8397: #    $uri = shift;
 8398: #    $filename = basename($uri);
 8399: #    $path     = dirname($uri);
 8400: #    return ($filename, $path);
 8401: #
 8402: #     The implementation below is probably faster however.
 8403: #
 8404: sub split_uri_for_cond {
 8405:     my $uri=&deversion(&declutter(shift));
 8406:     my @uriparts=split(/\//,$uri);
 8407:     my $filename=pop(@uriparts);
 8408:     my $pathname=join('/',@uriparts);
 8409:     return ($pathname,$filename);
 8410: }
 8411: # --------------------------------------------------- Is a resource on the map?
 8412: 
 8413: sub is_on_map {
 8414:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8415:     #Trying to find the conditional for the file
 8416:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8417: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8418:     if ($match) {
 8419: 	return (1,$1);
 8420:     } else {
 8421: 	return (0,0);
 8422:     }
 8423: }
 8424: 
 8425: # --------------------------------------------------------- Get symb from alias
 8426: 
 8427: sub get_symb_from_alias {
 8428:     my $symb=shift;
 8429:     my ($map,$resid,$url)=&decode_symb($symb);
 8430: # Already is a symb
 8431:     if ($url) { return $symb; }
 8432: # Must be an alias
 8433:     my $aliassymb='';
 8434:     my %bighash;
 8435:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8436:                             &GDBM_READER(),0640)) {
 8437:         my $rid=$bighash{'mapalias_'.$symb};
 8438: 	if ($rid) {
 8439: 	    my ($mapid,$resid)=split(/\./,$rid);
 8440: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8441: 				    $resid,$bighash{'src_'.$rid});
 8442: 	}
 8443:         untie %bighash;
 8444:     }
 8445:     return $aliassymb;
 8446: }
 8447: 
 8448: # ----------------------------------------------------------------- Define Role
 8449: 
 8450: sub definerole {
 8451:   if (allowed('mcr','/')) {
 8452:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8453:     foreach my $role (split(':',$sysrole)) {
 8454: 	my ($crole,$cqual)=split(/\&/,$role);
 8455:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8456:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8457: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8458:                return "refused:s:$crole&$cqual"; 
 8459:             }
 8460:         }
 8461:     }
 8462:     foreach my $role (split(':',$domrole)) {
 8463: 	my ($crole,$cqual)=split(/\&/,$role);
 8464:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8465:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8466: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8467:                return "refused:d:$crole&$cqual"; 
 8468:             }
 8469:         }
 8470:     }
 8471:     foreach my $role (split(':',$courole)) {
 8472: 	my ($crole,$cqual)=split(/\&/,$role);
 8473:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8474:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8475: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8476:                return "refused:c:$crole&$cqual"; 
 8477:             }
 8478:         }
 8479:     }
 8480:     my $uhome;
 8481:     if (($uname ne '') && ($udom ne '')) {
 8482:         $uhome = &homeserver($uname,$udom);
 8483:         return $uhome if ($uhome eq 'no_host');
 8484:     } else {
 8485:         $uname = $env{'user.name'};
 8486:         $udom = $env{'user.domain'};
 8487:         $uhome = $env{'user.home'};
 8488:     }
 8489:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8490:                 "$udom:$uname:rolesdef_$rolename=".
 8491:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8492:     return reply($command,$uhome);
 8493:   } else {
 8494:     return 'refused';
 8495:   }
 8496: }
 8497: 
 8498: # ---------------- Make a metadata query against the network of library servers
 8499: 
 8500: sub metadata_query {
 8501:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8502:     my %rhash;
 8503:     my %libserv = &all_library();
 8504:     my @server_list = (defined($server_array) ? @$server_array
 8505:                                               : keys(%libserv) );
 8506:     for my $server (@server_list) {
 8507:         my $domains = ''; 
 8508:         if (ref($domains_hash) eq 'HASH') {
 8509:             $domains = $domains_hash->{$server}; 
 8510:         }
 8511: 	unless ($custom or $customshow) {
 8512: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8513: 	    $rhash{$server}=$reply;
 8514: 	}
 8515: 	else {
 8516: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8517: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8518: 			     $server);
 8519: 	    $rhash{$server}=$reply;
 8520: 	}
 8521:     }
 8522:     return \%rhash;
 8523: }
 8524: 
 8525: # ----------------------------------------- Send log queries and wait for reply
 8526: 
 8527: sub log_query {
 8528:     my ($uname,$udom,$query,%filters)=@_;
 8529:     my $uhome=&homeserver($uname,$udom);
 8530:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8531:     my $uhost=&hostname($uhome);
 8532:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8533:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8534:                        $uhome);
 8535:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8536:     return get_query_reply($queryid);
 8537: }
 8538: 
 8539: # -------------------------- Update MySQL table for portfolio file
 8540: 
 8541: sub update_portfolio_table {
 8542:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8543:     if ($group ne '') {
 8544:         $file_name =~s /^\Q$group\E//;
 8545:     }
 8546:     my $homeserver = &homeserver($uname,$udom);
 8547:     my $queryid=
 8548:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8549:                ':'.&escape($file_name).':'.$action,$homeserver);
 8550:     my $reply = &get_query_reply($queryid);
 8551:     return $reply;
 8552: }
 8553: 
 8554: # -------------------------- Update MySQL allusers table
 8555: 
 8556: sub update_allusers_table {
 8557:     my ($uname,$udom,$names) = @_;
 8558:     my $homeserver = &homeserver($uname,$udom);
 8559:     my $queryid=
 8560:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8561:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8562:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8563:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8564:                'generation='.&escape($names->{'generation'}).'%%'.
 8565:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8566:                'id='.&escape($names->{'id'}),$homeserver);
 8567:     return;
 8568: }
 8569: 
 8570: # ------- Request retrieval of institutional classlists for course(s)
 8571: 
 8572: sub fetch_enrollment_query {
 8573:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8574:     my ($homeserver,$sleep,$loopmax);
 8575:     my $maxtries = 1;
 8576:     if ($context eq 'automated') {
 8577:         $homeserver = $perlvar{'lonHostID'};
 8578:         $sleep = 2;
 8579:         $loopmax = 100;
 8580:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8581:     } else {
 8582:         $homeserver = &homeserver($cnum,$dom);
 8583:     }
 8584:     my $host=&hostname($homeserver);
 8585:     my $cmd = '';
 8586:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8587:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8588:     }
 8589:     $cmd =~ s/%%$//;
 8590:     $cmd = &escape($cmd);
 8591:     my $query = 'fetchenrollment';
 8592:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8593:     unless ($queryid=~/^\Q$host\E\_/) { 
 8594:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8595:         return 'error: '.$queryid;
 8596:     }
 8597:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8598:     my $tries = 1;
 8599:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8600:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8601:         $tries ++;
 8602:     }
 8603:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8604:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8605:     } else {
 8606:         my @responses = split(/:/,$reply);
 8607:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8608:             foreach my $line (@responses) {
 8609:                 my ($key,$value) = split(/=/,$line,2);
 8610:                 $$replyref{$key} = $value;
 8611:             }
 8612:         } else {
 8613:             my $pathname = LONCAPA::tempdir();
 8614:             foreach my $line (@responses) {
 8615:                 my ($key,$value) = split(/=/,$line);
 8616:                 $$replyref{$key} = $value;
 8617:                 if ($value > 0) {
 8618:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8619:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8620:                         my $destname = $pathname.'/'.$filename;
 8621:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8622:                         if ($xml_classlist =~ /^error/) {
 8623:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8624:                         } else {
 8625:                             if ( open(FILE,">",$destname) ) {
 8626:                                 print FILE &unescape($xml_classlist);
 8627:                                 close(FILE);
 8628:                             } else {
 8629:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8630:                             }
 8631:                         }
 8632:                     }
 8633:                 }
 8634:             }
 8635:         }
 8636:         return 'ok';
 8637:     }
 8638:     return 'error';
 8639: }
 8640: 
 8641: sub get_query_reply {
 8642:     my ($queryid,$sleep,$loopmax) = @_;;
 8643:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8644:         $sleep = 0.2;
 8645:     }
 8646:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8647:         $loopmax = 100;
 8648:     }
 8649:     my $replyfile=LONCAPA::tempdir().$queryid;
 8650:     my $reply='';
 8651:     for (1..$loopmax) {
 8652: 	sleep($sleep);
 8653:         if (-e $replyfile.'.end') {
 8654: 	    if (open(my $fh,"<",$replyfile)) {
 8655: 		$reply = join('',<$fh>);
 8656: 		close($fh);
 8657: 	   } else { return 'error: reply_file_error'; }
 8658:            return &unescape($reply);
 8659: 	}
 8660:     }
 8661:     return 'timeout:'.$queryid;
 8662: }
 8663: 
 8664: sub courselog_query {
 8665: #
 8666: # possible filters:
 8667: # url: url or symb
 8668: # username
 8669: # domain
 8670: # action: view, submit, grade
 8671: # start: timestamp
 8672: # end: timestamp
 8673: #
 8674:     my (%filters)=@_;
 8675:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8676:     if ($filters{'url'}) {
 8677: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8678:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8679:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8680:     }
 8681:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8682:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8683:     return &log_query($cname,$cdom,'courselog',%filters);
 8684: }
 8685: 
 8686: sub userlog_query {
 8687: #
 8688: # possible filters:
 8689: # action: log check role
 8690: # start: timestamp
 8691: # end: timestamp
 8692: #
 8693:     my ($uname,$udom,%filters)=@_;
 8694:     return &log_query($uname,$udom,'userlog',%filters);
 8695: }
 8696: 
 8697: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8698: 
 8699: sub auto_run {
 8700:     my ($cnum,$cdom) = @_;
 8701:     my $response = 0;
 8702:     my $settings;
 8703:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8704:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8705:         $settings = $domconfig{'autoenroll'};
 8706:         if ($settings->{'run'} eq '1') {
 8707:             $response = 1;
 8708:         }
 8709:     } else {
 8710:         my $homeserver;
 8711:         if (&is_course($cdom,$cnum)) {
 8712:             $homeserver = &homeserver($cnum,$cdom);
 8713:         } else {
 8714:             $homeserver = &domain($cdom,'primary');
 8715:         }
 8716:         if ($homeserver ne 'no_host') {
 8717:             $response = &reply('autorun:'.$cdom,$homeserver);
 8718:         }
 8719:     }
 8720:     return $response;
 8721: }
 8722: 
 8723: sub auto_get_sections {
 8724:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8725:     my $homeserver;
 8726:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8727:         $homeserver = &homeserver($cnum,$cdom);
 8728:     }
 8729:     if (!defined($homeserver)) { 
 8730:         if ($cdom =~ /^$match_domain$/) {
 8731:             $homeserver = &domain($cdom,'primary');
 8732:         }
 8733:     }
 8734:     my @secs;
 8735:     if (defined($homeserver)) {
 8736:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8737:         unless ($response eq 'refused') {
 8738:             @secs = split(/:/,$response);
 8739:         }
 8740:     }
 8741:     return @secs;
 8742: }
 8743: 
 8744: sub auto_new_course {
 8745:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8746:     my $homeserver = &homeserver($cnum,$cdom);
 8747:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8748:     return $response;
 8749: }
 8750: 
 8751: sub auto_validate_courseID {
 8752:     my ($cnum,$cdom,$inst_course_id) = @_;
 8753:     my $homeserver = &homeserver($cnum,$cdom);
 8754:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8755:     return $response;
 8756: }
 8757: 
 8758: sub auto_validate_instcode {
 8759:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8760:     my ($homeserver,$response);
 8761:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8762:         $homeserver = &homeserver($cnum,$cdom);
 8763:     }
 8764:     if (!defined($homeserver)) {
 8765:         if ($cdom =~ /^$match_domain$/) {
 8766:             $homeserver = &domain($cdom,'primary');
 8767:         }
 8768:     }
 8769:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8770:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8771:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8772:     return ($outcome,$description,$defaultcredits);
 8773: }
 8774: 
 8775: sub auto_create_password {
 8776:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8777:     my ($homeserver,$response);
 8778:     my $create_passwd = 0;
 8779:     my $authchk = '';
 8780:     if ($udom =~ /^$match_domain$/) {
 8781:         $homeserver = &domain($udom,'primary');
 8782:     }
 8783:     if ($homeserver eq '') {
 8784:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8785:             $homeserver = &homeserver($cnum,$cdom);
 8786:         }
 8787:     }
 8788:     if ($homeserver eq '') {
 8789:         $authchk = 'nodomain';
 8790:     } else {
 8791:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8792:         if ($response eq 'refused') {
 8793:             $authchk = 'refused';
 8794:         } else {
 8795:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8796:         }
 8797:     }
 8798:     return ($authparam,$create_passwd,$authchk);
 8799: }
 8800: 
 8801: sub auto_photo_permission {
 8802:     my ($cnum,$cdom,$students) = @_;
 8803:     my $homeserver = &homeserver($cnum,$cdom);
 8804:     my ($outcome,$perm_reqd,$conditions) = 
 8805: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8806:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8807: 	return (undef,undef);
 8808:     }
 8809:     return ($outcome,$perm_reqd,$conditions);
 8810: }
 8811: 
 8812: sub auto_checkphotos {
 8813:     my ($uname,$udom,$pid) = @_;
 8814:     my $homeserver = &homeserver($uname,$udom);
 8815:     my ($result,$resulttype);
 8816:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8817: 				   &escape($uname).':'.&escape($pid),
 8818: 				   $homeserver));
 8819:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8820: 	return (undef,undef);
 8821:     }
 8822:     if ($outcome) {
 8823:         ($result,$resulttype) = split(/:/,$outcome);
 8824:     } 
 8825:     return ($result,$resulttype);
 8826: }
 8827: 
 8828: sub auto_photochoice {
 8829:     my ($cnum,$cdom) = @_;
 8830:     my $homeserver = &homeserver($cnum,$cdom);
 8831:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8832: 						       &escape($cdom),
 8833: 						       $homeserver)));
 8834:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8835: 	return (undef,undef);
 8836:     }
 8837:     return ($update,$comment);
 8838: }
 8839: 
 8840: sub auto_photoupdate {
 8841:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8842:     my $homeserver = &homeserver($cnum,$dom);
 8843:     my $host=&hostname($homeserver);
 8844:     my $cmd = '';
 8845:     my $maxtries = 1;
 8846:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8847:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8848:     }
 8849:     $cmd =~ s/%%$//;
 8850:     $cmd = &escape($cmd);
 8851:     my $query = 'institutionalphotos';
 8852:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8853:     unless ($queryid=~/^\Q$host\E\_/) {
 8854:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8855:         return 'error: '.$queryid;
 8856:     }
 8857:     my $reply = &get_query_reply($queryid);
 8858:     my $tries = 1;
 8859:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8860:         $reply = &get_query_reply($queryid);
 8861:         $tries ++;
 8862:     }
 8863:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8864:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8865:     } else {
 8866:         my @responses = split(/:/,$reply);
 8867:         my $outcome = shift(@responses); 
 8868:         foreach my $item (@responses) {
 8869:             my ($key,$value) = split(/=/,$item);
 8870:             $$photo{$key} = $value;
 8871:         }
 8872:         return $outcome;
 8873:     }
 8874:     return 'error';
 8875: }
 8876: 
 8877: sub auto_instcode_format {
 8878:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8879: 	$cat_order) = @_;
 8880:     my $courses = '';
 8881:     my @homeservers;
 8882:     if ($caller eq 'global') {
 8883: 	my %servers = &get_servers($codedom,'library');
 8884: 	foreach my $tryserver (keys(%servers)) {
 8885: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8886: 		push(@homeservers,$tryserver);
 8887: 	    }
 8888:         }
 8889:     } elsif ($caller eq 'requests') {
 8890:         if ($codedom =~ /^$match_domain$/) {
 8891:             my $chome = &domain($codedom,'primary');
 8892:             unless ($chome eq 'no_host') {
 8893:                 push(@homeservers,$chome);
 8894:             }
 8895:         }
 8896:     } else {
 8897:         push(@homeservers,&homeserver($caller,$codedom));
 8898:     }
 8899:     foreach my $code (keys(%{$instcodes})) {
 8900:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8901:     }
 8902:     chop($courses);
 8903:     my $ok_response = 0;
 8904:     my $response;
 8905:     while (@homeservers > 0 && $ok_response == 0) {
 8906:         my $server = shift(@homeservers); 
 8907:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8908:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8909:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8910: 		split(/:/,$response);
 8911:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8912:             push(@{$codetitles},&str2array($codetitles_str));
 8913:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8914:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8915:             $ok_response = 1;
 8916:         }
 8917:     }
 8918:     if ($ok_response) {
 8919:         return 'ok';
 8920:     } else {
 8921:         return $response;
 8922:     }
 8923: }
 8924: 
 8925: sub auto_instcode_defaults {
 8926:     my ($domain,$returnhash,$code_order) = @_;
 8927:     my @homeservers;
 8928: 
 8929:     my %servers = &get_servers($domain,'library');
 8930:     foreach my $tryserver (keys(%servers)) {
 8931: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8932: 	    push(@homeservers,$tryserver);
 8933: 	}
 8934:     }
 8935: 
 8936:     my $response;
 8937:     foreach my $server (@homeservers) {
 8938:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8939:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8940: 	
 8941: 	foreach my $pair (split(/\&/,$response)) {
 8942: 	    my ($name,$value)=split(/\=/,$pair);
 8943: 	    if ($name eq 'code_order') {
 8944: 		@{$code_order} = split(/\&/,&unescape($value));
 8945: 	    } else {
 8946: 		$returnhash->{&unescape($name)}=&unescape($value);
 8947: 	    }
 8948: 	}
 8949: 	return 'ok';
 8950:     }
 8951: 
 8952:     return $response;
 8953: }
 8954: 
 8955: sub auto_possible_instcodes {
 8956:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8957:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8958:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8959:         return;
 8960:     }
 8961:     my (@homeservers,$uhome);
 8962:     if (defined(&domain($domain,'primary'))) {
 8963:         $uhome=&domain($domain,'primary');
 8964:         push(@homeservers,&domain($domain,'primary'));
 8965:     } else {
 8966:         my %servers = &get_servers($domain,'library');
 8967:         foreach my $tryserver (keys(%servers)) {
 8968:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8969:                 push(@homeservers,$tryserver);
 8970:             }
 8971:         }
 8972:     }
 8973:     my $response;
 8974:     foreach my $server (@homeservers) {
 8975:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8976:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8977:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8978:             split(':',$response);
 8979:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8980:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8981:         foreach my $item (split('&',$cat_title)) {   
 8982:             my ($name,$value)=split('=',$item);
 8983:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8984:         }
 8985:         foreach my $item (split('&',$cat_order)) {
 8986:             my ($name,$value)=split('=',$item);
 8987:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8988:         }
 8989:         return 'ok';
 8990:     }
 8991:     return $response;
 8992: }
 8993: 
 8994: sub auto_courserequest_checks {
 8995:     my ($dom) = @_;
 8996:     my ($homeserver,%validations);
 8997:     if ($dom =~ /^$match_domain$/) {
 8998:         $homeserver = &domain($dom,'primary');
 8999:     }
 9000:     unless ($homeserver eq 'no_host') {
 9001:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9002:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9003:             my @items = split(/&/,$response);
 9004:             foreach my $item (@items) {
 9005:                 my ($key,$value) = split('=',$item);
 9006:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9007:             }
 9008:         }
 9009:     }
 9010:     return %validations; 
 9011: }
 9012: 
 9013: sub auto_courserequest_validation {
 9014:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9015:     my ($homeserver,$response);
 9016:     if ($dom =~ /^$match_domain$/) {
 9017:         $homeserver = &domain($dom,'primary');
 9018:     }
 9019:     unless ($homeserver eq 'no_host') {
 9020:         my $customdata;
 9021:         if (ref($custominfo) eq 'HASH') {
 9022:             $customdata = &freeze_escape($custominfo);
 9023:         }
 9024:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9025:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9026:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9027:                                     $customdata,$homeserver));
 9028:     }
 9029:     return $response;
 9030: }
 9031: 
 9032: sub auto_validate_class_sec {
 9033:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9034:     my $homeserver = &homeserver($cnum,$cdom);
 9035:     my $ownerlist;
 9036:     if (ref($owners) eq 'ARRAY') {
 9037:         $ownerlist = join(',',@{$owners});
 9038:     } else {
 9039:         $ownerlist = $owners;
 9040:     }
 9041:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9042:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9043:     return $response;
 9044: }
 9045: 
 9046: sub auto_validate_instclasses {
 9047:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9048:     my ($homeserver,%validations);
 9049:     $homeserver = &homeserver($cnum,$cdom);
 9050:     unless ($homeserver eq 'no_host') {
 9051:         my $ownerlist;
 9052:         if (ref($owners) eq 'ARRAY') {
 9053:             $ownerlist = join(',',@{$owners});
 9054:         } else {
 9055:             $ownerlist = $owners;
 9056:         }
 9057:         if (ref($classesref) eq 'HASH') {
 9058:             my $classes = &freeze_escape($classesref);
 9059:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9060:                                 ':'.$cdom.':'.$classes,$homeserver);
 9061:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9062:                 my @items = split(/&/,$response);
 9063:                 foreach my $item (@items) {
 9064:                     my ($key,$value) = split('=',$item);
 9065:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9066:                 }
 9067:             }
 9068:         }
 9069:     }
 9070:     return %validations;
 9071: }
 9072: 
 9073: sub auto_crsreq_update {
 9074:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9075:         $code,$accessstart,$accessend,$inbound) = @_;
 9076:     my ($homeserver,%crsreqresponse);
 9077:     if ($cdom =~ /^$match_domain$/) {
 9078:         $homeserver = &domain($cdom,'primary');
 9079:     }
 9080:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9081:         my $info;
 9082:         if (ref($inbound) eq 'HASH') {
 9083:             $info = &freeze_escape($inbound);
 9084:         }
 9085:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9086:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9087:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9088:                             &escape($title).':'.&escape($code).':'.
 9089:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9090:                             $homeserver);
 9091:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9092:             my @items = split(/&/,$response);
 9093:             foreach my $item (@items) {
 9094:                 my ($key,$value) = split('=',$item);
 9095:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9096:             }
 9097:         }
 9098:     }
 9099:     return \%crsreqresponse;
 9100: }
 9101: 
 9102: sub auto_export_grades {
 9103:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9104:     my ($homeserver,%exportresponse);
 9105:     if ($cdom =~ /^$match_domain$/) {
 9106:         $homeserver = &domain($cdom,'primary');
 9107:     }
 9108:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9109:         my $info;
 9110:         if (ref($inforef) eq 'HASH') {
 9111:             $info = &freeze_escape($inforef);
 9112:         }
 9113:         if (ref($gradesref) eq 'HASH') {
 9114:             my $grades = &freeze_escape($gradesref);
 9115:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9116:                                 $info.':'.$grades,$homeserver);
 9117:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9118:                 my @items = split(/&/,$response);
 9119:                 foreach my $item (@items) {
 9120:                     my ($key,$value) = split('=',$item);
 9121:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9122:                 }
 9123:             }
 9124:         }
 9125:     }
 9126:     return \%exportresponse;
 9127: }
 9128: 
 9129: sub check_instcode_cloning {
 9130:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9131:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9132:         return;
 9133:     }
 9134:     my $canclone;
 9135:     if (@{$code_order} > 0) {
 9136:         my $instcoderegexp ='^';
 9137:         my @clonecodes = split(/\&/,$cloner);
 9138:         foreach my $item (@{$code_order}) {
 9139:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9140:                 foreach my $pair (@clonecodes) {
 9141:                     my ($key,$val) = split(/\=/,$pair,2);
 9142:                     $val = &unescape($val);
 9143:                     if ($key eq $item) {
 9144:                         $instcoderegexp .= '('.$val.')';
 9145:                         last;
 9146:                     }
 9147:                 }
 9148:             } else {
 9149:                 $instcoderegexp .= $codedefaults->{$item};
 9150:             }
 9151:         }
 9152:         $instcoderegexp .= '$';
 9153:         my (@from,@to);
 9154:         eval {
 9155:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9156:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9157:         };
 9158:         if ((@from > 0) && (@to > 0)) {
 9159:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9160:             if (!@diffs) {
 9161:                 $canclone = 1;
 9162:             }
 9163:         }
 9164:     }
 9165:     return $canclone;
 9166: }
 9167: 
 9168: sub default_instcode_cloning {
 9169:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9170:     my (%codedefaults,@code_order,$canclone);
 9171:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9172:         %codedefaults = %{$codedefaultsref};
 9173:         @code_order = @{$codeorderref};
 9174:     } elsif ($clonedom) {
 9175:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9176:     }
 9177:     if (($domdefclone) && (@code_order)) {
 9178:         my @clonecodes = split(/\+/,$domdefclone);
 9179:         my $instcoderegexp ='^';
 9180:         foreach my $item (@code_order) {
 9181:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9182:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9183:             } else {
 9184:                 $instcoderegexp .= $codedefaults{$item};
 9185:             }
 9186:         }
 9187:         $instcoderegexp .= '$';
 9188:         my (@from,@to);
 9189:         eval {
 9190:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9191:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9192:         };
 9193:         if ((@from > 0) && (@to > 0)) {
 9194:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9195:             if (!@diffs) {
 9196:                 $canclone = 1;
 9197:             }
 9198:         }
 9199:     }
 9200:     return $canclone;
 9201: }
 9202: 
 9203: # ------------------------------------------------------- Course Group routines
 9204: 
 9205: sub get_coursegroups {
 9206:     my ($cdom,$cnum,$group,$namespace) = @_;
 9207:     return(&dump($namespace,$cdom,$cnum,$group));
 9208: }
 9209: 
 9210: sub modify_coursegroup {
 9211:     my ($cdom,$cnum,$groupsettings) = @_;
 9212:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9213: }
 9214: 
 9215: sub toggle_coursegroup_status {
 9216:     my ($cdom,$cnum,$group,$action) = @_;
 9217:     my ($from_namespace,$to_namespace);
 9218:     if ($action eq 'delete') {
 9219:         $from_namespace = 'coursegroups';
 9220:         $to_namespace = 'deleted_groups';
 9221:     } else {
 9222:         $from_namespace = 'deleted_groups';
 9223:         $to_namespace = 'coursegroups';
 9224:     }
 9225:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9226:     if (my $tmp = &error(%curr_group)) {
 9227:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9228:         return ('read error',$tmp);
 9229:     } else {
 9230:         my %savedsettings = %curr_group; 
 9231:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9232:         my $deloutcome;
 9233:         if ($result eq 'ok') {
 9234:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9235:         } else {
 9236:             return ('write error',$result);
 9237:         }
 9238:         if ($deloutcome eq 'ok') {
 9239:             return 'ok';
 9240:         } else {
 9241:             return ('delete error',$deloutcome);
 9242:         }
 9243:     }
 9244: }
 9245: 
 9246: sub modify_group_roles {
 9247:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9248:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9249:     my $role = 'gr/'.&escape($userprivs);
 9250:     my ($uname,$udom) = split(/:/,$user);
 9251:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9252:     if ($result eq 'ok') {
 9253:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9254:     }
 9255:     return $result;
 9256: }
 9257: 
 9258: sub modify_coursegroup_membership {
 9259:     my ($cdom,$cnum,$membership) = @_;
 9260:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9261:     return $result;
 9262: }
 9263: 
 9264: sub get_active_groups {
 9265:     my ($udom,$uname,$cdom,$cnum) = @_;
 9266:     my $now = time;
 9267:     my %groups = ();
 9268:     foreach my $key (keys(%env)) {
 9269:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9270:             my ($start,$end) = split(/\./,$env{$key});
 9271:             if (($end!=0) && ($end<$now)) { next; }
 9272:             if (($start!=0) && ($start>$now)) { next; }
 9273:             if ($1 eq $cdom && $2 eq $cnum) {
 9274:                 $groups{$3} = $env{$key} ;
 9275:             }
 9276:         }
 9277:     }
 9278:     return %groups;
 9279: }
 9280: 
 9281: sub get_group_membership {
 9282:     my ($cdom,$cnum,$group) = @_;
 9283:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9284: }
 9285: 
 9286: sub get_users_groups {
 9287:     my ($udom,$uname,$courseid) = @_;
 9288:     my @usersgroups;
 9289:     my $cachetime=1800;
 9290: 
 9291:     my $hashid="$udom:$uname:$courseid";
 9292:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9293:     if (defined($cached)) {
 9294:         @usersgroups = split(/:/,$grouplist);
 9295:     } else {  
 9296:         $grouplist = '';
 9297:         my $courseurl = &courseid_to_courseurl($courseid);
 9298:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9299:         my $access_end = $env{'course.'.$courseid.
 9300:                               '.default_enrollment_end_date'};
 9301:         my $now = time;
 9302:         foreach my $key (keys(%roleshash)) {
 9303:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9304:                 my $group = $1;
 9305:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9306:                     my $start = $2;
 9307:                     my $end = $1;
 9308:                     if ($start == -1) { next; } # deleted from group
 9309:                     if (($start!=0) && ($start>$now)) { next; }
 9310:                     if (($end!=0) && ($end<$now)) {
 9311:                         if ($access_end && $access_end < $now) {
 9312:                             if ($access_end - $end < 86400) {
 9313:                                 push(@usersgroups,$group);
 9314:                             }
 9315:                         }
 9316:                         next;
 9317:                     }
 9318:                     push(@usersgroups,$group);
 9319:                 }
 9320:             }
 9321:         }
 9322:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9323:         $grouplist = join(':',@usersgroups);
 9324:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9325:     }
 9326:     return @usersgroups;
 9327: }
 9328: 
 9329: sub devalidate_getgroups_cache {
 9330:     my ($udom,$uname,$cdom,$cnum)=@_;
 9331:     my $courseid = $cdom.'_'.$cnum;
 9332: 
 9333:     my $hashid="$udom:$uname:$courseid";
 9334:     &devalidate_cache_new('getgroups',$hashid);
 9335: }
 9336: 
 9337: # ------------------------------------------------------------------ Plain Text
 9338: 
 9339: sub plaintext {
 9340:     my ($short,$type,$cid,$forcedefault) = @_;
 9341:     if ($short =~ m{^cr/}) {
 9342: 	return (split('/',$short))[-1];
 9343:     }
 9344:     if (!defined($cid)) {
 9345:         $cid = $env{'request.course.id'};
 9346:     }
 9347:     my %rolenames = (
 9348:                       Course    => 'std',
 9349:                       Community => 'alt1',
 9350:                       Placement => 'std',
 9351:                     );
 9352:     if ($cid ne '') {
 9353:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9354:             unless ($forcedefault) {
 9355:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9356:                 &Apache::lonlocal::mt_escape(\$roletext);
 9357:                 return &Apache::lonlocal::mt($roletext);
 9358:             }
 9359:         }
 9360:     }
 9361:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9362:         (defined($rolenames{$type})) && 
 9363:         (defined($prp{$short}{$rolenames{$type}}))) {
 9364:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9365:     } elsif ($cid ne '') {
 9366:         my $crstype = $env{'course.'.$cid.'.type'};
 9367:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9368:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9369:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9370:         }
 9371:     }
 9372:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9373: }
 9374: 
 9375: # ----------------------------------------------------------------- Assign Role
 9376: 
 9377: sub assignrole {
 9378:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9379:         $context)=@_;
 9380:     my $mrole;
 9381:     if ($role =~ /^cr\//) {
 9382:         my $cwosec=$url;
 9383:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9384: 	unless (&allowed('ccr',$cwosec)) {
 9385:            my $refused = 1;
 9386:            if ($context eq 'requestcourses') {
 9387:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9388:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9389:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9390:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9391:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9392:                            if ($crsenv{'internal.courseowner'} eq
 9393:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9394:                                $refused = '';
 9395:                            }
 9396:                        }
 9397:                    }
 9398:                }
 9399:            }
 9400:            if ($refused) {
 9401:                &logthis('Refused custom assignrole: '.
 9402:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9403:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9404:                return 'refused';
 9405:            }
 9406:         }
 9407:         $mrole='cr';
 9408:     } elsif ($role =~ /^gr\//) {
 9409:         my $cwogrp=$url;
 9410:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9411:         unless (&allowed('mdg',$cwogrp)) {
 9412:             &logthis('Refused group assignrole: '.
 9413:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9414:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9415:             return 'refused';
 9416:         }
 9417:         $mrole='gr';
 9418:     } else {
 9419:         my $cwosec=$url;
 9420:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9421:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9422:             my $refused;
 9423:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9424:                 if (!(&allowed('c'.$role,$url))) {
 9425:                     $refused = 1;
 9426:                 }
 9427:             } else {
 9428:                 $refused = 1;
 9429:             }
 9430:             if ($refused) {
 9431:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9432:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9433:                     my %crsenv;
 9434:                     if ($role eq 'cc' || $role eq 'co') {
 9435:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9436:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9437:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9438:                                 if ($crsenv{'internal.courseowner'} eq 
 9439:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9440:                                     $refused = '';
 9441:                                 }
 9442:                             }
 9443:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9444:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9445:                                 if ($crsenv{'internal.courseowner'} eq 
 9446:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9447:                                     $refused = '';
 9448:                                 }
 9449:                             }
 9450:                         }
 9451:                     }
 9452:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9453:                     if ($role eq 'st') {
 9454:                         $refused = '';
 9455:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9456:                         $refused = '';
 9457:                     }
 9458:                 } elsif ($context eq 'requestcourses') {
 9459:                     my @possroles = ('st','ta','ep','in','cc','co');
 9460:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9461:                         my $wrongcc;
 9462:                         if ($cnum =~ /^$match_community$/) {
 9463:                             $wrongcc = 1 if ($role eq 'cc');
 9464:                         } else {
 9465:                             $wrongcc = 1 if ($role eq 'co');
 9466:                         }
 9467:                         unless ($wrongcc) {
 9468:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9469:                             if ($crsenv{'internal.courseowner'} eq 
 9470:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9471:                                 $refused = '';
 9472:                             }
 9473:                         }
 9474:                     }
 9475:                 } elsif ($context eq 'requestauthor') {
 9476:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9477:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9478:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9479:                             $refused = '';
 9480:                         } else {
 9481:                             my %domdefaults = &get_domain_defaults($udom);
 9482:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9483:                                 my $checkbystatus;
 9484:                                 if ($env{'user.adv'}) { 
 9485:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9486:                                     if ($disposition eq 'automatic') {
 9487:                                         $refused = '';
 9488:                                     } elsif ($disposition eq '') {
 9489:                                         $checkbystatus = 1;
 9490:                                     } 
 9491:                                 } else {
 9492:                                     $checkbystatus = 1;
 9493:                                 }
 9494:                                 if ($checkbystatus) {
 9495:                                     if ($env{'environment.inststatus'}) {
 9496:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9497:                                         foreach my $type (@inststatuses) {
 9498:                                             if (($type ne '') &&
 9499:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9500:                                                 $refused = '';
 9501:                                             }
 9502:                                         }
 9503:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9504:                                         $refused = '';
 9505:                                     }
 9506:                                 }
 9507:                             }
 9508:                         }
 9509:                     }
 9510:                 }
 9511:                 if ($refused) {
 9512:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9513:                              ' '.$role.' '.$end.' '.$start.' by '.
 9514: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9515:                     return 'refused';
 9516:                 }
 9517:             }
 9518:         } elsif ($role eq 'au') {
 9519:             if ($url ne '/'.$udom.'/') {
 9520:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9521:                          ' to assign author role for '.$uname.':'.$udom.
 9522:                          ' in domain: '.$url.' refused (wrong domain).');
 9523:                 return 'refused';
 9524:             }
 9525:         }
 9526:         $mrole=$role;
 9527:     }
 9528:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9529:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9530:     if ($end) { $command.='_'.$end; }
 9531:     if ($start) {
 9532: 	if ($end) { 
 9533:            $command.='_'.$start; 
 9534:         } else {
 9535:            $command.='_0_'.$start;
 9536:         }
 9537:     }
 9538:     my $origstart = $start;
 9539:     my $origend = $end;
 9540:     my $delflag;
 9541: # actually delete
 9542:     if ($deleteflag) {
 9543: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9544: # modify command to delete the role
 9545:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9546:                 "$udom:$uname:$url".'_'."$mrole";
 9547: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9548: # set start and finish to negative values for userrolelog
 9549:            $start=-1;
 9550:            $end=-1;
 9551:            $delflag = 1;
 9552:         }
 9553:     }
 9554: # send command
 9555:     my $answer=&reply($command,&homeserver($uname,$udom));
 9556: # log new user role if status is ok
 9557:     if ($answer eq 'ok') {
 9558: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9559:         if (($role eq 'cc') || ($role eq 'in') ||
 9560:             ($role eq 'ep') || ($role eq 'ad') ||
 9561:             ($role eq 'ta') || ($role eq 'st') ||
 9562:             ($role=~/^cr/) || ($role eq 'gr') ||
 9563:             ($role eq 'co')) {
 9564: # for course roles, perform group memberships changes triggered by role change.
 9565:             unless ($role =~ /^gr/) {
 9566:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9567:                                                  $origstart,$selfenroll,$context);
 9568:             }
 9569:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9570:                            $selfenroll,$context);
 9571:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9572:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9573:                  ($role eq 'da')) {
 9574:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9575:                            $context);
 9576:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9577:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9578:                              $context); 
 9579:         }
 9580:         if ($role eq 'cc') {
 9581:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9582:         }
 9583:     }
 9584:     return $answer;
 9585: }
 9586: 
 9587: sub autoupdate_coowners {
 9588:     my ($url,$end,$start,$uname,$udom) = @_;
 9589:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9590:     if (($cdom ne '') && ($cnum ne '')) {
 9591:         my $now = time;
 9592:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9593:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9594:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9595:             my $instcode = $coursehash{'internal.coursecode'};
 9596:             if ($instcode ne '') {
 9597:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9598:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9599:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9600:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9601:                         if ($result eq 'valid') {
 9602:                             if ($coursehash{'internal.co-owners'}) {
 9603:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9604:                                     push(@newcoowners,$coowner);
 9605:                                 }
 9606:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9607:                                     push(@newcoowners,$uname.':'.$udom);
 9608:                                 }
 9609:                                 @newcoowners = sort(@newcoowners);
 9610:                             } else {
 9611:                                 push(@newcoowners,$uname.':'.$udom);
 9612:                             }
 9613:                         } else {
 9614:                             if ($coursehash{'internal.co-owners'}) {
 9615:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9616:                                     unless ($coowner eq $uname.':'.$udom) {
 9617:                                         push(@newcoowners,$coowner);
 9618:                                     }
 9619:                                 }
 9620:                                 unless (@newcoowners > 0) {
 9621:                                     $delcoowners = 1;
 9622:                                     $coowners = '';
 9623:                                 }
 9624:                             }
 9625:                         }
 9626:                         if (@newcoowners || $delcoowners) {
 9627:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9628:                                             $delcoowners,@newcoowners);
 9629:                         }
 9630:                     }
 9631:                 }
 9632:             }
 9633:         }
 9634:     }
 9635: }
 9636: 
 9637: sub store_coowners {
 9638:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9639:     my $cid = $cdom.'_'.$cnum;
 9640:     my ($coowners,$delresult,$putresult);
 9641:     if (@newcoowners) {
 9642:         $coowners = join(',',@newcoowners);
 9643:         my %coownershash = (
 9644:                             'internal.co-owners' => $coowners,
 9645:                            );
 9646:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9647:         if ($putresult eq 'ok') {
 9648:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9649:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9650:             }
 9651:         }
 9652:     }
 9653:     if ($delcoowners) {
 9654:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9655:         if ($delresult eq 'ok') {
 9656:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9657:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9658:             }
 9659:         }
 9660:     }
 9661:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9662:         my %crsinfo =
 9663:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9664:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9665:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9666:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9667:         }
 9668:     }
 9669: }
 9670: 
 9671: # -------------------------------------------------- Modify user authentication
 9672: # Overrides without validation
 9673: 
 9674: sub modifyuserauth {
 9675:     my ($udom,$uname,$umode,$upass)=@_;
 9676:     my $uhome=&homeserver($uname,$udom);
 9677:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9678:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9679:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9680:              ' in domain '.$env{'request.role.domain'});  
 9681:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9682: 		     &escape($upass),$uhome);
 9683:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9684:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9685:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9686:     &log($udom,,$uname,$uhome,
 9687:         'Authentication changed by '.$env{'user.domain'}.', '.
 9688:                                      $env{'user.name'}.', '.$umode.
 9689:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9690:     unless ($reply eq 'ok') {
 9691:         &logthis('Authentication mode error: '.$reply);
 9692: 	return 'error: '.$reply;
 9693:     }   
 9694:     return 'ok';
 9695: }
 9696: 
 9697: # --------------------------------------------------------------- Modify a user
 9698: 
 9699: sub modifyuser {
 9700:     my ($udom,    $uname, $uid,
 9701:         $umode,   $upass, $first,
 9702:         $middle,  $last,  $gene,
 9703:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9704:     $udom= &LONCAPA::clean_domain($udom);
 9705:     $uname=&LONCAPA::clean_username($uname);
 9706:     my $showcandelete = 'none';
 9707:     if (ref($candelete) eq 'ARRAY') {
 9708:         if (@{$candelete} > 0) {
 9709:             $showcandelete = join(', ',@{$candelete});
 9710:         }
 9711:     }
 9712:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9713:              $umode.', '.$first.', '.$middle.', '.
 9714: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9715:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9716:                                      ' desiredhome not specified'). 
 9717:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9718:              ' in domain '.$env{'request.role.domain'});
 9719:     my $uhome=&homeserver($uname,$udom,'true');
 9720:     my $newuser;
 9721:     if ($uhome eq 'no_host') {
 9722:         $newuser = 1;
 9723:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9724:                 ($umode eq 'lti')) {
 9725:             return 'error: more information needed to create new user';
 9726:         }
 9727:     }
 9728: # ----------------------------------------------------------------- Create User
 9729:     if (($uhome eq 'no_host') && 
 9730: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9731:         my $unhome='';
 9732:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9733:             $unhome = $desiredhome;
 9734: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9735: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9736:         } else { # load balancing routine for determining $unhome
 9737:             my $loadm=10000000;
 9738: 	    my %servers = &get_servers($udom,'library');
 9739: 	    foreach my $tryserver (keys(%servers)) {
 9740: 		my $answer=reply('load',$tryserver);
 9741: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9742: 		    $loadm=$answer;
 9743: 		    $unhome=$tryserver;
 9744: 		}
 9745: 	    }
 9746:         }
 9747:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9748: 	    return 'error: unable to find a home server for '.$uname.
 9749:                    ' in domain '.$udom;
 9750:         }
 9751:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9752:                          &escape($upass),$unhome);
 9753: 	unless ($reply eq 'ok') {
 9754:             return 'error: '.$reply;
 9755:         }   
 9756:         $uhome=&homeserver($uname,$udom,'true');
 9757:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9758: 	    return 'error: unable verify users home machine.';
 9759:         }
 9760:     }   # End of creation of new user
 9761: # ---------------------------------------------------------------------- Add ID
 9762:     if ($uid) {
 9763:        $uid=~tr/A-Z/a-z/;
 9764:        my %uidhash=&idrget($udom,$uname);
 9765:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9766:          && (!$forceid)) {
 9767: 	  unless ($uid eq $uidhash{$uname}) {
 9768: 	      return 'error: user id "'.$uid.'" does not match '.
 9769:                   'current user id "'.$uidhash{$uname}.'".';
 9770:           }
 9771:        } else {
 9772: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9773:        }
 9774:     }
 9775: # -------------------------------------------------------------- Add names, etc
 9776:     my @tmp=&get('environment',
 9777: 		   ['firstname','middlename','lastname','generation','id',
 9778:                     'permanentemail','inststatus'],
 9779: 		   $udom,$uname);
 9780:     my (%names,%oldnames);
 9781:     if ($tmp[0] =~ m/^error:.*/) { 
 9782:         %names=(); 
 9783:     } else {
 9784:         %names = @tmp;
 9785:         %oldnames = %names;
 9786:     }
 9787: #
 9788: # If name, email and/or uid are blank (e.g., because an uploaded file
 9789: # of users did not contain them), do not overwrite existing values
 9790: # unless field is in $candelete array ref.  
 9791: #
 9792: 
 9793:     my @fields = ('firstname','middlename','lastname','generation',
 9794:                   'permanentemail','id');
 9795:     my %newvalues;
 9796:     if (ref($candelete) eq 'ARRAY') {
 9797:         foreach my $field (@fields) {
 9798:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9799:                 if ($field eq 'firstname') {
 9800:                     $names{$field} = $first;
 9801:                 } elsif ($field eq 'middlename') {
 9802:                     $names{$field} = $middle;
 9803:                 } elsif ($field eq 'lastname') {
 9804:                     $names{$field} = $last;
 9805:                 } elsif ($field eq 'generation') { 
 9806:                     $names{$field} = $gene;
 9807:                 } elsif ($field eq 'permanentemail') {
 9808:                     $names{$field} = $email;
 9809:                 } elsif ($field eq 'id') {
 9810:                     $names{$field}  = $uid;
 9811:                 }
 9812:             }
 9813:         }
 9814:     }
 9815:     if ($first)  { $names{'firstname'}  = $first; }
 9816:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9817:     if ($last)   { $names{'lastname'}   = $last; }
 9818:     if (defined($gene))   { $names{'generation'} = $gene; }
 9819:     if ($email) {
 9820:        $email=~s/[^\w\@\.\-\,]//gs;
 9821:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9822:     }
 9823:     if ($uid) { $names{'id'}  = $uid; }
 9824:     if (defined($inststatus)) {
 9825:         $names{'inststatus'} = '';
 9826:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9827:         if (ref($usertypes) eq 'HASH') {
 9828:             my @okstatuses; 
 9829:             foreach my $item (split(/:/,$inststatus)) {
 9830:                 if (defined($usertypes->{$item})) {
 9831:                     push(@okstatuses,$item);  
 9832:                 }
 9833:             }
 9834:             if (@okstatuses) {
 9835:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9836:             }
 9837:         }
 9838:     }
 9839:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9840:                  $umode.', '.$first.', '.$middle.', '.
 9841:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9842:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9843:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9844:     } else {
 9845:         $logmsg .= ' during self creation';
 9846:     }
 9847:     my $changed;
 9848:     if ($newuser) {
 9849:         $changed = 1;
 9850:     } else {
 9851:         foreach my $field (@fields) {
 9852:             if ($names{$field} ne $oldnames{$field}) {
 9853:                 $changed = 1;
 9854:                 last;
 9855:             }
 9856:         }
 9857:     }
 9858:     unless ($changed) {
 9859:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9860:         &logthis($logmsg);
 9861:         return 'ok';
 9862:     }
 9863:     my $reply = &put('environment', \%names, $udom,$uname);
 9864:     if ($reply ne 'ok') { 
 9865:         return 'error: '.$reply;
 9866:     }
 9867:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9868:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9869:     }
 9870:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9871:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9872:     $logmsg = 'Success modifying user '.$logmsg;
 9873:     &logthis($logmsg);
 9874:     return 'ok';
 9875: }
 9876: 
 9877: # -------------------------------------------------------------- Modify student
 9878: 
 9879: sub modifystudent {
 9880:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9881:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9882:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9883:     if (!$cid) {
 9884: 	unless ($cid=$env{'request.course.id'}) {
 9885: 	    return 'not_in_class';
 9886: 	}
 9887:     }
 9888: # --------------------------------------------------------------- Make the user
 9889:     my $reply=&modifyuser
 9890: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9891:          $desiredhome,$email,$inststatus);
 9892:     unless ($reply eq 'ok') { return $reply; }
 9893:     # This will cause &modify_student_enrollment to get the uid from the
 9894:     # student's environment
 9895:     $uid = undef if (!$forceid);
 9896:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9897:                                         $gene,$usec,$end,$start,$type,$locktype,
 9898:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9899:     return $reply;
 9900: }
 9901: 
 9902: sub modify_student_enrollment {
 9903:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9904:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9905:     my ($cdom,$cnum,$chome);
 9906:     if (!$cid) {
 9907: 	unless ($cid=$env{'request.course.id'}) {
 9908: 	    return 'not_in_class';
 9909: 	}
 9910: 	$cdom=$env{'course.'.$cid.'.domain'};
 9911: 	$cnum=$env{'course.'.$cid.'.num'};
 9912:     } else {
 9913: 	($cdom,$cnum)=split(/_/,$cid);
 9914:     }
 9915:     $chome=$env{'course.'.$cid.'.home'};
 9916:     if (!$chome) {
 9917: 	$chome=&homeserver($cnum,$cdom);
 9918:     }
 9919:     if (!$chome) { return 'unknown_course'; }
 9920:     # Make sure the user exists
 9921:     my $uhome=&homeserver($uname,$udom);
 9922:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9923: 	return 'error: no such user';
 9924:     }
 9925:     # Get student data if we were not given enough information
 9926:     if (!defined($first)  || $first  eq '' || 
 9927:         !defined($last)   || $last   eq '' || 
 9928:         !defined($uid)    || $uid    eq '' || 
 9929:         !defined($middle) || $middle eq '' || 
 9930:         !defined($gene)   || $gene   eq '') {
 9931:         # They did not supply us with enough data to enroll the student, so
 9932:         # we need to pick up more information.
 9933:         my %tmp = &get('environment',
 9934:                        ['firstname','middlename','lastname', 'generation','id']
 9935:                        ,$udom,$uname);
 9936: 
 9937:         #foreach my $key (keys(%tmp)) {
 9938:         #    &logthis("key $key = ".$tmp{$key});
 9939:         #}
 9940:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9941:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9942:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9943:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9944:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9945:     }
 9946:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9947:     my $user = "$uname:$udom";
 9948:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9949:     my $reply=cput('classlist',
 9950: 		   {$user => 
 9951: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9952: 		   $cdom,$cnum);
 9953:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9954:         &devalidate_getsection_cache($udom,$uname,$cid);
 9955:     } else { 
 9956: 	return 'error: '.$reply;
 9957:     }
 9958:     # Add student role to user
 9959:     my $uurl='/'.$cid;
 9960:     $uurl=~s/\_/\//g;
 9961:     if ($usec) {
 9962: 	$uurl.='/'.$usec;
 9963:     }
 9964:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9965:                              $selfenroll,$context);
 9966:     if ($result ne 'ok') {
 9967:         if ($old_entry{$user} ne '') {
 9968:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9969:         } else {
 9970:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9971:         }
 9972:     }
 9973:     return $result; 
 9974: }
 9975: 
 9976: sub format_name {
 9977:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9978:     my $name;
 9979:     if ($first ne 'lastname') {
 9980: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9981:     } else {
 9982: 	if ($lastname=~/\S/) {
 9983: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9984: 	    $name=~s/\s+,/,/;
 9985: 	} else {
 9986: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9987: 	}
 9988:     }
 9989:     $name=~s/^\s+//;
 9990:     $name=~s/\s+$//;
 9991:     $name=~s/\s+/ /g;
 9992:     return $name;
 9993: }
 9994: 
 9995: # ------------------------------------------------- Write to course preferences
 9996: 
 9997: sub writecoursepref {
 9998:     my ($courseid,%prefs)=@_;
 9999:     $courseid=~s/^\///;
10000:     $courseid=~s/\_/\//g;
10001:     my ($cdomain,$cnum)=split(/\//,$courseid);
10002:     my $chome=homeserver($cnum,$cdomain);
10003:     if (($chome eq '') || ($chome eq 'no_host')) { 
10004: 	return 'error: no such course';
10005:     }
10006:     my $cstring='';
10007:     foreach my $pref (keys(%prefs)) {
10008: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10009:     }
10010:     $cstring=~s/\&$//;
10011:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10012: }
10013: 
10014: # ---------------------------------------------------------- Make/modify course
10015: 
10016: sub createcourse {
10017:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10018:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10019:     $url=&declutter($url);
10020:     my $cid='';
10021:     if ($context eq 'requestcourses') {
10022:         my $can_create = 0;
10023:         my ($ownername,$ownerdom) = split(':',$course_owner);
10024:         if ($udom eq $ownerdom) {
10025:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10026:                                   $context)) {
10027:                 $can_create = 1;
10028:             }
10029:         } else {
10030:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10031:                                            $category);
10032:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10033:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10034:                 if (@curr > 0) {
10035:                     my @options = qw(approval validate autolimit);
10036:                     my $optregex = join('|',@options);
10037:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10038:                         $can_create = 1;
10039:                     }
10040:                 }
10041:             }
10042:         }
10043:         if ($can_create) {
10044:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10045:                 unless (&allowed('ccc',$udom)) {
10046:                     return 'refused'; 
10047:                 }
10048:             }
10049:         } else {
10050:             return 'refused';
10051:         }
10052:     } elsif (!&allowed('ccc',$udom)) {
10053:         return 'refused';
10054:     }
10055: # --------------------------------------------------------------- Get Unique ID
10056:     my $uname;
10057:     if ($cnum =~ /^$match_courseid$/) {
10058:         my $chome=&homeserver($cnum,$udom,'true');
10059:         if (($chome eq '') || ($chome eq 'no_host')) {
10060:             $uname = $cnum;
10061:         } else {
10062:             $uname = &generate_coursenum($udom,$crstype);
10063:         }
10064:     } else {
10065:         $uname = &generate_coursenum($udom,$crstype);
10066:     }
10067:     return $uname if ($uname =~ /^error/);
10068: # -------------------------------------------------- Check supplied server name
10069:     if (!defined($course_server)) {
10070:         if (defined(&domain($udom,'primary'))) {
10071:             $course_server = &domain($udom,'primary');
10072:         } else {
10073:             $course_server = $env{'user.home'}; 
10074:         }
10075:     }
10076:     my %host_servers =
10077:         &Apache::lonnet::get_servers($udom,'library');
10078:     unless ($host_servers{$course_server}) {
10079:         return 'error: invalid home server for course: '.$course_server;
10080:     }
10081: # ------------------------------------------------------------- Make the course
10082:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10083:                       $course_server);
10084:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10085:     my $uhome=&homeserver($uname,$udom,'true');
10086:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10087: 	return 'error: no such course';
10088:     }
10089: # ----------------------------------------------------------------- Course made
10090: # log existence
10091:     my $now = time;
10092:     my $newcourse = {
10093:                     $udom.'_'.$uname => {
10094:                                      description => $description,
10095:                                      inst_code   => $inst_code,
10096:                                      owner       => $course_owner,
10097:                                      type        => $crstype,
10098:                                      creator     => $env{'user.name'}.':'.
10099:                                                     $env{'user.domain'},
10100:                                      created     => $now,
10101:                                      context     => $context,
10102:                                                 },
10103:                     };
10104:     &courseidput($udom,$newcourse,$uhome,'notime');
10105: # set toplevel url
10106:     my $topurl=$url;
10107:     unless ($nonstandard) {
10108: # ------------------------------------------ For standard courses, make top url
10109:         my $mapurl=&clutter($url);
10110:         if ($mapurl eq '/res/') { $mapurl=''; }
10111:         $env{'form.initmap'}=(<<ENDINITMAP);
10112: <map>
10113: <resource id="1" type="start"></resource>
10114: <resource id="2" src="$mapurl"></resource>
10115: <resource id="3" type="finish"></resource>
10116: <link index="1" from="1" to="2"></link>
10117: <link index="2" from="2" to="3"></link>
10118: </map>
10119: ENDINITMAP
10120:         $topurl=&declutter(
10121:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10122:                           );
10123:     }
10124: # ----------------------------------------------------------- Write preferences
10125:     &writecoursepref($udom.'_'.$uname,
10126:                      ('description'              => $description,
10127:                       'url'                      => $topurl,
10128:                       'internal.creator'         => $env{'user.name'}.':'.
10129:                                                     $env{'user.domain'},
10130:                       'internal.created'         => $now,
10131:                       'internal.creationcontext' => $context)
10132:                     );
10133:     return '/'.$udom.'/'.$uname;
10134: }
10135: 
10136: # ------------------------------------------------------------------- Create ID
10137: sub generate_coursenum {
10138:     my ($udom,$crstype) = @_;
10139:     my $domdesc = &domain($udom);
10140:     return 'error: invalid domain' if ($domdesc eq '');
10141:     my $first;
10142:     if ($crstype eq 'Community') {
10143:         $first = '0';
10144:     } else {
10145:         $first = int(1+rand(9)); 
10146:     } 
10147:     my $uname=$first.
10148:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10149:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10150:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10151: # ----------------------------------------------- Make sure that does not exist
10152:     my $uhome=&homeserver($uname,$udom,'true');
10153:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10154:         if ($crstype eq 'Community') {
10155:             $first = '0';
10156:         } else {
10157:             $first = int(1+rand(9));
10158:         }
10159:         $uname=$first.
10160:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10161:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10162:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10163:         $uhome=&homeserver($uname,$udom,'true');
10164:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10165:             return 'error: unable to generate unique course-ID';
10166:         }
10167:     }
10168:     return $uname;
10169: }
10170: 
10171: sub is_course {
10172:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10173:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10174: 
10175:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10176:     my $uhome=&homeserver($cnum,$cdom);
10177:     my $iscourse;
10178:     if (grep { $_ eq $uhome } current_machine_ids()) {
10179:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10180:     } else {
10181:         my $hashid = $cdom.':'.$cnum;
10182:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10183:         unless (defined($cached)) {
10184:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10185:                                         $cnum,undef,undef,'.');
10186:             $iscourse = 0;
10187:             if (exists($courses{$cdom.'_'.$cnum})) {
10188:                 $iscourse = 1;
10189:             }
10190:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10191:         }
10192:     }
10193:     return unless ($iscourse);
10194:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10195: }
10196: 
10197: sub store_userdata {
10198:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10199:     my $result;
10200:     if ($datakey ne '') {
10201:         if (ref($storehash) eq 'HASH') {
10202:             if ($udom eq '' || $uname eq '') {
10203:                 $udom = $env{'user.domain'};
10204:                 $uname = $env{'user.name'};
10205:             }
10206:             my $uhome=&homeserver($uname,$udom);
10207:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10208:                 $result = 'error: no_host';
10209:             } else {
10210:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10211:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10212: 
10213:                 my $namevalue='';
10214:                 foreach my $key (keys(%{$storehash})) {
10215:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10216:                 }
10217:                 $namevalue=~s/\&$//;
10218:                 unless ($namespace eq 'courserequests') {
10219:                     $datakey = &escape($datakey);
10220:                 }
10221:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10222:                                   $namevalue,$uhome);
10223:             }
10224:         } else {
10225:             $result = 'error: data to store was not a hash reference'; 
10226:         }
10227:     } else {
10228:         $result= 'error: invalid requestkey'; 
10229:     }
10230:     return $result;
10231: }
10232: 
10233: # ---------------------------------------------------------- Assign Custom Role
10234: 
10235: sub assigncustomrole {
10236:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10237:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10238:                        $end,$start,$deleteflag,$selfenroll,$context);
10239: }
10240: 
10241: # ----------------------------------------------------------------- Revoke Role
10242: 
10243: sub revokerole {
10244:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10245:     my $now=time;
10246:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10247: }
10248: 
10249: # ---------------------------------------------------------- Revoke Custom Role
10250: 
10251: sub revokecustomrole {
10252:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10253:     my $now=time;
10254:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10255:            $deleteflag,$selfenroll,$context);
10256: }
10257: 
10258: # ------------------------------------------------------------ Disk usage
10259: sub diskusage {
10260:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10261:     $directorypath =~ s/\/$//;
10262:     my $listing=&reply('du2:'.&escape($directorypath).':'
10263:                        .&escape($getpropath).':'.&escape($uname).':'
10264:                        .&escape($udom),homeserver($uname,$udom));
10265:     if ($listing eq 'unknown_cmd') {
10266:         if ($getpropath) {
10267:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10268:         }
10269:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10270:     }
10271:     return $listing;
10272: }
10273: 
10274: sub is_locked {
10275:     my ($file_name, $domain, $user, $which) = @_;
10276:     my @check;
10277:     my $is_locked;
10278:     push (@check,$file_name);
10279:     my %locked = &get('file_permissions',\@check,
10280: 		      $env{'user.domain'},$env{'user.name'});
10281:     my ($tmp)=keys(%locked);
10282:     if ($tmp=~/^error:/) { undef(%locked); }
10283:     
10284:     if (ref($locked{$file_name}) eq 'ARRAY') {
10285:         $is_locked = 'false';
10286:         foreach my $entry (@{$locked{$file_name}}) {
10287:            if (ref($entry) eq 'ARRAY') {
10288:                $is_locked = 'true';
10289:                if (ref($which) eq 'ARRAY') {
10290:                    push(@{$which},$entry);
10291:                } else {
10292:                    last;
10293:                }
10294:            }
10295:        }
10296:     } else {
10297:         $is_locked = 'false';
10298:     }
10299:     return $is_locked;
10300: }
10301: 
10302: sub declutter_portfile {
10303:     my ($file) = @_;
10304:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10305:     return $file;
10306: }
10307: 
10308: # ------------------------------------------------------------- Mark as Read Only
10309: 
10310: sub mark_as_readonly {
10311:     my ($domain,$user,$files,$what) = @_;
10312:     my %current_permissions = &dump('file_permissions',$domain,$user);
10313:     my ($tmp)=keys(%current_permissions);
10314:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10315:     foreach my $file (@{$files}) {
10316: 	$file = &declutter_portfile($file);
10317:         push(@{$current_permissions{$file}},$what);
10318:     }
10319:     &put('file_permissions',\%current_permissions,$domain,$user);
10320:     return;
10321: }
10322: 
10323: # ------------------------------------------------------------Save Selected Files
10324: 
10325: sub save_selected_files {
10326:     my ($user, $path, @files) = @_;
10327:     my $filename = $user."savedfiles";
10328:     my @other_files = &files_not_in_path($user, $path);
10329:     open (OUT,'>',LONCAPA::tempdir().$filename);
10330:     foreach my $file (@files) {
10331:         print (OUT $env{'form.currentpath'}.$file."\n");
10332:     }
10333:     foreach my $file (@other_files) {
10334:         print (OUT $file."\n");
10335:     }
10336:     close (OUT);
10337:     return 'ok';
10338: }
10339: 
10340: sub clear_selected_files {
10341:     my ($user) = @_;
10342:     my $filename = $user."savedfiles";
10343:     open (OUT,'>',LONCAPA::tempdir().$filename);
10344:     print (OUT undef);
10345:     close (OUT);
10346:     return ("ok");    
10347: }
10348: 
10349: sub files_in_path {
10350:     my ($user, $path) = @_;
10351:     my $filename = $user."savedfiles";
10352:     my %return_files;
10353:     open (IN,'<',LONCAPA::tempdir().$filename);
10354:     while (my $line_in = <IN>) {
10355:         chomp ($line_in);
10356:         my @paths_and_file = split (m!/!, $line_in);
10357:         my $file_part = pop (@paths_and_file);
10358:         my $path_part = join ('/', @paths_and_file);
10359:         $path_part.='/';
10360:         my $path_and_file = $path_part.$file_part;
10361:         if ($path_part eq $path) {
10362:             $return_files{$file_part}= 'selected';
10363:         }
10364:     }
10365:     close (IN);
10366:     return (\%return_files);
10367: }
10368: 
10369: # called in portfolio select mode, to show files selected NOT in current directory
10370: sub files_not_in_path {
10371:     my ($user, $path) = @_;
10372:     my $filename = $user."savedfiles";
10373:     my @return_files;
10374:     my $path_part;
10375:     open(IN, '<',LONCAPA::tempdir().$filename);
10376:     while (my $line = <IN>) {
10377:         #ok, I know it's clunky, but I want it to work
10378:         my @paths_and_file = split(m|/|, $line);
10379:         my $file_part = pop(@paths_and_file);
10380:         chomp($file_part);
10381:         my $path_part = join('/', @paths_and_file);
10382:         $path_part .= '/';
10383:         my $path_and_file = $path_part.$file_part;
10384:         if ($path_part ne $path) {
10385:             push(@return_files, ($path_and_file));
10386:         }
10387:     }
10388:     close(OUT);
10389:     return (@return_files);
10390: }
10391: 
10392: #------------------------------Submitted/Handedback Portfolio Files Versioning
10393:  
10394: sub portfiles_versioning {
10395:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10396:     my $portfolio_root = '/userfiles/portfolio';
10397:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10398:     foreach my $file (@{$portfiles}) {
10399:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10400:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10401:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10402:         my $getpropath = 1;
10403:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10404:                                              $stu_name,$getpropath);
10405:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10406:         my $new_answer = 
10407:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10408:         if ($new_answer ne 'problem getting file') {
10409:             push(@{$versioned_portfiles}, $directory.$new_answer);
10410:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10411:                               [$symb,$env{'request.course.id'},'graded']);
10412:         }
10413:     }
10414: }
10415: 
10416: sub get_next_version {
10417:     my ($answer_name, $answer_ext, $dir_list) = @_;
10418:     my $version;
10419:     if (ref($dir_list) eq 'ARRAY') {
10420:         foreach my $row (@{$dir_list}) {
10421:             my ($file) = split(/\&/,$row,2);
10422:             my ($file_name,$file_version,$file_ext) =
10423:                 &file_name_version_ext($file);
10424:             if (($file_name eq $answer_name) &&
10425:                 ($file_ext eq $answer_ext)) {
10426:                      # gets here if filename and extension match,
10427:                      # regardless of version
10428:                 if ($file_version ne '') {
10429:                     # a versioned file is found  so save it for later
10430:                     if ($file_version > $version) {
10431:                         $version = $file_version;
10432:                     }
10433:                 }
10434:             }
10435:         }
10436:     }
10437:     $version ++;
10438:     return($version);
10439: }
10440: 
10441: sub version_selected_portfile {
10442:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10443:     my ($answer_name,$answer_ver,$answer_ext) =
10444:         &file_name_version_ext($file_name);
10445:     my $new_answer;
10446:     $env{'form.copy'} =
10447:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10448:     if($env{'form.copy'} eq '-1') {
10449:         $new_answer = 'problem getting file';
10450:     } else {
10451:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10452:         my $copy_result = 
10453:             &finishuserfileupload($stu_name,$domain,'copy',
10454:                                   '/portfolio'.$directory.$new_answer);
10455:     }
10456:     undef($env{'form.copy'});
10457:     return ($new_answer);
10458: }
10459: 
10460: sub file_name_version_ext {
10461:     my ($file)=@_;
10462:     my @file_parts = split(/\./, $file);
10463:     my ($name,$version,$ext);
10464:     if (@file_parts > 1) {
10465:         $ext=pop(@file_parts);
10466:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10467:             $version=pop(@file_parts);
10468:         }
10469:         $name=join('.',@file_parts);
10470:     } else {
10471:         $name=join('.',@file_parts);
10472:     }
10473:     return($name,$version,$ext);
10474: }
10475: 
10476: #----------------------------------------------Get portfolio file permissions
10477: 
10478: sub get_portfile_permissions {
10479:     my ($domain,$user) = @_;
10480:     my %current_permissions = &dump('file_permissions',$domain,$user);
10481:     my ($tmp)=keys(%current_permissions);
10482:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10483:     return \%current_permissions;
10484: }
10485: 
10486: #---------------------------------------------Get portfolio file access controls
10487: 
10488: sub get_access_controls {
10489:     my ($current_permissions,$group,$file) = @_;
10490:     my %access;
10491:     my $real_file = $file;
10492:     $file =~ s/\.meta$//;
10493:     if (defined($file)) {
10494:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10495:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10496:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10497:             }
10498:         }
10499:     } else {
10500:         foreach my $key (keys(%{$current_permissions})) {
10501:             if ($key =~ /\0accesscontrol$/) {
10502:                 if (defined($group)) {
10503:                     if ($key !~ m-^\Q$group\E/-) {
10504:                         next;
10505:                     }
10506:                 }
10507:                 my ($fullpath) = split(/\0/,$key);
10508:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10509:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10510:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10511:                     }
10512:                 }
10513:             }
10514:         }
10515:     }
10516:     return %access;
10517: }
10518: 
10519: sub modify_access_controls {
10520:     my ($file_name,$changes,$domain,$user)=@_;
10521:     my ($outcome,$deloutcome);
10522:     my %store_permissions;
10523:     my %new_values;
10524:     my %new_control;
10525:     my %translation;
10526:     my @deletions = ();
10527:     my $now = time;
10528:     if (exists($$changes{'activate'})) {
10529:         if (ref($$changes{'activate'}) eq 'HASH') {
10530:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10531:             my $numnew = scalar(@newitems);
10532:             for (my $i=0; $i<$numnew; $i++) {
10533:                 my $newkey = $newitems[$i];
10534:                 my $newid = &Apache::loncommon::get_cgi_id();
10535:                 if ($newkey =~ /^\d+:/) { 
10536:                     $newkey =~ s/^(\d+)/$newid/;
10537:                     $translation{$1} = $newid;
10538:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10539:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10540:                     $translation{$1} = $newid;
10541:                 }
10542:                 $new_values{$file_name."\0".$newkey} = 
10543:                                           $$changes{'activate'}{$newitems[$i]};
10544:                 $new_control{$newkey} = $now;
10545:             }
10546:         }
10547:     }
10548:     my %todelete;
10549:     my %changed_items;
10550:     foreach my $action ('delete','update') {
10551:         if (exists($$changes{$action})) {
10552:             if (ref($$changes{$action}) eq 'HASH') {
10553:                 foreach my $key (keys(%{$$changes{$action}})) {
10554:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10555:                     if ($action eq 'delete') { 
10556:                         $todelete{$itemnum} = 1;
10557:                     } else {
10558:                         $changed_items{$itemnum} = $key;
10559:                     }
10560:                 }
10561:             }
10562:         }
10563:     }
10564:     # get lock on access controls for file.
10565:     my $lockhash = {
10566:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10567:                                                        ':'.$env{'user.domain'},
10568:                    }; 
10569:     my $tries = 0;
10570:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10571:    
10572:     while (($gotlock ne 'ok') && $tries < 10) {
10573:         $tries ++;
10574:         sleep(0.1);
10575:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10576:     }
10577:     if ($gotlock eq 'ok') {
10578:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10579:         my ($tmp)=keys(%curr_permissions);
10580:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10581:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10582:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10583:             if (ref($curr_controls) eq 'HASH') {
10584:                 foreach my $control_item (keys(%{$curr_controls})) {
10585:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10586:                     if (defined($todelete{$itemnum})) {
10587:                         push(@deletions,$file_name."\0".$control_item);
10588:                     } else {
10589:                         if (defined($changed_items{$itemnum})) {
10590:                             $new_control{$changed_items{$itemnum}} = $now;
10591:                             push(@deletions,$file_name."\0".$control_item);
10592:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10593:                         } else {
10594:                             $new_control{$control_item} = $$curr_controls{$control_item};
10595:                         }
10596:                     }
10597:                 }
10598:             }
10599:         }
10600:         my ($group);
10601:         if (&is_course($domain,$user)) {
10602:             ($group,my $file) = split(/\//,$file_name,2);
10603:         }
10604:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10605:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10606:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10607:         #  remove lock
10608:         my @del_lock = ($file_name."\0".'locked_access_records');
10609:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10610:         my $sqlresult =
10611:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10612:                                     $group);
10613:     } else {
10614:         $outcome = "error: could not obtain lockfile\n";  
10615:     }
10616:     return ($outcome,$deloutcome,\%new_values,\%translation);
10617: }
10618: 
10619: sub make_public_indefinitely {
10620:     my (@requrl) = @_;
10621:     return &automated_portfile_access('public',\@requrl);
10622: }
10623: 
10624: sub automated_portfile_access {
10625:     my ($accesstype,$addsref,$delsref,$info) = @_;
10626:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10627:         return 'invalid';
10628:     }
10629:     my %urls;
10630:     if (ref($addsref) eq 'ARRAY') {
10631:         foreach my $requrl (@{$addsref}) {
10632:             if (&is_portfolio_url($requrl)) {
10633:                 unless (exists($urls{$requrl})) {
10634:                     $urls{$requrl} = 'add';
10635:                 }
10636:             }
10637:         }
10638:     }
10639:     if (ref($delsref) eq 'ARRAY') {
10640:         foreach my $requrl (@{$delsref}) { 
10641:             if (&is_portfolio_url($requrl)) {
10642:                 unless (exists($urls{$requrl})) {
10643:                     $urls{$requrl} = 'delete'; 
10644:                 }
10645:             }
10646:         }
10647:     }
10648:     unless (keys(%urls)) {
10649:         return 'invalid';
10650:     }
10651:     my $ip;
10652:     if ($accesstype eq 'ip') {
10653:         if (ref($info) eq 'HASH') {
10654:             if ($info->{'ip'} ne '') {
10655:                 $ip = $info->{'ip'};
10656:             }
10657:         }
10658:         if ($ip eq '') {
10659:             return 'invalid';
10660:         }
10661:     }
10662:     my $errors;
10663:     my $now = time;
10664:     my %current_perms;
10665:     foreach my $requrl (sort(keys(%urls))) {
10666:         my $action;
10667:         if ($urls{$requrl} eq 'add') {
10668:             $action = 'activate';
10669:         } else {
10670:             $action = 'none';
10671:         }
10672:         my $aclnum = 0;
10673:         my (undef,$udom,$unum,$file_name,$group) =
10674:             &parse_portfolio_url($requrl);
10675:         unless (exists($current_perms{$unum.':'.$udom})) {
10676:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10677:         }
10678:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10679:                                                    $group,$file_name);
10680:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10681:             my ($num,$scope,$end,$start) = 
10682:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10683:             if ($scope eq $accesstype) {
10684:                 if (($start <= $now) && ($end == 0)) {
10685:                     if ($accesstype eq 'ip') {
10686:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10687:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10688:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10689:                                     if ($urls{$requrl} eq 'add') {
10690:                                         $action = 'none';
10691:                                         last;
10692:                                     } else {
10693:                                         $action = 'delete';
10694:                                         $aclnum = $num;
10695:                                         last;
10696:                                     }
10697:                                 }
10698:                             }
10699:                         }
10700:                     } elsif ($accesstype eq 'public') {
10701:                         if ($urls{$requrl} eq 'add') {
10702:                             $action = 'none';
10703:                             last;
10704:                         } else {
10705:                             $action = 'delete';
10706:                             $aclnum = $num;
10707:                             last;
10708:                         }
10709:                     }
10710:                 } elsif ($accesstype eq 'public') {
10711:                     $action = 'update';
10712:                     $aclnum = $num;
10713:                     last;
10714:                 }
10715:             }
10716:         }
10717:         if ($action eq 'none') {
10718:             next;
10719:         } else {
10720:             my %changes;
10721:             my $newend = 0;
10722:             my $newstart = $now;
10723:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10724:             $changes{$action}{$newkey} = {
10725:                 type => $accesstype,
10726:                 time => {
10727:                     start => $newstart,
10728:                     end   => $newend,
10729:                 },
10730:             };
10731:             if ($accesstype eq 'ip') {
10732:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10733:             }
10734:             my ($outcome,$deloutcome,$new_values,$translation) =
10735:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10736:             unless ($outcome eq 'ok') {
10737:                 $errors .= $outcome.' ';
10738:             }
10739:         }
10740:     }
10741:     if ($errors) {
10742:         $errors =~ s/\s$//;
10743:         return $errors;
10744:     } else {
10745:         return 'ok';
10746:     }
10747: }
10748: 
10749: #------------------------------------------------------Get Marked as Read Only
10750: 
10751: sub get_marked_as_readonly {
10752:     my ($domain,$user,$what,$group) = @_;
10753:     my $current_permissions = &get_portfile_permissions($domain,$user);
10754:     my @readonly_files;
10755:     my $cmp1=$what;
10756:     if (ref($what)) { $cmp1=join('',@{$what}) };
10757:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10758:         if (defined($group)) {
10759:             if ($file_name !~ m-^\Q$group\E/-) {
10760:                 next;
10761:             }
10762:         }
10763:         if (ref($value) eq "ARRAY"){
10764:             foreach my $stored_what (@{$value}) {
10765:                 my $cmp2=$stored_what;
10766:                 if (ref($stored_what) eq 'ARRAY') {
10767:                     $cmp2=join('',@{$stored_what});
10768:                 }
10769:                 if ($cmp1 eq $cmp2) {
10770:                     push(@readonly_files, $file_name);
10771:                     last;
10772:                 } elsif (!defined($what)) {
10773:                     push(@readonly_files, $file_name);
10774:                     last;
10775:                 }
10776:             }
10777:         }
10778:     }
10779:     return @readonly_files;
10780: }
10781: #-----------------------------------------------------------Get Marked as Read Only Hash
10782: 
10783: sub get_marked_as_readonly_hash {
10784:     my ($current_permissions,$group,$what) = @_;
10785:     my %readonly_files;
10786:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10787:         if (defined($group)) {
10788:             if ($file_name !~ m-^\Q$group\E/-) {
10789:                 next;
10790:             }
10791:         }
10792:         if (ref($value) eq "ARRAY"){
10793:             foreach my $stored_what (@{$value}) {
10794:                 if (ref($stored_what) eq 'ARRAY') {
10795:                     foreach my $lock_descriptor(@{$stored_what}) {
10796:                         if ($lock_descriptor eq 'graded') {
10797:                             $readonly_files{$file_name} = 'graded';
10798:                         } elsif ($lock_descriptor eq 'handback') {
10799:                             $readonly_files{$file_name} = 'handback';
10800:                         } else {
10801:                             if (!exists($readonly_files{$file_name})) {
10802:                                 $readonly_files{$file_name} = 'locked';
10803:                             }
10804:                         }
10805:                     }
10806:                 } 
10807:             }
10808:         } 
10809:     }
10810:     return %readonly_files;
10811: }
10812: # ------------------------------------------------------------ Unmark as Read Only
10813: 
10814: sub unmark_as_readonly {
10815:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10816:     # for portfolio submissions, $what contains [$symb,$crsid] 
10817:     my ($domain,$user,$what,$file_name,$group) = @_;
10818:     $file_name = &declutter_portfile($file_name);
10819:     my $symb_crs = $what;
10820:     if (ref($what)) { $symb_crs=join('',@$what); }
10821:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10822:     my ($tmp)=keys(%current_permissions);
10823:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10824:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10825:     foreach my $file (@readonly_files) {
10826: 	my $clean_file = &declutter_portfile($file);
10827: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10828: 	my $current_locks = $current_permissions{$file};
10829:         my @new_locks;
10830:         my @del_keys;
10831:         if (ref($current_locks) eq "ARRAY"){
10832:             foreach my $locker (@{$current_locks}) {
10833:                 my $compare=$locker;
10834:                 if (ref($locker) eq 'ARRAY') {
10835:                     $compare=join('',@{$locker});
10836:                     if ($compare ne $symb_crs) {
10837:                         push(@new_locks, $locker);
10838:                     }
10839:                 }
10840:             }
10841:             if (scalar(@new_locks) > 0) {
10842:                 $current_permissions{$file} = \@new_locks;
10843:             } else {
10844:                 push(@del_keys, $file);
10845:                 &del('file_permissions',\@del_keys, $domain, $user);
10846:                 delete($current_permissions{$file});
10847:             }
10848:         }
10849:     }
10850:     &put('file_permissions',\%current_permissions,$domain,$user);
10851:     return;
10852: }
10853: 
10854: # ------------------------------------------------------------ Directory lister
10855: 
10856: sub dirlist {
10857:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10858:     $uri=~s/^\///;
10859:     $uri=~s/\/$//;
10860:     my ($udom, $uname);
10861:     if ($getuserdir) {
10862:         $udom = $userdomain;
10863:         $uname = $username;
10864:     } else {
10865:         (undef,$udom,$uname)=split(/\//,$uri);
10866:         if(defined($userdomain)) {
10867:             $udom = $userdomain;
10868:         }
10869:         if(defined($username)) {
10870:             $uname = $username;
10871:         }
10872:     }
10873:     my ($dirRoot,$listing,@listing_results);
10874: 
10875:     $dirRoot = $perlvar{'lonDocRoot'};
10876:     if (defined($getpropath)) {
10877:         $dirRoot = &propath($udom,$uname);
10878:         $dirRoot =~ s/\/$//;
10879:     } elsif (defined($getuserdir)) {
10880:         my $subdir=$uname.'__';
10881:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10882:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10883:                    ."/$udom/$subdir/$uname";
10884:     } elsif (defined($alternateRoot)) {
10885:         $dirRoot = $alternateRoot;
10886:     }
10887: 
10888:     if($udom) {
10889:         if($uname) {
10890:             my $uhome = &homeserver($uname,$udom);
10891:             if ($uhome eq 'no_host') {
10892:                 return ([],'no_host');
10893:             }
10894:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10895:                               .$getuserdir.':'.&escape($dirRoot)
10896:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10897:             if ($listing eq 'unknown_cmd') {
10898:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10899:             } else {
10900:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10901:             }
10902:             if ($listing eq 'unknown_cmd') {
10903:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10904:                 @listing_results = split(/:/,$listing);
10905:             } else {
10906:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10907:             }
10908:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10909:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10910:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10911:                 return ([],$listing);
10912:             } else {
10913:                 return (\@listing_results);
10914:             }
10915:         } elsif(!$alternateRoot) {
10916:             my (%allusers,%listerror);
10917: 	    my %servers = &get_servers($udom,'library');
10918:  	    foreach my $tryserver (keys(%servers)) {
10919:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10920:                                   &escape($udom),$tryserver);
10921:                 if ($listing eq 'unknown_cmd') {
10922: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10923: 				      $udom, $tryserver);
10924:                 } else {
10925:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10926:                 }
10927: 		if ($listing eq 'unknown_cmd') {
10928: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10929: 				      $udom, $tryserver);
10930: 		    @listing_results = split(/:/,$listing);
10931: 		} else {
10932: 		    @listing_results =
10933: 			map { &unescape($_); } split(/:/,$listing);
10934: 		}
10935:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10936:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10937:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10938:                     $listerror{$tryserver} = $listing;
10939:                 } else {
10940: 		    foreach my $line (@listing_results) {
10941: 			my ($entry) = split(/&/,$line,2);
10942: 			$allusers{$entry} = 1;
10943: 		    }
10944: 		}
10945:             }
10946:             my @alluserslist=();
10947:             foreach my $user (sort(keys(%allusers))) {
10948:                 push(@alluserslist,$user.'&user');
10949:             }
10950: 
10951:             if (!%listerror) {
10952:                 # no errors
10953:                 return (\@alluserslist);
10954:             } elsif (scalar(keys(%servers)) == 1) {
10955:                 # one library server, one error 
10956:                 my ($key) = keys(%listerror);
10957:                 return (\@alluserslist, $listerror{$key});
10958:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10959:                 # con_lost indicates that we might miss data from at least one
10960:                 # library server
10961:                 return (\@alluserslist, 'con_lost');
10962:             } else {
10963:                 # multiple library servers and no con_lost -> data should be
10964:                 # complete. 
10965:                 return (\@alluserslist);
10966:             }
10967: 
10968:         } else {
10969:             return ([],'missing username');
10970:         }
10971:     } elsif(!defined($getpropath)) {
10972:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10973:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10974:         return (\@all_domains);
10975:     } else {
10976:         return ([],'missing domain');
10977:     }
10978: }
10979: 
10980: # --------------------------------------------- GetFileTimestamp
10981: # This function utilizes dirlist and returns the date stamp for
10982: # when it was last modified.  It will also return an error of -1
10983: # if an error occurs
10984: 
10985: sub GetFileTimestamp {
10986:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10987:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10988:     $studentName   = &LONCAPA::clean_username($studentName);
10989:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10990:                                     undef,$getuserdir);
10991:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10992:         return -1;
10993:     }
10994:     if (ref($fileref) eq 'ARRAY') {
10995:         my @stats = split('&',$fileref->[0]);
10996:         # @stats contains first the filename, then the stat output
10997:         return $stats[10]; # so this is 10 instead of 9.
10998:     } else {
10999:         return -1;
11000:     }
11001: }
11002: 
11003: sub stat_file {
11004:     my ($uri) = @_;
11005:     $uri = &clutter_with_no_wrapper($uri);
11006: 
11007:     my ($udom,$uname,$file);
11008:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11009: 	($udom,$uname,$file) =
11010: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11011: 	$file = 'userfiles/'.$file;
11012:     }
11013:     if ($uri =~ m-^/res/-) {
11014: 	($udom,$uname) = 
11015: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11016: 	$file = $uri;
11017:     }
11018: 
11019:     if (!$udom || !$uname || !$file) {
11020: 	# unable to handle the uri
11021: 	return ();
11022:     }
11023:     my $getpropath;
11024:     if ($file =~ /^userfiles\//) {
11025:         $getpropath = 1;
11026:     }
11027:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11028:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11029:         return ();
11030:     } else {
11031:         if (ref($listref) eq 'ARRAY') {
11032:             my @stats = split('&',$listref->[0]);
11033: 	    shift(@stats); #filename is first
11034: 	    return @stats;
11035:         }
11036:     }
11037:     return ();
11038: }
11039: 
11040: # --------------------------------------------------------- recursedirs
11041: # Recursive function to traverse either a specific user's Authoring Space
11042: # or corresponding Published Resource Space, and populate the hash ref:
11043: # $dirhashref with URLs of all directories, and if $filehashref hash
11044: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11045: # or .rights files in resource space, and .meta, .save, .log, and .bak
11046: # files in Authoring Space.
11047: #
11048: # Inputs:
11049: #
11050: # $is_home - true if current server is home server for user's space
11051: # $context - either: priv, or res respectively for Authoring or Resource Space.
11052: # $docroot - Document root (i.e., /home/httpd/html
11053: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11054: # $relpath - Current path (relative to top level).
11055: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11056: # $filehashref - reference to hash to populate with URLs of files (Optional)
11057: #
11058: # Returns: nothing
11059: #
11060: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11061: #
11062: # Currently used by interface/londocs.pm to create linked select boxes for
11063: # directory and filename to import a Course "Author" resource into a course, and
11064: # also to create linked select boxes for Authoring Space and Directory to choose
11065: # save location for creation of a new "standard" problem from the Course Editor.
11066: #
11067: 
11068: sub recursedirs {
11069:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11070:     return unless (ref($dirhashref) eq 'HASH');
11071:     my $currpath = $docroot.$toppath;
11072:     if ($relpath) {
11073:         $currpath .= "/$relpath";
11074:     }
11075:     my $savefile;
11076:     if (ref($filehashref)) {
11077:         $savefile = 1;
11078:     }
11079:     if ($is_home) {
11080:         if (opendir(my $dirh,$currpath)) {
11081:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11082:                 next if ($item eq '');
11083:                 if (-d "$currpath/$item") {
11084:                     my $newpath;
11085:                     if ($relpath) {
11086:                         $newpath = "$relpath/$item";
11087:                     } else {
11088:                         $newpath = $item;
11089:                     }
11090:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11091:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11092:                 } elsif ($savefile) {
11093:                     if ($context eq 'priv') {
11094:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11095:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11096:                         }
11097:                     } else {
11098:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11099:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11100:                         }
11101:                     }
11102:                 }
11103:             }
11104:             closedir($dirh);
11105:         }
11106:     } else {
11107:         my ($dirlistref,$listerror) =
11108:             &dirlist($toppath.$relpath);
11109:         my @dir_lines;
11110:         my $dirptr=16384;
11111:         if (ref($dirlistref) eq 'ARRAY') {
11112:             foreach my $dir_line (sort
11113:                               {
11114:                                   my ($afile)=split('&',$a,2);
11115:                                   my ($bfile)=split('&',$b,2);
11116:                                   return (lc($afile) cmp lc($bfile));
11117:                               } (@{$dirlistref})) {
11118:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11119:                     split(/\&/,$dir_line,16);
11120:                 $item =~ s/\s+$//;
11121:                 next if (($item =~ /^\.\.?$/) || ($obs));
11122:                 if ($dirptr&$testdir) {
11123:                     my $newpath;
11124:                     if ($relpath) {
11125:                         $newpath = "$relpath/$item";
11126:                     } else {
11127:                         $relpath = '/';
11128:                         $newpath = $item;
11129:                     }
11130:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11131:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11132:                 } elsif ($savefile) {
11133:                     if ($context eq 'priv') {
11134:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11135:                             $filehashref->{$relpath}{$item} = 1;
11136:                         }
11137:                     } else {
11138:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11139:                             $filehashref->{$relpath}{$item} = 1;
11140:                         }
11141:                     }
11142:                 }
11143:             }
11144:         }
11145:     }
11146:     return;
11147: }
11148: 
11149: # -------------------------------------------------------- Value of a Condition
11150: 
11151: # gets the value of a specific preevaluated condition
11152: #    stored in the string  $env{user.state.<cid>}
11153: # or looks up a condition reference in the bighash and if if hasn't
11154: # already been evaluated recurses into docondval to get the value of
11155: # the condition, then memoizing it to 
11156: #   $env{user.state.<cid>.<condition>}
11157: sub directcondval {
11158:     my $number=shift;
11159:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11160: 	&Apache::lonuserstate::evalstate();
11161:     }
11162:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11163: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11164:     } elsif ($number =~ /^_/) {
11165: 	my $sub_condition;
11166: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11167: 		&GDBM_READER(),0640)) {
11168: 	    $sub_condition=$bighash{'conditions'.$number};
11169: 	    untie(%bighash);
11170: 	}
11171: 	my $value = &docondval($sub_condition);
11172: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11173: 	return $value;
11174:     }
11175:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11176:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11177:     } else {
11178:        return 2;
11179:     }
11180: }
11181: 
11182: # get the collection of conditions for this resource
11183: sub condval {
11184:     my $condidx=shift;
11185:     my $allpathcond='';
11186:     foreach my $cond (split(/\|/,$condidx)) {
11187: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11188: 	    $allpathcond.=
11189: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11190: 	}
11191:     }
11192:     $allpathcond=~s/\|$//;
11193:     return &docondval($allpathcond);
11194: }
11195: 
11196: #evaluates an expression of conditions
11197: sub docondval {
11198:     my ($allpathcond) = @_;
11199:     my $result=0;
11200:     if ($env{'request.course.id'}
11201: 	&& defined($allpathcond)) {
11202: 	my $operand='|';
11203: 	my @stack;
11204: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11205: 	    if ($chunk eq '(') {
11206: 		push @stack,($operand,$result);
11207: 	    } elsif ($chunk eq ')') {
11208: 		my $before=pop @stack;
11209: 		if (pop @stack eq '&') {
11210: 		    $result=$result>$before?$before:$result;
11211: 		} else {
11212: 		    $result=$result>$before?$result:$before;
11213: 		}
11214: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11215: 		$operand=$chunk;
11216: 	    } else {
11217: 		my $new=directcondval($chunk);
11218: 		if ($operand eq '&') {
11219: 		    $result=$result>$new?$new:$result;
11220: 		} else {
11221: 		    $result=$result>$new?$result:$new;
11222: 		}
11223: 	    }
11224: 	}
11225:     }
11226:     return $result;
11227: }
11228: 
11229: # ---------------------------------------------------- Devalidate courseresdata
11230: 
11231: sub devalidatecourseresdata {
11232:     my ($coursenum,$coursedomain)=@_;
11233:     my $hashid=$coursenum.':'.$coursedomain;
11234:     &devalidate_cache_new('courseres',$hashid);
11235: }
11236: 
11237: 
11238: # --------------------------------------------------- Course Resourcedata Query
11239: #
11240: #  Parameters:
11241: #      $coursenum    - Number of the course.
11242: #      $coursedomain - Domain at which the course was created.
11243: #  Returns:
11244: #     A hash of the course parameters along (I think) with timestamps
11245: #     and version info.
11246: 
11247: sub get_courseresdata {
11248:     my ($coursenum,$coursedomain)=@_;
11249:     my $coursehom=&homeserver($coursenum,$coursedomain);
11250:     my $hashid=$coursenum.':'.$coursedomain;
11251:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11252:     my %dumpreply;
11253:     unless (defined($cached)) {
11254: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11255: 	$result=\%dumpreply;
11256: 	my ($tmp) = keys(%dumpreply);
11257: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11258: 	    &do_cache_new('courseres',$hashid,$result,600);
11259: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11260: 	    return $tmp;
11261: 	} elsif ($tmp =~ /^(error)/) {
11262: 	    $result=undef;
11263: 	    &do_cache_new('courseres',$hashid,$result,600);
11264: 	}
11265:     }
11266:     return $result;
11267: }
11268: 
11269: sub devalidateuserresdata {
11270:     my ($uname,$udom)=@_;
11271:     my $hashid="$udom:$uname";
11272:     &devalidate_cache_new('userres',$hashid);
11273: }
11274: 
11275: sub get_userresdata {
11276:     my ($uname,$udom)=@_;
11277:     #most student don\'t have any data set, check if there is some data
11278:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11279: 
11280:     my $hashid="$udom:$uname";
11281:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11282:     if (!defined($cached)) {
11283: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11284: 	$result=\%resourcedata;
11285: 	&do_cache_new('userres',$hashid,$result,600);
11286:     }
11287:     my ($tmp)=keys(%$result);
11288:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11289: 	return $result;
11290:     }
11291:     #error 2 occurs when the .db doesn't exist
11292:     if ($tmp!~/error: 2 /) {
11293:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11294: 	    &logthis("<font color=\"blue\">WARNING:".
11295: 		     " Trying to get resource data for ".
11296: 		     $uname." at ".$udom.": ".
11297: 		     $tmp."</font>");
11298:         }
11299:     } elsif ($tmp=~/error: 2 /) {
11300: 	#&EXT_cache_set($udom,$uname);
11301: 	&do_cache_new('userres',$hashid,undef,600);
11302: 	undef($tmp); # not really an error so don't send it back
11303:     }
11304:     return $tmp;
11305: }
11306: #----------------------------------------------- resdata - return resource data
11307: #  Purpose:
11308: #    Return resource data for either users or for a course.
11309: #  Parameters:
11310: #     $name      - Course/user name.
11311: #     $domain    - Name of the domain the user/course is registered on.
11312: #     $type      - Type of thing $name is (must be 'course' or 'user')
11313: #     $mapp      - decluttered URL of enclosing map  
11314: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11315: #     $recurseup - Ref to array of map URLs, starting with map containing
11316: #                  $mapp up through hierarchy of nested maps to top level map.  
11317: #     $courseid  - CourseID (first part of param identifier).
11318: #     $modifier  - Middle part of param identifier.
11319: #     $what      - Last part of param identifier.
11320: #     @which     - Array of names of resources desired.
11321: #  Returns:
11322: #     The value of the first reasource in @which that is found in the
11323: #     resource hash.
11324: #  Exceptional Conditions:
11325: #     If the $type passed in is not valid (not the string 'course' or 
11326: #     'user', an undefined  reference is returned.
11327: #     If none of the resources are found, an undef is returned
11328: sub resdata {
11329:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11330:         $modifier,$what,@which)=@_;
11331:     my $result;
11332:     if ($type eq 'course') {
11333: 	$result=&get_courseresdata($name,$domain);
11334:     } elsif ($type eq 'user') {
11335: 	$result=&get_userresdata($name,$domain);
11336:     }
11337:     if (!ref($result)) { return $result; }    
11338:     foreach my $item (@which) {
11339:         if ($item->[1] eq 'course') {
11340:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11341:                 unless ($$recursed) {
11342:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11343:                     $$recursed = 1;
11344:                 }
11345:                 foreach my $item (@${recurseup}) {
11346:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11347:                     last if (defined($result->{$norecursechk}));
11348:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11349:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11350:                 }
11351:             }
11352:         }
11353:         if (defined($result->{$item->[0]})) {
11354: 	    return [$result->{$item->[0]},$item->[1]];
11355: 	}
11356:     }
11357:     return undef;
11358: }
11359: 
11360: sub get_domain_lti {
11361:     my ($cdom,$context) = @_;
11362:     my ($name,%lti);
11363:     if ($context eq 'consumer') {
11364:         $name = 'ltitools';
11365:     } elsif ($context eq 'provider') {
11366:         $name = 'lti';
11367:     } else {
11368:         return %lti;
11369:     }
11370:     my ($result,$cached)=&is_cached_new($name,$cdom);
11371:     if (defined($cached)) {
11372:         if (ref($result) eq 'HASH') {
11373:             %lti = %{$result};
11374:         }
11375:     } else {
11376:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11377:         if (ref($domconfig{$name}) eq 'HASH') {
11378:             %lti = %{$domconfig{$name}};
11379:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11380:             if (ref($encdomconfig{$name}) eq 'HASH') {
11381:                 foreach my $id (keys(%lti)) {
11382:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11383:                         foreach my $item ('key','secret') {
11384:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11385:                         }
11386:                     }
11387:                 }
11388:             }
11389:         }
11390:         my $cachetime = 24*60*60;
11391:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11392:     }
11393:     return %lti;
11394: }
11395: 
11396: sub get_numsuppfiles {
11397:     my ($cnum,$cdom,$ignorecache)=@_;
11398:     my $hashid=$cnum.':'.$cdom;
11399:     my ($suppcount,$cached);
11400:     unless ($ignorecache) {
11401:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11402:     }
11403:     unless (defined($cached)) {
11404:         my $chome=&homeserver($cnum,$cdom);
11405:         unless ($chome eq 'no_host') {
11406:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11407:             my $suppmap = 'supplemental.sequence';
11408:             ($suppcount,$supptools,$errors) =
11409:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11410:                                                          $supptools,$errors);
11411:         }
11412:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11413:     }
11414:     return $suppcount;
11415: }
11416: 
11417: #
11418: # EXT resource caching routines
11419: #
11420: 
11421: {
11422: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11423: #
11424: # The course for which we cache
11425: my $cachedmapkey='';
11426: # The cached recursive maps for this course
11427: my %cachedmaps=();
11428: # When this was last done
11429: my $cachedmaptime='';
11430: 
11431: sub clear_EXT_cache_status {
11432:     &delenv('cache.EXT.');
11433: }
11434: 
11435: sub EXT_cache_status {
11436:     my ($target_domain,$target_user) = @_;
11437:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11438:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11439:         # We know already the user has no data
11440:         return 1;
11441:     } else {
11442:         return 0;
11443:     }
11444: }
11445: 
11446: sub EXT_cache_set {
11447:     my ($target_domain,$target_user) = @_;
11448:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11449:     #&appenv({$cachename => time});
11450: }
11451: 
11452: # --------------------------------------------------------- Value of a Variable
11453: sub EXT {
11454: 
11455:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11456:     unless ($varname) { return ''; }
11457:     #get real user name/domain, courseid and symb
11458:     my $courseid;
11459:     my $publicuser;
11460:     if ($symbparm) {
11461: 	$symbparm=&get_symb_from_alias($symbparm);
11462:     }
11463:     if (!($uname && $udom)) {
11464:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11465:       if (!$symbparm) {	$symbparm=$cursymb; }
11466:     } else {
11467: 	$courseid=$env{'request.course.id'};
11468:     }
11469:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11470:     my $rest;
11471:     if (defined($therest[0])) {
11472:        $rest=join('.',@therest);
11473:     } else {
11474:        $rest='';
11475:     }
11476: 
11477:     my $qualifierrest=$qualifier;
11478:     if ($rest) { $qualifierrest.='.'.$rest; }
11479:     my $spacequalifierrest=$space;
11480:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11481:     if ($realm eq 'user') {
11482: # --------------------------------------------------------------- user.resource
11483: 	if ($space eq 'resource') {
11484: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11485: 		  || defined($Apache::lonhomework::parsing_a_task))
11486: 		 &&
11487: 		 ($symbparm eq &symbread()) ) {	
11488: 		# if we are in the middle of processing the resource the
11489: 		# get the value we are planning on committing
11490:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11491:                     return $Apache::lonhomework::results{$qualifierrest};
11492:                 } else {
11493:                     return $Apache::lonhomework::history{$qualifierrest};
11494:                 }
11495: 	    } else {
11496: 		my %restored;
11497: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11498: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11499: 		} else {
11500: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11501: 		}
11502: 		return $restored{$qualifierrest};
11503: 	    }
11504: # ----------------------------------------------------------------- user.access
11505:         } elsif ($space eq 'access') {
11506: 	    # FIXME - not supporting calls for a specific user
11507:             return &allowed($qualifier,$rest);
11508: # ------------------------------------------ user.preferences, user.environment
11509:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11510: 	    if (($uname eq $env{'user.name'}) &&
11511: 		($udom eq $env{'user.domain'})) {
11512: 		return $env{join('.',('environment',$qualifierrest))};
11513: 	    } else {
11514: 		my %returnhash;
11515: 		if (!$publicuser) {
11516: 		    %returnhash=&userenvironment($udom,$uname,
11517: 						 $qualifierrest);
11518: 		}
11519: 		return $returnhash{$qualifierrest};
11520: 	    }
11521: # ----------------------------------------------------------------- user.course
11522:         } elsif ($space eq 'course') {
11523: 	    # FIXME - not supporting calls for a specific user
11524:             return $env{join('.',('request.course',$qualifier))};
11525: # ------------------------------------------------------------------- user.role
11526:         } elsif ($space eq 'role') {
11527: 	    # FIXME - not supporting calls for a specific user
11528:             my ($role,$where)=split(/\./,$env{'request.role'});
11529:             if ($qualifier eq 'value') {
11530: 		return $role;
11531:             } elsif ($qualifier eq 'extent') {
11532:                 return $where;
11533:             }
11534: # ----------------------------------------------------------------- user.domain
11535:         } elsif ($space eq 'domain') {
11536:             return $udom;
11537: # ------------------------------------------------------------------- user.name
11538:         } elsif ($space eq 'name') {
11539:             return $uname;
11540: # ---------------------------------------------------- Any other user namespace
11541:         } else {
11542: 	    my %reply;
11543: 	    if (!$publicuser) {
11544: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11545: 	    }
11546: 	    return $reply{$qualifierrest};
11547:         }
11548:     } elsif ($realm eq 'query') {
11549: # ---------------------------------------------- pull stuff out of query string
11550:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11551: 						[$spacequalifierrest]);
11552: 	return $env{'form.'.$spacequalifierrest}; 
11553:    } elsif ($realm eq 'request') {
11554: # ------------------------------------------------------------- request.browser
11555:         if ($space eq 'browser') {
11556:             return $env{'browser.'.$qualifier};
11557: # ------------------------------------------------------------ request.filename
11558:         } else {
11559:             return $env{'request.'.$spacequalifierrest};
11560:         }
11561:     } elsif ($realm eq 'course') {
11562: # ---------------------------------------------------------- course.description
11563:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11564:     } elsif ($realm eq 'resource') {
11565: 
11566: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11567: 	    if (!$symbparm) { $symbparm=&symbread(); }
11568: 	}
11569: 
11570:         if ($qualifier eq '') {
11571: 	    if ($space eq 'title') {
11572: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11573: 	        return &gettitle($symbparm);
11574: 	    }
11575: 	
11576: 	    if ($space eq 'map') {
11577: 	        my ($map) = &decode_symb($symbparm);
11578: 	        return &symbread($map);
11579: 	    }
11580:             if ($space eq 'maptitle') {
11581:                 my ($map) = &decode_symb($symbparm);
11582:                 return &gettitle($map);
11583:             }
11584: 	    if ($space eq 'filename') {
11585: 	        if ($symbparm) {
11586: 		    return &clutter((&decode_symb($symbparm))[2]);
11587: 	        }
11588: 	        return &hreflocation('',$env{'request.filename'});
11589: 	    }
11590: 
11591:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11592:                 if ($space eq 'visibleparts') {
11593:                     my $navmap = Apache::lonnavmaps::navmap->new();
11594:                     my $item;
11595:                     if (ref($navmap)) {
11596:                         my $res = $navmap->getBySymb($symbparm);
11597:                         my $parts = $res->parts();
11598:                         if (ref($parts) eq 'ARRAY') {
11599:                             $item = join(',',@{$parts});
11600:                         }
11601:                         undef($navmap);
11602:                     }
11603:                     return $item;
11604:                 }
11605:             }
11606:         }
11607: 
11608: 	my ($section, $group, @groups, @recurseup, $recursed);
11609: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11610:         if (($courseid eq '') && ($cid)) {
11611:             $courseid = $cid;
11612:         }
11613: 	if (($symbparm && $courseid) && 
11614: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11615: 
11616: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11617: 
11618: # ----------------------------------------------------- Cascading lookup scheme
11619: 	    my $symbp=$symbparm;
11620: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11621: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11622:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11623: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11624: 	    if (($env{'user.name'} eq $uname) &&
11625: 		($env{'user.domain'} eq $udom)) {
11626: 		$section=$env{'request.course.sec'};
11627:                 @groups = split(/:/,$env{'request.course.groups'});  
11628:                 @groups=&sort_course_groups($courseid,@groups); 
11629: 	    } else {
11630: 		if (! defined($usection)) {
11631: 		    $section=&getsection($udom,$uname,$courseid);
11632: 		} else {
11633: 		    $section = $usection;
11634: 		}
11635:                 @groups = &get_users_groups($udom,$uname,$courseid);
11636: 	    }
11637: 
11638: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11639: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11640:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11641: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11642: 
11643: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11644: 	    my $courselevelr=$courseid.'.'.$symbparm;
11645:             $courseleveli=$courseid.'.'.$recurseparm;
11646: 	    $courselevelm=$courseid.'.'.$mapparm;
11647: 
11648: # ----------------------------------------------------------- first, check user
11649: 
11650: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11651:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11652: 				       ([$courselevelr,'resource'],
11653: 					[$courselevelm,'map'     ],
11654:                                         [$courseleveli,'map'     ],
11655: 					[$courselevel, 'course'  ]));
11656: 	    if (defined($userreply)) { return &get_reply($userreply); }
11657: 
11658: # ------------------------------------------------ second, check some of course
11659:             my $coursereply;
11660:             if (@groups > 0) {
11661:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11662:                                        $recurseparm,$mapparm,$spacequalifierrest,
11663:                                        $mapp,\$recursed,\@recurseup);
11664:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11665:             }
11666: 
11667: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11668: 				  $env{'course.'.$courseid.'.domain'},
11669: 				  'course',$mapp,\$recursed,\@recurseup,
11670:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11671: 				  ([$seclevelr,   'resource'],
11672: 				   [$seclevelm,   'map'     ],
11673:                                    [$secleveli,   'map'     ],
11674: 				   [$seclevel,    'course'  ],
11675: 				   [$courselevelr,'resource']));
11676: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11677: 
11678: # ------------------------------------------------------ third, check map parms
11679: 	    my %parmhash=();
11680: 	    my $thisparm='';
11681: 	    if (tie(%parmhash,'GDBM_File',
11682: 		    $env{'request.course.fn'}.'_parms.db',
11683: 		    &GDBM_READER(),0640)) {
11684: 		$thisparm=$parmhash{$symbparm};
11685: 		untie(%parmhash);
11686: 	    }
11687: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11688: 	}
11689: # ------------------------------------------ fourth, look in resource metadata
11690:  
11691:         my $what = $spacequalifierrest;
11692: 	$what=~s/\./\_/;
11693: 	my $filename;
11694: 	if (!$symbparm) { $symbparm=&symbread(); }
11695: 	if ($symbparm) {
11696: 	    $filename=(&decode_symb($symbparm))[2];
11697: 	} else {
11698: 	    $filename=$env{'request.filename'};
11699: 	}
11700:         my $toolsymb;
11701:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11702:             $toolsymb = $symbparm;
11703:         }
11704: 	my $metadata=&metadata($filename,$what,$toolsymb);
11705: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11706: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11707: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11708: 
11709: # ----------------------------------------------- fifth, look in rest of course
11710: 	if ($symbparm && defined($courseid) && 
11711: 	    $courseid eq $env{'request.course.id'}) {
11712: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11713: 				     $env{'course.'.$courseid.'.domain'},
11714: 				     'course',$mapp,\$recursed,\@recurseup,
11715:                                      $courseid,'.',$spacequalifierrest,
11716: 				     ([$courselevelm,'map'   ],
11717:                                       [$courseleveli,'map'   ],
11718: 				      [$courselevel, 'course']));
11719: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11720: 	}
11721: # ------------------------------------------------------------------ Cascade up
11722: 	unless ($space eq '0') {
11723: 	    my @parts=split(/_/,$space);
11724: 	    my $id=pop(@parts);
11725: 	    my $part=join('_',@parts);
11726: 	    if ($part eq '') { $part='0'; }
11727: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11728: 				 $symbparm,$udom,$uname,$section,1);
11729: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11730: 	}
11731: 	if ($recurse) { return undef; }
11732: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11733: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11734: # ---------------------------------------------------- Any other user namespace
11735:     } elsif ($realm eq 'environment') {
11736: # ----------------------------------------------------------------- environment
11737: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11738: 	    return $env{'environment.'.$spacequalifierrest};
11739: 	} else {
11740: 	    if ($uname eq 'anonymous' && $udom eq '') {
11741: 		return '';
11742: 	    }
11743: 	    my %returnhash=&userenvironment($udom,$uname,
11744: 					    $spacequalifierrest);
11745: 	    return $returnhash{$spacequalifierrest};
11746: 	}
11747:     } elsif ($realm eq 'system') {
11748: # ----------------------------------------------------------------- system.time
11749: 	if ($space eq 'time') {
11750: 	    return time;
11751:         }
11752:     } elsif ($realm eq 'server') {
11753: # ----------------------------------------------------------------- system.time
11754: 	if ($space eq 'name') {
11755: 	    return $ENV{'SERVER_NAME'};
11756:         }
11757:     }
11758:     return '';
11759: }
11760: 
11761: sub get_reply {
11762:     my ($reply_value) = @_;
11763:     if (ref($reply_value) eq 'ARRAY') {
11764:         if (wantarray) {
11765: 	    return @$reply_value;
11766:         }
11767:         return $reply_value->[0];
11768:     } else {
11769:         return $reply_value;
11770:     }
11771: }
11772: 
11773: sub check_group_parms {
11774:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11775:         $recursed,$recurseupref) = @_;
11776:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11777:                   [$what,'course']);
11778:     my $coursereply;
11779:     foreach my $group (@{$groups}) {
11780:         my @groupitems = ();
11781:         foreach my $level (@levels) {
11782:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11783:              push(@groupitems,[$item,$level->[1]]);
11784:         }
11785:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11786:                                    $env{'course.'.$courseid.'.domain'},
11787:                                    'course',$mapp,$recursed,$recurseupref,
11788:                                    $courseid,'.['.$group.'].',$what,
11789:                                    @groupitems);
11790:         last if (defined($coursereply));
11791:     }
11792:     return $coursereply;
11793: }
11794: 
11795: sub get_map_hierarchy {
11796:     my ($mapname,$courseid) = @_;
11797:     my @recurseup = ();
11798:     if ($mapname) {
11799:         if (($cachedmapkey eq $courseid) &&
11800:             (abs($cachedmaptime-time)<5)) {
11801:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11802:                 return @{$cachedmaps{$mapname}};
11803:             }
11804:         }
11805:         my $navmap = Apache::lonnavmaps::navmap->new();
11806:         if (ref($navmap)) {
11807:             @recurseup = $navmap->recurseup_maps($mapname);
11808:             undef($navmap);
11809:             $cachedmaps{$mapname} = \@recurseup;
11810:             $cachedmaptime=time;
11811:             $cachedmapkey=$courseid;
11812:         }
11813:     }
11814:     return @recurseup;
11815: }
11816: 
11817: }
11818: 
11819: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11820:     my ($courseid,@groups) = @_;
11821:     @groups = sort(@groups);
11822:     return @groups;
11823: }
11824: 
11825: sub packages_tab_default {
11826:     my ($uri,$varname,$toolsymb)=@_;
11827:     my (undef,$part,$name)=split(/\./,$varname);
11828: 
11829:     my (@extension,@specifics,$do_default);
11830:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11831: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11832: 	if ($pack_type eq 'default') {
11833: 	    $do_default=1;
11834: 	} elsif ($pack_type eq 'extension') {
11835: 	    push(@extension,[$package,$pack_type,$pack_part]);
11836: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11837: 	    # only look at packages defaults for packages that this id is
11838: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11839: 	}
11840:     }
11841:     # first look for a package that matches the requested part id
11842:     foreach my $package (@specifics) {
11843: 	my (undef,$pack_type,$pack_part)=@{$package};
11844: 	next if ($pack_part ne $part);
11845: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11846: 	    return $packagetab{"$pack_type&$name&default"};
11847: 	}
11848:     }
11849:     # look for any possible matching non extension_ package
11850:     foreach my $package (@specifics) {
11851: 	my (undef,$pack_type,$pack_part)=@{$package};
11852: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11853: 	    return $packagetab{"$pack_type&$name&default"};
11854: 	}
11855: 	if ($pack_type eq 'part') { $pack_part='0'; }
11856: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11857: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11858: 	}
11859:     }
11860:     # look for any posible extension_ match
11861:     foreach my $package (@extension) {
11862: 	my ($package,$pack_type)=@{$package};
11863: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11864: 	    return $packagetab{"$pack_type&$name&default"};
11865: 	}
11866: 	if (defined($packagetab{$package."&$name&default"})) {
11867: 	    return $packagetab{$package."&$name&default"};
11868: 	}
11869:     }
11870:     # look for a global default setting
11871:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11872: 	return $packagetab{"default&$name&default"};
11873:     }
11874:     return undef;
11875: }
11876: 
11877: sub add_prefix_and_part {
11878:     my ($prefix,$part)=@_;
11879:     my $keyroot;
11880:     if (defined($prefix) && $prefix !~ /^__/) {
11881: 	# prefix that has a part already
11882: 	$keyroot=$prefix;
11883:     } elsif (defined($prefix)) {
11884: 	# prefix that is missing a part
11885: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11886:     } else {
11887: 	# no prefix at all
11888: 	if (defined($part)) { $keyroot='_'.$part; }
11889:     }
11890:     return $keyroot;
11891: }
11892: 
11893: # ---------------------------------------------------------------- Get metadata
11894: 
11895: my %metaentry;
11896: my %importedpartids;
11897: my %importedrespids;
11898: sub metadata {
11899:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11900:     $uri=&declutter($uri);
11901:     # if it is a non metadata possible uri return quickly
11902:     if (($uri eq '') || 
11903: 	(($uri =~ m|^/*adm/|) && 
11904: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11905:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11906: 	return undef;
11907:     }
11908:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11909: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11910: 	return undef;
11911:     }
11912:     my $filename=$uri;
11913:     $uri=~s/\.meta$//;
11914: #
11915: # Is the metadata already cached?
11916: # Look at timestamp of caching
11917: # Everything is cached by the main uri, libraries are never directly cached
11918: #
11919:     if (!defined($liburi)) {
11920: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11921: 	if (defined($cached)) { return $result->{':'.$what}; }
11922:     }
11923: 
11924: #
11925: # If the uri is for an external tool the file from
11926: # which metadata should be retrieved depends on whether
11927: # the tool had been configured to be gradable (set in the Course
11928: # Editor or Resource Editor).
11929: #
11930: # If a valid symb has been included as the third arg in the call
11931: # to &metadata() that can be used to retrieve the value of
11932: # parameter_0_gradable set for the resource, and included in the
11933: # uploaded map containing the tool. The value is retrieved via
11934: # &EXT(), if a valid symb is available.  Otherwise the value of
11935: # gradable in the exttool_$marker.db file for the tool instance
11936: # is retrieved via &get().
11937: #
11938: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11939: # hiddenresource and encrypturl (during course initialization)
11940: # the map-level parameter for resource.0.gradable included in the 
11941: # uploaded map containing the tool will not yet have been stored
11942: # in the user_course_parms.db file for the user's session, so in 
11943: # this case fall back to retrieving gradable status from the
11944: # exttool_$marker.db file.
11945: #
11946: # In order to avoid an infinite loop, &metadata() will return
11947: # before a call to &EXT(), if the uri is for an external tool
11948: # and the $what for which metadata is being requested is
11949: # parameter_0_gradable or 0_gradable.
11950: #
11951: 
11952:     if ($uri =~ /ext\.tool$/) {
11953:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11954:             return;
11955:         } else {
11956:             my ($checked,$use_passback);
11957:             if ($toolsymb ne '') {
11958:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11959:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11960:                     $checked = 1;
11961:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11962:                         $use_passback = 1;
11963:                     }
11964:                 }
11965:             }
11966:             unless ($checked) {
11967:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11968:                 $marker=~s/\D//g;
11969:                 if ($marker) {
11970:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11971:                     $use_passback = $toolsettings{'gradable'};
11972:                 }
11973:             }
11974:             if ($use_passback) {
11975:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11976:             } else {
11977:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11978:             }
11979:         }
11980:     }
11981: 
11982:     {
11983: # Imported parts would go here
11984:         my @origfiletagids=();
11985:         my $importedparts=0;
11986: 
11987: # Imported responseids would go here
11988:         my $importedresponses=0;
11989: #
11990: # Is this a recursive call for a library?
11991: #
11992: #	if (! exists($metacache{$uri})) {
11993: #	    $metacache{$uri}={};
11994: #	}
11995: 	my $cachetime = 60*60;
11996:         if ($liburi) {
11997: 	    $liburi=&declutter($liburi);
11998:             $filename=$liburi;
11999:         } else {
12000: 	    &devalidate_cache_new('meta',$uri);
12001: 	    undef(%metaentry);
12002: 	}
12003:         my %metathesekeys=();
12004:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
12005: 	my $metastring;
12006: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
12007: 	    my $which = &hreflocation('','/'.($liburi || $uri));
12008: 	    $metastring = 
12009: 		&Apache::lonnet::ssi_body($which,
12010: 					  ('grade_target' => 'meta'));
12011: 	    $cachetime = 1; # only want this cached in the child not long term
12012: 	} elsif (($uri !~ m -^(editupload)/-) && 
12013:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
12014: 	    my $file=&filelocation('',&clutter($filename));
12015: 	    #push(@{$metaentry{$uri.'.file'}},$file);
12016: 	    $metastring=&getfile($file);
12017: 	}
12018:         my $parser=HTML::LCParser->new(\$metastring);
12019:         my $token;
12020:         undef %metathesekeys;
12021:         while ($token=$parser->get_token) {
12022: 	    if ($token->[0] eq 'S') {
12023: 		if (defined($token->[2]->{'package'})) {
12024: #
12025: # This is a package - get package info
12026: #
12027: 		    my $package=$token->[2]->{'package'};
12028: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12029: 		    if (defined($token->[2]->{'id'})) { 
12030: 			$keyroot.='_'.$token->[2]->{'id'}; 
12031: 		    }
12032: 		    if ($metaentry{':packages'}) {
12033: 			$metaentry{':packages'}.=','.$package.$keyroot;
12034: 		    } else {
12035: 			$metaentry{':packages'}=$package.$keyroot;
12036: 		    }
12037: 		    foreach my $pack_entry (keys(%packagetab)) {
12038: 			my $part=$keyroot;
12039: 			$part=~s/^\_//;
12040: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12041: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12042: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12043: 			    # ignore package.tab specified default values
12044:                             # here &package_tab_default() will fetch those
12045: 			    if ($subp eq 'default') { next; }
12046: 			    my $value=$packagetab{$pack_entry};
12047: 			    my $unikey;
12048: 			    if ($pack =~ /_0$/) {
12049: 				$unikey='parameter_0_'.$name;
12050: 				$part=0;
12051: 			    } else {
12052: 				$unikey='parameter'.$keyroot.'_'.$name;
12053: 			    }
12054: 			    if ($subp eq 'display') {
12055: 				$value.=' [Part: '.$part.']';
12056: 			    }
12057: 			    $metaentry{':'.$unikey.'.part'}=$part;
12058: 			    $metathesekeys{$unikey}=1;
12059: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12060: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12061: 			    }
12062: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12063: 				$metaentry{':'.$unikey}=
12064: 				    $metaentry{':'.$unikey.'.default'};
12065: 			    }
12066: 			}
12067: 		    }
12068: 		} else {
12069: #
12070: # This is not a package - some other kind of start tag
12071: #
12072: 		    my $entry=$token->[1];
12073: 		    my $unikey='';
12074: 
12075: 		    if ($entry eq 'import') {
12076: #
12077: # Importing a library here
12078: #
12079:                         my $location=$parser->get_text('/import');
12080:                         my $dir=$filename;
12081:                         $dir=~s|[^/]*$||;
12082:                         $location=&filelocation($dir,$location);
12083: 
12084:                         my $importid=$token->[2]->{'id'};
12085:                         my $importmode=$token->[2]->{'importmode'};
12086: #
12087: # Check metadata for imported file to
12088: # see if it contained response items
12089: #
12090:                         my ($origfile,@libfilekeys);
12091:                         my %currmetaentry = %metaentry;
12092:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12093:                                                            $depthcount+1));
12094:                         if (grep(/^responseorder$/,@libfilekeys)) {
12095:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12096:                                                              undef,$depthcount+1);
12097:                             if ($libresponseorder ne '') {
12098:                                 if ($#origfiletagids<0) {
12099:                                     undef(%importedrespids);
12100:                                     undef(%importedpartids);
12101:                                 }
12102:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12103:                                 if (@respids) {
12104:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12105:                                 }
12106:                                 if ($importedrespids{$importid} ne '') {
12107:                                     $importedresponses = 1;
12108: # We need to get the original file and the imported file to get the response order correct
12109: # Load and inspect original file
12110:                                     if ($#origfiletagids<0) {
12111:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12112:                                         $origfile=&getfile($origfilelocation);
12113:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12114:                                     }
12115:                                 }
12116:                             }
12117:                         }
12118: # Do not overwrite contents of %metaentry hash for resource itself with 
12119: # hash populated for imported library file
12120:                         %metaentry = %currmetaentry;
12121:                         undef(%currmetaentry);
12122:                         if ($importmode eq 'part') {
12123: # Import as part(s)
12124:                            $importedparts=1;
12125: # We need to get the original file and the imported file to get the part order correct
12126: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12127: # Load and inspect original file if we didn't do that already
12128:                            if ($#origfiletagids<0) {
12129:                                undef(%importedrespids);
12130:                                undef(%importedpartids);
12131:                                if ($origfile eq '') {
12132:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12133:                                    $origfile=&getfile($origfilelocation);
12134:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12135:                                }
12136:                            }
12137:                            my @impfilepartids;
12138: # If <partorder> tag is included in metadata for the imported file
12139: # get the parts in the imported file from that.
12140:                            if (grep(/^partorder$/,@libfilekeys)) {
12141:                                %currmetaentry = %metaentry;
12142:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12143:                                                             $depthcount+1);
12144:                                %metaentry = %currmetaentry;
12145:                                undef(%currmetaentry);
12146:                                if ($libpartorder ne '') {
12147:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12148:                                }
12149:                            } else {
12150: # If no <partorder> tag available, load and inspect imported file
12151:                                my $impfile=&getfile($location);
12152:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12153:                            }
12154:                            if ($#impfilepartids>=0) {
12155: # This problem had parts
12156:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12157:                            } else {
12158: # Importing by turning a single problem into a problem part
12159: # It gets the import-tags ID as part-ID
12160:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12161:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12162:                            }
12163:                         } else {
12164: # Import as problem or as normal import
12165:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12166:                             unless ($importmode eq 'problem') {
12167: # Normal import
12168:                                 if (defined($token->[2]->{'id'})) {
12169:                                     $unikey.='_'.$token->[2]->{'id'};
12170:                                 }
12171:                             }
12172: # Check metadata for imported file to
12173: # see if it contained parts
12174:                             if (grep(/^partorder$/,@libfilekeys)) {
12175:                                 %currmetaentry = %metaentry;
12176:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12177:                                                              $depthcount+1);
12178:                                 %metaentry = %currmetaentry;
12179:                                 undef(%currmetaentry);
12180:                                 if ($libpartorder ne '') {
12181:                                     $importedparts = 1;
12182:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12183:                                 }
12184:                             }
12185:                         }
12186: 			if ($depthcount<20) {
12187: 			    my $metadata = 
12188: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12189: 					  $depthcount+1);
12190: 			    foreach my $meta (split(',',$metadata)) {
12191: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12192: 				$metathesekeys{$meta}=1;
12193: 			    }
12194:                         }
12195: 		    } else {
12196: #
12197: # Not importing, some other kind of non-package, non-library start tag
12198: # 
12199:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12200:                         if (defined($token->[2]->{'id'})) {
12201:                             $unikey.='_'.$token->[2]->{'id'};
12202:                         }
12203: 			if (defined($token->[2]->{'name'})) { 
12204: 			    $unikey.='_'.$token->[2]->{'name'}; 
12205: 			}
12206: 			$metathesekeys{$unikey}=1;
12207: 			foreach my $param (@{$token->[3]}) {
12208: 			    $metaentry{':'.$unikey.'.'.$param} =
12209: 				$token->[2]->{$param};
12210: 			}
12211: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12212: 			my $default=$metaentry{':'.$unikey.'.default'};
12213: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12214: 		 # only ws inside the tag, and not in default, so use default
12215: 		 # as value
12216: 			    $metaentry{':'.$unikey}=$default;
12217: 			} elsif ( $internaltext =~ /\S/ ) {
12218: 		  # something interesting inside the tag
12219: 			    $metaentry{':'.$unikey}=$internaltext;
12220: 			} else {
12221: 		  # no interesting values, don't set a default
12222: 			}
12223: # end of not-a-package not-a-library import
12224: 		    }
12225: # end of not-a-package start tag
12226: 		}
12227: # the next is the end of "start tag"
12228: 	    }
12229: 	}
12230: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12231: 	$extension = lc($extension);
12232: 	if ($extension eq 'htm') { $extension='html'; }
12233: 
12234: 	foreach my $key (keys(%packagetab)) {
12235: 	    #no specific packages #how's our extension
12236: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12237: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12238: 					 \%metathesekeys);
12239: 	}
12240: 
12241: 	if (!exists($metaentry{':packages'})
12242: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12243: 	    foreach my $key (keys(%packagetab)) {
12244: 		#no specific packages well let's get default then
12245: 		if ($key!~/^default&/) { next; }
12246: 		&metadata_create_package_def($uri,$key,'default',
12247: 					     \%metathesekeys);
12248: 	    }
12249: 	}
12250: # are there custom rights to evaluate
12251: 	if ($metaentry{':copyright'} eq 'custom') {
12252: 
12253:     #
12254:     # Importing a rights file here
12255:     #
12256: 	    unless ($depthcount) {
12257: 		my $location=$metaentry{':customdistributionfile'};
12258: 		my $dir=$filename;
12259: 		$dir=~s|[^/]*$||;
12260: 		$location=&filelocation($dir,$location);
12261: 		my $rights_metadata =
12262: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12263: 			      $depthcount+1);
12264: 		foreach my $rights (split(',',$rights_metadata)) {
12265: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12266: 		    $metathesekeys{$rights}=1;
12267: 		}
12268: 	    }
12269: 	}
12270: 	# uniqifiy package listing
12271: 	my %seen;
12272: 	my @uniq_packages =
12273: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12274: 	$metaentry{':packages'} = join(',',@uniq_packages);
12275: 
12276:         if (($importedresponses) || ($importedparts)) {
12277:             if ($importedparts) {
12278: # We had imported parts and need to rebuild partorder
12279:                 $metaentry{':partorder'}='';
12280:                 $metathesekeys{'partorder'}=1;
12281:             }
12282:             if ($importedresponses) {
12283: # We had imported responses and need to rebuil responseorder
12284:                 $metaentry{':responseorder'}='';
12285:                 $metathesekeys{'responseorder'}=1;
12286:             }
12287:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12288:                 my $origid = $origfiletagids[$index+1];
12289:                 if ($origfiletagids[$index] eq 'part') {
12290: # Original part, part of the problem
12291:                     if ($importedparts) {
12292:                         $metaentry{':partorder'}.=','.$origid;
12293:                     }
12294:                 } elsif ($origfiletagids[$index] eq 'import') {
12295:                     if ($importedparts) {
12296: # We have imported parts at this position
12297:                         if ($importedpartids{$origid} ne '') {
12298:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12299:                         }
12300:                     }
12301:                     if ($importedresponses) {
12302: # We have imported responses at this position
12303:                         if ($importedrespids{$origid} ne '') {
12304:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12305:                         }
12306:                     }
12307:                 } else {
12308: # Original response item, part of the problem
12309:                     if ($importedresponses) {
12310:                         $metaentry{':responseorder'}.=','.$origid;
12311:                     }
12312:                 }
12313:             }
12314:             if ($importedparts) {
12315:                 $metaentry{':partorder'}=~s/^\,//;
12316:             }
12317:             if ($importedresponses) {
12318:                 $metaentry{':responseorder'}=~s/^\,//;
12319:             }
12320:         }
12321: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12322: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12323: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12324:         unless ($liburi) {
12325: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12326:         }
12327: # this is the end of "was not already recently cached
12328:     }
12329:     return $metaentry{':'.$what};
12330: }
12331: 
12332: sub metadata_create_package_def {
12333:     my ($uri,$key,$package,$metathesekeys)=@_;
12334:     my ($pack,$name,$subp)=split(/\&/,$key);
12335:     if ($subp eq 'default') { next; }
12336:     
12337:     if (defined($metaentry{':packages'})) {
12338: 	$metaentry{':packages'}.=','.$package;
12339:     } else {
12340: 	$metaentry{':packages'}=$package;
12341:     }
12342:     my $value=$packagetab{$key};
12343:     my $unikey;
12344:     $unikey='parameter_0_'.$name;
12345:     $metaentry{':'.$unikey.'.part'}=0;
12346:     $$metathesekeys{$unikey}=1;
12347:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12348: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12349:     }
12350:     if (defined($metaentry{':'.$unikey.'.default'})) {
12351: 	$metaentry{':'.$unikey}=
12352: 	    $metaentry{':'.$unikey.'.default'};
12353:     }
12354: }
12355: 
12356: sub metadata_generate_part0 {
12357:     my ($metadata,$metacache,$uri) = @_;
12358:     my %allnames;
12359:     foreach my $metakey (keys(%$metadata)) {
12360: 	if ($metakey=~/^parameter\_(.*)/) {
12361: 	  my $part=$$metacache{':'.$metakey.'.part'};
12362: 	  my $name=$$metacache{':'.$metakey.'.name'};
12363: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12364: 	    $allnames{$name}=$part;
12365: 	  }
12366: 	}
12367:     }
12368:     foreach my $name (keys(%allnames)) {
12369:       $$metadata{"parameter_0_$name"}=1;
12370:       my $key=":parameter_0_$name";
12371:       $$metacache{"$key.part"}='0';
12372:       $$metacache{"$key.name"}=$name;
12373:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12374: 					   $allnames{$name}.'_'.$name.
12375: 					   '.type'};
12376:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12377: 			     '.display'};
12378:       my $expr='[Part: '.$allnames{$name}.']';
12379:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12380:       $$metacache{"$key.display"}=$olddis;
12381:     }
12382: }
12383: 
12384: # ------------------------------------------------------ Devalidate title cache
12385: 
12386: sub devalidate_title_cache {
12387:     my ($url)=@_;
12388:     if (!$env{'request.course.id'}) { return; }
12389:     my $symb=&symbread($url);
12390:     if (!$symb) { return; }
12391:     my $key=$env{'request.course.id'}."\0".$symb;
12392:     &devalidate_cache_new('title',$key);
12393: }
12394: 
12395: # ------------------------------------------------- Get the title of a course
12396: 
12397: sub current_course_title {
12398:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12399: }
12400: # ------------------------------------------------- Get the title of a resource
12401: 
12402: sub gettitle {
12403:     my $urlsymb=shift;
12404:     my $symb=&symbread($urlsymb);
12405:     if ($symb) {
12406: 	my $key=$env{'request.course.id'}."\0".$symb;
12407: 	my ($result,$cached)=&is_cached_new('title',$key);
12408: 	if (defined($cached)) { 
12409: 	    return $result;
12410: 	}
12411: 	my ($map,$resid,$url)=&decode_symb($symb);
12412: 	my $title='';
12413: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12414: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12415: 	} else {
12416: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12417: 		    &GDBM_READER(),0640)) {
12418: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12419: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12420: 		untie(%bighash);
12421: 	    }
12422: 	}
12423: 	$title=~s/\&colon\;/\:/gs;
12424: 	if ($title) {
12425: # Remember both $symb and $title for dynamic metadata
12426:             $accesshash{$symb.'___crstitle'}=$title;
12427:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12428: # Cache this title and then return it
12429: 	    return &do_cache_new('title',$key,$title,600);
12430: 	}
12431: 	$urlsymb=$url;
12432:     }
12433:     my $title=&metadata($urlsymb,'title');
12434:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12435:     return $title;
12436: }
12437: 
12438: sub get_slot {
12439:     my ($which,$cnum,$cdom)=@_;
12440:     if (!$cnum || !$cdom) {
12441: 	(undef,my $courseid)=&whichuser();
12442: 	$cdom=$env{'course.'.$courseid.'.domain'};
12443: 	$cnum=$env{'course.'.$courseid.'.num'};
12444:     }
12445:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12446:     my %slotinfo;
12447:     if (exists($remembered{$key})) {
12448: 	$slotinfo{$which} = $remembered{$key};
12449:     } else {
12450: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12451: 	&Apache::lonhomework::showhash(%slotinfo);
12452: 	my ($tmp)=keys(%slotinfo);
12453: 	if ($tmp=~/^error:/) { return (); }
12454: 	$remembered{$key} = $slotinfo{$which};
12455:     }
12456:     if (ref($slotinfo{$which}) eq 'HASH') {
12457: 	return %{$slotinfo{$which}};
12458:     }
12459:     return $slotinfo{$which};
12460: }
12461: 
12462: sub get_reservable_slots {
12463:     my ($cnum,$cdom,$uname,$udom) = @_;
12464:     my $now = time;
12465:     my $reservable_info;
12466:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12467:     if (exists($remembered{$key})) {
12468:         $reservable_info = $remembered{$key};
12469:     } else {
12470:         my %resv;
12471:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12472:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12473:         $reservable_info = \%resv;
12474:         $remembered{$key} = $reservable_info;
12475:     }
12476:     return $reservable_info;
12477: }
12478: 
12479: sub get_course_slots {
12480:     my ($cnum,$cdom) = @_;
12481:     my $hashid=$cnum.':'.$cdom;
12482:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12483:     if (defined($cached)) {
12484:         if (ref($result) eq 'HASH') {
12485:             return %{$result};
12486:         }
12487:     } else {
12488:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12489:         my ($tmp) = keys(%slots);
12490:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12491:             &do_cache_new('allslots',$hashid,\%slots,600);
12492:             return %slots;
12493:         }
12494:     }
12495:     return;
12496: }
12497: 
12498: sub devalidate_slots_cache {
12499:     my ($cnum,$cdom)=@_;
12500:     my $hashid=$cnum.':'.$cdom;
12501:     &devalidate_cache_new('allslots',$hashid);
12502: }
12503: 
12504: sub get_coursechange {
12505:     my ($cdom,$cnum) = @_;
12506:     if ($cdom eq '' || $cnum eq '') {
12507:         return unless ($env{'request.course.id'});
12508:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12509:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12510:     }
12511:     my $hashid=$cdom.'_'.$cnum;
12512:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12513:     if ((defined($cached)) && ($change ne '')) {
12514:         return $change;
12515:     } else {
12516:         my %crshash;
12517:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12518:         if ($crshash{'internal.contentchange'} eq '') {
12519:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12520:             if ($change eq '') {
12521:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12522:                 $change = $crshash{'internal.created'};
12523:             }
12524:         } else {
12525:             $change = $crshash{'internal.contentchange'};
12526:         }
12527:         my $cachetime = 600;
12528:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12529:     }
12530:     return $change;
12531: }
12532: 
12533: sub devalidate_coursechange_cache {
12534:     my ($cnum,$cdom)=@_;
12535:     my $hashid=$cnum.':'.$cdom;
12536:     &devalidate_cache_new('crschange',$hashid);
12537: }
12538: 
12539: # ------------------------------------------------- Update symbolic store links
12540: 
12541: sub symblist {
12542:     my ($mapname,%newhash)=@_;
12543:     $mapname=&deversion(&declutter($mapname));
12544:     my %hash;
12545:     if (($env{'request.course.fn'}) && (%newhash)) {
12546:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12547:                       &GDBM_WRCREAT(),0640)) {
12548: 	    foreach my $url (keys(%newhash)) {
12549: 		next if ($url eq 'last_known'
12550: 			 && $env{'form.no_update_last_known'});
12551: 		$hash{declutter($url)}=&encode_symb($mapname,
12552: 						    $newhash{$url}->[1],
12553: 						    $newhash{$url}->[0]);
12554:             }
12555:             if (untie(%hash)) {
12556: 		return 'ok';
12557:             }
12558:         }
12559:     }
12560:     return 'error';
12561: }
12562: 
12563: # --------------------------------------------------------------- Verify a symb
12564: 
12565: sub symbverify {
12566:     my ($symb,$thisurl,$encstate)=@_;
12567:     my $thisfn=$thisurl;
12568:     $thisfn=&declutter($thisfn);
12569: # direct jump to resource in page or to a sequence - will construct own symbs
12570:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12571: # check URL part
12572:     my ($map,$resid,$url)=&decode_symb($symb);
12573: 
12574:     unless ($url eq $thisfn) { return 0; }
12575: 
12576:     $symb=&symbclean($symb);
12577:     $thisurl=&deversion($thisurl);
12578:     $thisfn=&deversion($thisfn);
12579: 
12580:     my %bighash;
12581:     my $okay=0;
12582: 
12583:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12584:                             &GDBM_READER(),0640)) {
12585:         my $noclutter;
12586:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12587:             $thisurl =~ s/\?.+$//;
12588:             if ($map =~ m{^uploaded/.+\.page$}) {
12589:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12590:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12591:                 $noclutter = 1;
12592:             }
12593:         }
12594:         my $ids;
12595:         if ($noclutter) {
12596:             $ids=$bighash{'ids_'.$thisurl};
12597:         } else {
12598:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12599:         }
12600:         unless ($ids) {
12601:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12602:             $ids=$bighash{$idkey};
12603:         }
12604:         if ($ids) {
12605: # ------------------------------------------------------------------- Has ID(s)
12606:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12607:                 $symb =~ s/\?.+$//;
12608:             }
12609: 	    foreach my $id (split(/\,/,$ids)) {
12610: 	       my ($mapid,$resid)=split(/\./,$id);
12611:                if (
12612:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12613:    eq $symb) {
12614:                    if (ref($encstate)) {
12615:                        $$encstate = $bighash{'encrypted_'.$id};
12616:                    }
12617: 		   if (($env{'request.role.adv'}) ||
12618: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12619:                        ($thisurl eq '/adm/navmaps')) {
12620: 		       $okay=1;
12621:                        last;
12622: 		   }
12623: 	       }
12624: 	   }
12625:         }
12626: 	untie(%bighash);
12627:     }
12628:     return $okay;
12629: }
12630: 
12631: # --------------------------------------------------------------- Clean-up symb
12632: 
12633: sub symbclean {
12634:     my $symb=shift;
12635:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12636: # remove version from map
12637:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12638: 
12639: # remove version from URL
12640:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12641: 
12642: # remove wrapper
12643: 
12644:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12645:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12646:     return $symb;
12647: }
12648: 
12649: # ---------------------------------------------- Split symb to find map and url
12650: 
12651: sub encode_symb {
12652:     my ($map,$resid,$url)=@_;
12653:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12654: }
12655: 
12656: sub decode_symb {
12657:     my $symb=shift;
12658:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12659:     my ($map,$resid,$url)=split(/___/,$symb);
12660:     return (&fixversion($map),$resid,&fixversion($url));
12661: }
12662: 
12663: sub fixversion {
12664:     my $fn=shift;
12665:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12666:     my %bighash;
12667:     my $uri=&clutter($fn);
12668:     my $key=$env{'request.course.id'}.'_'.$uri;
12669: # is this cached?
12670:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12671:     if (defined($cached)) { return $result; }
12672: # unfortunately not cached, or expired
12673:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12674: 	    &GDBM_READER(),0640)) {
12675:  	if ($bighash{'version_'.$uri}) {
12676:  	    my $version=$bighash{'version_'.$uri};
12677:  	    unless (($version eq 'mostrecent') || 
12678: 		    ($version==&getversion($uri))) {
12679:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12680:  	    }
12681:  	}
12682:  	untie %bighash;
12683:     }
12684:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12685: }
12686: 
12687: sub deversion {
12688:     my $url=shift;
12689:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12690:     return $url;
12691: }
12692: 
12693: # ------------------------------------------------------ Return symb list entry
12694: 
12695: sub symbread {
12696:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12697:     my $cache_str='request.symbread.cached.'.$thisfn;
12698:     if (defined($env{$cache_str})) {
12699:         if ($ignorecachednull) {
12700:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12701:         } else {
12702:             return $env{$cache_str};
12703:         }
12704:     }
12705: # no filename provided? try from environment
12706:     unless ($thisfn) {
12707:         if ($env{'request.symb'}) {
12708: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12709: 	}
12710: 	$thisfn=$env{'request.filename'};
12711:     }
12712:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12713: # is that filename actually a symb? Verify, clean, and return
12714:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12715: 	if (&symbverify($thisfn,$1)) {
12716: 	    return $env{$cache_str}=&symbclean($thisfn);
12717: 	}
12718:     }
12719:     $thisfn=declutter($thisfn);
12720:     my %hash;
12721:     my %bighash;
12722:     my $syval='';
12723:     if (($env{'request.course.fn'}) && ($thisfn)) {
12724:         my $targetfn = $thisfn;
12725:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12726:             $targetfn = 'adm/wrapper/'.$thisfn;
12727:         }
12728: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12729: 	    $targetfn=$1;
12730: 	}
12731:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12732:                       &GDBM_READER(),0640)) {
12733: 	    $syval=$hash{$targetfn};
12734:             untie(%hash);
12735:         }
12736: # ---------------------------------------------------------- There was an entry
12737:         if ($syval) {
12738: 	    #unless ($syval=~/\_\d+$/) {
12739: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12740: 		    #&appenv({'request.ambiguous' => $thisfn});
12741: 		    #return $env{$cache_str}='';
12742: 		#}    
12743: 		#$syval.=$1;
12744: 	    #}
12745:         } else {
12746: # ------------------------------------------------------- Was not in symb table
12747:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12748:                             &GDBM_READER(),0640)) {
12749: # ---------------------------------------------- Get ID(s) for current resource
12750:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12751:               unless ($ids) { 
12752:                  $ids=$bighash{'ids_/'.$thisfn};
12753:               }
12754:               unless ($ids) {
12755: # alias?
12756: 		  $ids=$bighash{'mapalias_'.$thisfn};
12757:               }
12758:               if ($ids) {
12759: # ------------------------------------------------------------------- Has ID(s)
12760:                  my @possibilities=split(/\,/,$ids);
12761:                  if ($#possibilities==0) {
12762: # ----------------------------------------------- There is only one possibility
12763: 		     my ($mapid,$resid)=split(/\./,$ids);
12764: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12765: 						    $resid,$thisfn);
12766:                      if (ref($possibles) eq 'HASH') {
12767:                          $possibles->{$syval} = 1;    
12768:                      }
12769:                      if ($checkforblock) {
12770:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12771:                          if (@blockers) {
12772:                              $syval = '';
12773:                              return;
12774:                          }
12775:                      }
12776:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12777: # ------------------------------------------ There is more than one possibility
12778:                      my $realpossible=0;
12779:                      foreach my $id (@possibilities) {
12780: 			 my $file=$bighash{'src_'.$id};
12781:                          my $canaccess;
12782:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12783:                              $canaccess = 1;
12784:                          } else { 
12785:                              $canaccess = &allowed('bre',$file);
12786:                          }
12787:                          if ($canaccess) {
12788:          		     my ($mapid,$resid)=split(/\./,$id);
12789:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12790:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12791: 						             $resid,$thisfn);
12792:                                  if (ref($possibles) eq 'HASH') {
12793:                                      $possibles->{$syval} = 1;
12794:                                  }
12795:                                  if ($checkforblock) {
12796:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12797:                                      unless (@blockers > 0) {
12798:                                          $syval = $poss_syval;
12799:                                          $realpossible++;
12800:                                      }
12801:                                  } else {
12802:                                      $syval = $poss_syval;
12803:                                      $realpossible++;
12804:                                  }
12805:                              }
12806: 			 }
12807:                      }
12808: 		     if ($realpossible!=1) { $syval=''; }
12809:                  } else {
12810:                      $syval='';
12811:                  }
12812: 	      }
12813:               untie(%bighash);
12814:            }
12815:         }
12816:         if ($syval) {
12817: 	    return $env{$cache_str}=$syval;
12818:         }
12819:     }
12820:     &appenv({'request.ambiguous' => $thisfn});
12821:     return $env{$cache_str}='';
12822: }
12823: 
12824: # ---------------------------------------------------------- Return random seed
12825: 
12826: sub numval {
12827:     my $txt=shift;
12828:     $txt=~tr/A-J/0-9/;
12829:     $txt=~tr/a-j/0-9/;
12830:     $txt=~tr/K-T/0-9/;
12831:     $txt=~tr/k-t/0-9/;
12832:     $txt=~tr/U-Z/0-5/;
12833:     $txt=~tr/u-z/0-5/;
12834:     $txt=~s/\D//g;
12835:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12836:     return int($txt);
12837: }
12838: 
12839: sub numval2 {
12840:     my $txt=shift;
12841:     $txt=~tr/A-J/0-9/;
12842:     $txt=~tr/a-j/0-9/;
12843:     $txt=~tr/K-T/0-9/;
12844:     $txt=~tr/k-t/0-9/;
12845:     $txt=~tr/U-Z/0-5/;
12846:     $txt=~tr/u-z/0-5/;
12847:     $txt=~s/\D//g;
12848:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12849:     my $total;
12850:     foreach my $val (@txts) { $total+=$val; }
12851:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12852:     return int($total);
12853: }
12854: 
12855: sub numval3 {
12856:     use integer;
12857:     my $txt=shift;
12858:     $txt=~tr/A-J/0-9/;
12859:     $txt=~tr/a-j/0-9/;
12860:     $txt=~tr/K-T/0-9/;
12861:     $txt=~tr/k-t/0-9/;
12862:     $txt=~tr/U-Z/0-5/;
12863:     $txt=~tr/u-z/0-5/;
12864:     $txt=~s/\D//g;
12865:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12866:     my $total;
12867:     foreach my $val (@txts) { $total+=$val; }
12868:     if ($_64bit) { $total=(($total<<32)>>32); }
12869:     return $total;
12870: }
12871: 
12872: sub digest {
12873:     my ($data)=@_;
12874:     my $digest=&Digest::MD5::md5($data);
12875:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12876:     my ($e,$f);
12877:     {
12878:         use integer;
12879:         $e=($a+$b);
12880:         $f=($c+$d);
12881:         if ($_64bit) {
12882:             $e=(($e<<32)>>32);
12883:             $f=(($f<<32)>>32);
12884:         }
12885:     }
12886:     if (wantarray) {
12887: 	return ($e,$f);
12888:     } else {
12889: 	my $g;
12890: 	{
12891: 	    use integer;
12892: 	    $g=($e+$f);
12893: 	    if ($_64bit) {
12894: 		$g=(($g<<32)>>32);
12895: 	    }
12896: 	}
12897: 	return $g;
12898:     }
12899: }
12900: 
12901: sub latest_rnd_algorithm_id {
12902:     return '64bit5';
12903: }
12904: 
12905: sub get_rand_alg {
12906:     my ($courseid)=@_;
12907:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12908:     if ($courseid) {
12909: 	return $env{"course.$courseid.rndseed"};
12910:     }
12911:     return &latest_rnd_algorithm_id();
12912: }
12913: 
12914: sub validCODE {
12915:     my ($CODE)=@_;
12916:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12917:     return 0;
12918: }
12919: 
12920: sub getCODE {
12921:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12922:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12923: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12924: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12925: 	return $Apache::lonhomework::history{'resource.CODE'};
12926:     }
12927:     return undef;
12928: }
12929: #
12930: #  Determines the random seed for a specific context:
12931: #
12932: # parameters:
12933: #   symb      - in course context the symb for the seed.
12934: #   course_id - The course id of the form domain_coursenum.
12935: #   domain    - Domain for the user.
12936: #   course    - Course for the user.
12937: #   cenv      - environment of the course.
12938: #
12939: # NOTE:
12940: #   All parameters are picked out of the environment if missing
12941: #   or not defined.
12942: #   If a symb cannot be determined the current time is used instead.
12943: #
12944: #  For a given well defined symb, courside, domain, username,
12945: #  and course environment, the seed is reproducible.
12946: #
12947: sub rndseed {
12948:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12949:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12950:     if (!defined($symb)) {
12951: 	unless ($symb=$wsymb) { return time; }
12952:     }
12953:     if (!defined $courseid) { 
12954: 	$courseid=$wcourseid; 
12955:     }
12956:     if (!defined $domain) { $domain=$wdomain; }
12957:     if (!defined $username) { $username=$wusername }
12958: 
12959:     my $which;
12960:     if (defined($cenv->{'rndseed'})) {
12961: 	$which = $cenv->{'rndseed'};
12962:     } else {
12963: 	$which =&get_rand_alg($courseid);
12964:     }
12965:     if (defined(&getCODE())) {
12966: 
12967: 	if ($which eq '64bit5') {
12968: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12969: 	} elsif ($which eq '64bit4') {
12970: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12971: 	} else {
12972: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12973: 	}
12974:     } elsif ($which eq '64bit5') {
12975: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12976:     } elsif ($which eq '64bit4') {
12977: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12978:     } elsif ($which eq '64bit3') {
12979: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12980:     } elsif ($which eq '64bit2') {
12981: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12982:     } elsif ($which eq '64bit') {
12983: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12984:     }
12985:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12986: }
12987: 
12988: sub rndseed_32bit {
12989:     my ($symb,$courseid,$domain,$username)=@_;
12990:     {
12991: 	use integer;
12992: 	my $symbchck=unpack("%32C*",$symb) << 27;
12993: 	my $symbseed=numval($symb) << 22;
12994: 	my $namechck=unpack("%32C*",$username) << 17;
12995: 	my $nameseed=numval($username) << 12;
12996: 	my $domainseed=unpack("%32C*",$domain) << 7;
12997: 	my $courseseed=unpack("%32C*",$courseid);
12998: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12999: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13000: 	#&logthis("rndseed :$num:$symb");
13001: 	if ($_64bit) { $num=(($num<<32)>>32); }
13002: 	return $num;
13003:     }
13004: }
13005: 
13006: sub rndseed_64bit {
13007:     my ($symb,$courseid,$domain,$username)=@_;
13008:     {
13009: 	use integer;
13010: 	my $symbchck=unpack("%32S*",$symb) << 21;
13011: 	my $symbseed=numval($symb) << 10;
13012: 	my $namechck=unpack("%32S*",$username);
13013: 	
13014: 	my $nameseed=numval($username) << 21;
13015: 	my $domainseed=unpack("%32S*",$domain) << 10;
13016: 	my $courseseed=unpack("%32S*",$courseid);
13017: 	
13018: 	my $num1=$symbchck+$symbseed+$namechck;
13019: 	my $num2=$nameseed+$domainseed+$courseseed;
13020: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13021: 	#&logthis("rndseed :$num:$symb");
13022: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13023: 	return "$num1,$num2";
13024:     }
13025: }
13026: 
13027: sub rndseed_64bit2 {
13028:     my ($symb,$courseid,$domain,$username)=@_;
13029:     {
13030: 	use integer;
13031: 	# strings need to be an even # of cahracters long, it it is odd the
13032:         # last characters gets thrown away
13033: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13034: 	my $symbseed=numval($symb) << 10;
13035: 	my $namechck=unpack("%32S*",$username.' ');
13036: 	
13037: 	my $nameseed=numval($username) << 21;
13038: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13039: 	my $courseseed=unpack("%32S*",$courseid.' ');
13040: 	
13041: 	my $num1=$symbchck+$symbseed+$namechck;
13042: 	my $num2=$nameseed+$domainseed+$courseseed;
13043: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13044: 	#&logthis("rndseed :$num:$symb");
13045: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13046: 	return "$num1,$num2";
13047:     }
13048: }
13049: 
13050: sub rndseed_64bit3 {
13051:     my ($symb,$courseid,$domain,$username)=@_;
13052:     {
13053: 	use integer;
13054: 	# strings need to be an even # of cahracters long, it it is odd the
13055:         # last characters gets thrown away
13056: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13057: 	my $symbseed=numval2($symb) << 10;
13058: 	my $namechck=unpack("%32S*",$username.' ');
13059: 	
13060: 	my $nameseed=numval2($username) << 21;
13061: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13062: 	my $courseseed=unpack("%32S*",$courseid.' ');
13063: 	
13064: 	my $num1=$symbchck+$symbseed+$namechck;
13065: 	my $num2=$nameseed+$domainseed+$courseseed;
13066: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13067: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13068: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13069: 	
13070: 	return "$num1:$num2";
13071:     }
13072: }
13073: 
13074: sub rndseed_64bit4 {
13075:     my ($symb,$courseid,$domain,$username)=@_;
13076:     {
13077: 	use integer;
13078: 	# strings need to be an even # of cahracters long, it it is odd the
13079:         # last characters gets thrown away
13080: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13081: 	my $symbseed=numval3($symb) << 10;
13082: 	my $namechck=unpack("%32S*",$username.' ');
13083: 	
13084: 	my $nameseed=numval3($username) << 21;
13085: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13086: 	my $courseseed=unpack("%32S*",$courseid.' ');
13087: 	
13088: 	my $num1=$symbchck+$symbseed+$namechck;
13089: 	my $num2=$nameseed+$domainseed+$courseseed;
13090: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13091: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13092: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13093: 	
13094: 	return "$num1:$num2";
13095:     }
13096: }
13097: 
13098: sub rndseed_64bit5 {
13099:     my ($symb,$courseid,$domain,$username)=@_;
13100:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13101:     return "$num1:$num2";
13102: }
13103: 
13104: sub rndseed_CODE_64bit {
13105:     my ($symb,$courseid,$domain,$username)=@_;
13106:     {
13107: 	use integer;
13108: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13109: 	my $symbseed=numval2($symb);
13110: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13111: 	my $CODEseed=numval(&getCODE());
13112: 	my $courseseed=unpack("%32S*",$courseid.' ');
13113: 	my $num1=$symbseed+$CODEchck;
13114: 	my $num2=$CODEseed+$courseseed+$symbchck;
13115: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13116: 	#&logthis("rndseed :$num1:$num2:$symb");
13117: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13118: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13119: 	return "$num1:$num2";
13120:     }
13121: }
13122: 
13123: sub rndseed_CODE_64bit4 {
13124:     my ($symb,$courseid,$domain,$username)=@_;
13125:     {
13126: 	use integer;
13127: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13128: 	my $symbseed=numval3($symb);
13129: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13130: 	my $CODEseed=numval3(&getCODE());
13131: 	my $courseseed=unpack("%32S*",$courseid.' ');
13132: 	my $num1=$symbseed+$CODEchck;
13133: 	my $num2=$CODEseed+$courseseed+$symbchck;
13134: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13135: 	#&logthis("rndseed :$num1:$num2:$symb");
13136: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13137: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13138: 	return "$num1:$num2";
13139:     }
13140: }
13141: 
13142: sub rndseed_CODE_64bit5 {
13143:     my ($symb,$courseid,$domain,$username)=@_;
13144:     my $code = &getCODE();
13145:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13146:     return "$num1:$num2";
13147: }
13148: 
13149: sub setup_random_from_rndseed {
13150:     my ($rndseed)=@_;
13151:     if ($rndseed =~/([,:])/) {
13152:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13153:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13154:             &Math::Random::random_set_seed_from_phrase($rndseed);
13155:         } else {
13156:             &Math::Random::random_set_seed($num1,$num2);
13157:         }
13158:     } else {
13159: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13160:     }
13161: }
13162: 
13163: sub latest_receipt_algorithm_id {
13164:     return 'receipt3';
13165: }
13166: 
13167: sub recunique {
13168:     my $fucourseid=shift;
13169:     my $unique;
13170:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13171: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13172: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13173:     } else {
13174: 	$unique=$perlvar{'lonReceipt'};
13175:     }
13176:     return unpack("%32C*",$unique);
13177: }
13178: 
13179: sub recprefix {
13180:     my $fucourseid=shift;
13181:     my $prefix;
13182:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13183: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13184: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13185:     } else {
13186: 	$prefix=$perlvar{'lonHostID'};
13187:     }
13188:     return unpack("%32C*",$prefix);
13189: }
13190: 
13191: sub ireceipt {
13192:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13193: 
13194:     my $return =&recprefix($fucourseid).'-';
13195: 
13196:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13197: 	$env{'request.state'} eq 'construct') {
13198: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13199: 	return $return;
13200:     }
13201: 
13202:     my $cuname=unpack("%32C*",$funame);
13203:     my $cudom=unpack("%32C*",$fudom);
13204:     my $cucourseid=unpack("%32C*",$fucourseid);
13205:     my $cusymb=unpack("%32C*",$fusymb);
13206:     my $cunique=&recunique($fucourseid);
13207:     my $cpart=unpack("%32S*",$part);
13208:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13209: 
13210: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13211: 			       
13212: 	$return.= ($cunique%$cuname+
13213: 		   $cunique%$cudom+
13214: 		   $cusymb%$cuname+
13215: 		   $cusymb%$cudom+
13216: 		   $cucourseid%$cuname+
13217: 		   $cucourseid%$cudom+
13218: 		   $cpart%$cuname+
13219: 		   $cpart%$cudom);
13220:     } else {
13221: 	$return.= ($cunique%$cuname+
13222: 		   $cunique%$cudom+
13223: 		   $cusymb%$cuname+
13224: 		   $cusymb%$cudom+
13225: 		   $cucourseid%$cuname+
13226: 		   $cucourseid%$cudom);
13227:     }
13228:     return $return;
13229: }
13230: 
13231: sub receipt {
13232:     my ($part)=@_;
13233:     my ($symb,$courseid,$domain,$name) = &whichuser();
13234:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13235: }
13236: 
13237: sub whichuser {
13238:     my ($passedsymb)=@_;
13239:     my ($symb,$courseid,$domain,$name,$publicuser);
13240:     if (defined($env{'form.grade_symb'})) {
13241: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13242: 	my $allowed=&allowed('vgr',$tmp_courseid);
13243: 	if (!$allowed &&
13244: 	    exists($env{'request.course.sec'}) &&
13245: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13246: 	    $allowed=&allowed('vgr',$tmp_courseid.
13247: 			      '/'.$env{'request.course.sec'});
13248: 	}
13249: 	if ($allowed) {
13250: 	    ($symb)=&get_env_multiple('form.grade_symb');
13251: 	    $courseid=$tmp_courseid;
13252: 	    ($domain)=&get_env_multiple('form.grade_domain');
13253: 	    ($name)=&get_env_multiple('form.grade_username');
13254: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13255: 	}
13256:     }
13257:     if (!$passedsymb) {
13258: 	$symb=&symbread();
13259:     } else {
13260: 	$symb=$passedsymb;
13261:     }
13262:     $courseid=$env{'request.course.id'};
13263:     $domain=$env{'user.domain'};
13264:     $name=$env{'user.name'};
13265:     if ($name eq 'public' && $domain eq 'public') {
13266: 	if (!defined($env{'form.username'})) {
13267: 	    $env{'form.username'}.=time.rand(10000000);
13268: 	}
13269: 	$name.=$env{'form.username'};
13270:     }
13271:     return ($symb,$courseid,$domain,$name,$publicuser);
13272: 
13273: }
13274: 
13275: # ------------------------------------------------------------ Serves up a file
13276: # returns either the contents of the file or 
13277: # -1 if the file doesn't exist
13278: #
13279: # if the target is a file that was uploaded via DOCS, 
13280: # a check will be made to see if a current copy exists on the local server,
13281: # if it does this will be served, otherwise a copy will be retrieved from
13282: # the home server for the course and stored in /home/httpd/html/userfiles on
13283: # the local server.   
13284: 
13285: sub getfile {
13286:     my ($file) = @_;
13287:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13288:     &repcopy($file);
13289:     return &readfile($file);
13290: }
13291: 
13292: sub repcopy_userfile {
13293:     my ($file)=@_;
13294:     my $londocroot = $perlvar{'lonDocRoot'};
13295:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13296:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13297:     my ($cdom,$cnum,$filename) = 
13298: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13299:     my $uri="/uploaded/$cdom/$cnum/$filename";
13300:     if (-e "$file") {
13301: # we already have a local copy, check it out
13302: 	my @fileinfo = stat($file);
13303: 	my $rtncode;
13304: 	my $info;
13305: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13306: 	if ($lwpresp ne 'ok') {
13307: # there is no such file anymore, even though we had a local copy
13308: 	    if ($rtncode eq '404') {
13309: 		unlink($file);
13310: 	    }
13311: 	    return -1;
13312: 	}
13313: 	if ($info < $fileinfo[9]) {
13314: # nice, the file we have is up-to-date, just say okay
13315: 	    return 'ok';
13316: 	} else {
13317: # the file is outdated, get rid of it
13318: 	    unlink($file);
13319: 	}
13320:     }
13321: # one way or the other, at this point, we don't have the file
13322: # construct the correct path for the file
13323:     my @parts = ($cdom,$cnum); 
13324:     if ($filename =~ m|^(.+)/[^/]+$|) {
13325: 	push @parts, split(/\//,$1);
13326:     }
13327:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13328:     foreach my $part (@parts) {
13329: 	$path .= '/'.$part;
13330: 	if (!-e $path) {
13331: 	    mkdir($path,0770);
13332: 	}
13333:     }
13334: # now the path exists for sure
13335: # get a user agent
13336:     my $transferfile=$file.'.in.transfer';
13337: # FIXME: this should flock
13338:     if (-e $transferfile) { return 'ok'; }
13339:     my $request;
13340:     $uri=~s/^\///;
13341:     my $homeserver = &homeserver($cnum,$cdom);
13342:     my $protocol = $protocol{$homeserver};
13343:     $protocol = 'http' if ($protocol ne 'https');
13344:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13345:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13346: # did it work?
13347:     if ($response->is_error()) {
13348: 	unlink($transferfile);
13349: 	&logthis("Userfile repcopy failed for $uri");
13350: 	return -1;
13351:     }
13352: # worked, rename the transfer file
13353:     rename($transferfile,$file);
13354:     return 'ok';
13355: }
13356: 
13357: sub tokenwrapper {
13358:     my $uri=shift;
13359:     $uri=~s|^https?\://([^/]+)||;
13360:     $uri=~s|^/||;
13361:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13362:     my $token=$1;
13363:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13364:     if ($udom && $uname && $file) {
13365: 	$file=~s|(\?\.*)*$||;
13366:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13367:         my $homeserver = &homeserver($uname,$udom);
13368:         my $protocol = $protocol{$homeserver};
13369:         $protocol = 'http' if ($protocol ne 'https');
13370:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13371:                (($uri=~/\?/)?'&':'?').'token='.$token.
13372:                                '&tokenissued='.$perlvar{'lonHostID'};
13373:     } else {
13374:         return '/adm/notfound.html';
13375:     }
13376: }
13377: 
13378: # call with reqtype HEAD: get last modification time
13379: # call with reqtype GET: get the file contents
13380: # Do not call this with reqtype GET for large files! It loads everything into memory
13381: #
13382: sub getuploaded {
13383:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13384:     $uri=~s/^\///;
13385:     my $homeserver = &homeserver($cnum,$cdom);
13386:     my $protocol = $protocol{$homeserver};
13387:     $protocol = 'http' if ($protocol ne 'https');
13388:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13389:     my $request=new HTTP::Request($reqtype,$uri);
13390:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13391:     $$rtncode = $response->code;
13392:     if (! $response->is_success()) {
13393: 	return 'failed';
13394:     }      
13395:     if ($reqtype eq 'HEAD') {
13396: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13397:     } elsif ($reqtype eq 'GET') {
13398: 	$$info = $response->content;
13399:     }
13400:     return 'ok';
13401: }
13402: 
13403: sub readfile {
13404:     my $file = shift;
13405:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13406:     my $fh;
13407:     open($fh,"<",$file);
13408:     my $a='';
13409:     while (my $line = <$fh>) { $a .= $line; }
13410:     return $a;
13411: }
13412: 
13413: sub filelocation {
13414:     my ($dir,$file) = @_;
13415:     my $location;
13416:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13417: 
13418:     if ($file =~ m-^/adm/-) {
13419: 	$file=~s-^/adm/wrapper/-/-;
13420: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13421:     }
13422: 
13423:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13424:         $location = $file;
13425:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13426:         my ($udom,$uname,$filename)=
13427:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13428:         my $home=&homeserver($uname,$udom);
13429:         my $is_me=0;
13430:         my @ids=&current_machine_ids();
13431:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13432:         if ($is_me) {
13433:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13434:         } else {
13435:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13436:   	      $udom.'/'.$uname.'/'.$filename;
13437:         }
13438:     } elsif ($file =~ m-^/adm/-) {
13439: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13440:     } else {
13441:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13442:         $file=~s:^/(res|priv)/:/:;
13443:         my $space=$1;
13444:         if ( !( $file =~ m:^/:) ) {
13445:             $location = $dir. '/'.$file;
13446:         } else {
13447:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13448:         }
13449:     }
13450:     $location=~s://+:/:g; # remove duplicate /
13451:     while ($location=~m{/\.\./}) {
13452: 	if ($location =~ m{/[^/]+/\.\./}) {
13453: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13454: 	} else {
13455: 	    $location=~ s{/\.\./}{/}g;
13456: 	}
13457:     } #remove dir/..
13458:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13459:     return $location;
13460: }
13461: 
13462: sub hreflocation {
13463:     my ($dir,$file)=@_;
13464:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13465: 	$file=filelocation($dir,$file);
13466:     } elsif ($file=~m-^/adm/-) {
13467: 	$file=~s-^/adm/wrapper/-/-;
13468: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13469:     }
13470:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13471: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13472:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13473: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13474: 	        {/uploaded/$1/$2/}x;
13475:     }
13476:     if ($file=~ m{^/userfiles/}) {
13477: 	$file =~ s{^/userfiles/}{/uploaded/};
13478:     }
13479:     return $file;
13480: }
13481: 
13482: 
13483: 
13484: 
13485: 
13486: sub current_machine_domains {
13487:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13488: }
13489: 
13490: sub machine_domains {
13491:     my ($hostname) = @_;
13492:     my @domains;
13493:     my %hostname = &all_hostnames();
13494:     while( my($id, $name) = each(%hostname)) {
13495: #	&logthis("-$id-$name-$hostname-");
13496: 	if ($hostname eq $name) {
13497: 	    push(@domains,&host_domain($id));
13498: 	}
13499:     }
13500:     return @domains;
13501: }
13502: 
13503: sub current_machine_ids {
13504:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13505: }
13506: 
13507: sub machine_ids {
13508:     my ($hostname) = @_;
13509:     $hostname ||= &hostname($perlvar{'lonHostID'});
13510:     my @ids;
13511:     my %name_to_host = &all_names();
13512:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13513: 	return @{ $name_to_host{$hostname} };
13514:     }
13515:     return;
13516: }
13517: 
13518: sub additional_machine_domains {
13519:     my @domains;
13520:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13521:     while( my $line = <$fh>) {
13522:         $line =~ s/\s//g;
13523:         push(@domains,$line);
13524:     }
13525:     return @domains;
13526: }
13527: 
13528: sub default_login_domain {
13529:     my $domain = $perlvar{'lonDefDomain'};
13530:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13531:     foreach my $posdom (&current_machine_domains(),
13532:                         &additional_machine_domains()) {
13533:         if (lc($posdom) eq lc($testdomain)) {
13534:             $domain=$posdom;
13535:             last;
13536:         }
13537:     }
13538:     return $domain;
13539: }
13540: 
13541: # ------------------------------------------------------------- Declutters URLs
13542: 
13543: sub declutter {
13544:     my $thisfn=shift;
13545:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13546:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13547:         $thisfn=~s{^/home/httpd/html}{};
13548:     }
13549:     $thisfn=~s/^\///;
13550:     $thisfn=~s|^adm/wrapper/||;
13551:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13552:     $thisfn=~s/^res\///;
13553:     $thisfn=~s/^priv\///;
13554:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13555:         $thisfn=~s/\?.+$//;
13556:     }
13557:     return $thisfn;
13558: }
13559: 
13560: # ------------------------------------------------------------- Clutter up URLs
13561: 
13562: sub clutter {
13563:     my $thisfn='/'.&declutter(shift);
13564:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13565: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13566:        $thisfn='/res'.$thisfn; 
13567:     }
13568:     if ($thisfn !~m|^/adm|) {
13569: 	if ($thisfn =~ m|^/ext/|) {
13570: 	    $thisfn='/adm/wrapper'.$thisfn;
13571: 	} else {
13572: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13573: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13574: 	    if ($embstyle eq 'ssi'
13575: 		|| ($embstyle eq 'hdn')
13576: 		|| ($embstyle eq 'rat')
13577: 		|| ($embstyle eq 'prv')
13578: 		|| ($embstyle eq 'ign')) {
13579: 		#do nothing with these
13580: 	    } elsif (($embstyle eq 'img') 
13581: 		|| ($embstyle eq 'emb')
13582: 		|| ($embstyle eq 'wrp')) {
13583: 		$thisfn='/adm/wrapper'.$thisfn;
13584: 	    } elsif ($embstyle eq 'unk'
13585: 		     && $thisfn!~/\.(sequence|page)$/) {
13586: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13587: 	    } else {
13588: #		&logthis("Got a blank emb style");
13589: 	    }
13590: 	}
13591:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13592:         $thisfn='/adm/wrapper'.$thisfn;
13593:     }
13594:     return $thisfn;
13595: }
13596: 
13597: sub clutter_with_no_wrapper {
13598:     my $uri = &clutter(shift);
13599:     if ($uri =~ m-^/adm/-) {
13600: 	$uri =~ s-^/adm/wrapper/-/-;
13601: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13602:     }
13603:     return $uri;
13604: }
13605: 
13606: sub freeze_escape {
13607:     my ($value)=@_;
13608:     if (ref($value)) {
13609: 	$value=&nfreeze($value);
13610: 	return '__FROZEN__'.&escape($value);
13611:     }
13612:     return &escape($value);
13613: }
13614: 
13615: 
13616: sub thaw_unescape {
13617:     my ($value)=@_;
13618:     if ($value =~ /^__FROZEN__/) {
13619: 	substr($value,0,10,undef);
13620: 	$value=&unescape($value);
13621: 	return &thaw($value);
13622:     }
13623:     return &unescape($value);
13624: }
13625: 
13626: sub correct_line_ends {
13627:     my ($result)=@_;
13628:     $$result =~s/\r\n/\n/mg;
13629:     $$result =~s/\r/\n/mg;
13630: }
13631: # ================================================================ Main Program
13632: 
13633: sub goodbye {
13634:    &logthis("Starting Shut down");
13635: #not converted to using infrastruture and probably shouldn't be
13636:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13637: #converted
13638: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13639:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13640: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13641: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13642: #1.1 only
13643: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13644: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13645: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13646: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13647:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13648:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13649:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13650:    &flushcourselogs();
13651:    &logthis("Shutting down");
13652: }
13653: 
13654: sub get_dns {
13655:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13656:     if (!$ignore_cache) {
13657: 	my ($content,$cached)=
13658: 	    &Apache::lonnet::is_cached_new('dns',$url);
13659: 	if ($cached) {
13660: 	    &$func($content,$hashref);
13661: 	    return;
13662: 	}
13663:     }
13664: 
13665:     my %alldns;
13666:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13667:         foreach my $dns (<$config>) {
13668: 	    next if ($dns !~ /^\^(\S*)/x);
13669:             my $line = $1;
13670:             my ($host,$protocol) = split(/:/,$line);
13671:             if ($protocol ne 'https') {
13672:                 $protocol = 'http';
13673:             }
13674: 	    $alldns{$host} = $protocol;
13675:         }
13676:         close($config);
13677:     }
13678:     while (%alldns) {
13679: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13680: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13681:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13682:         delete($alldns{$dns});
13683: 	next if ($response->is_error());
13684:         if ($url eq '/adm/dns/loncapaCRL') {
13685:             return &$func($response);
13686:         } else {
13687: 	    my @content = split("\n",$response->content);
13688: 	    unless ($nocache) {
13689: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13690: 	    }
13691: 	    &$func(\@content,$hashref);
13692:             return;
13693:         }
13694:     }
13695:     my $which = (split('/',$url,4))[3];
13696:     if ($which eq 'loncapaCRL') {
13697:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13698:         if (-e $diskfile) {
13699:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13700:         } else {
13701:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13702:         }
13703:     } else {
13704:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13705:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13706:             my @content = <$config>;
13707:             close($config);
13708:             &$func(\@content,$hashref);
13709:         }
13710:     }
13711:     return;
13712: }
13713: 
13714: # ------------------------------------------------------Get DNS checksums file
13715: sub parse_dns_checksums_tab {
13716:     my ($lines,$hashref) = @_;
13717:     my $lonhost = $perlvar{'lonHostID'};
13718:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13719:     my $loncaparev = &get_server_loncaparev($machine_dom);
13720:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13721:     my $webconfdir = '/etc/httpd/conf';
13722:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13723:         $webconfdir = '/etc/apache2';
13724:     } elsif ($distro =~ /^sles(\d+)$/) {
13725:         if ($1 >= 10) {
13726:             $webconfdir = '/etc/apache2';
13727:         }
13728:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13729:         if ($1 >= 10.0) {
13730:             $webconfdir = '/etc/apache2';
13731:         }
13732:     }
13733:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13734:     my (%chksum,%revnum);
13735:     if (ref($lines) eq 'ARRAY') {
13736:         chomp(@{$lines});
13737:         my $version = shift(@{$lines});
13738:         if ($version eq $release) {  
13739:             foreach my $line (@{$lines}) {
13740:                 my ($file,$version,$shasum) = split(/,/,$line);
13741:                 if ($file =~ m{^/etc/httpd/conf}) {
13742:                     if ($webconfdir eq '/etc/apache2') {
13743:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13744:                     }
13745:                 }
13746:                 $chksum{$file} = $shasum;
13747:                 $revnum{$file} = $version;
13748:             }
13749:             if (ref($hashref) eq 'HASH') {
13750:                 %{$hashref} = (
13751:                                 sums     => \%chksum,
13752:                                 versions => \%revnum,
13753:                               );
13754:             }
13755:         }
13756:     }
13757:     return;
13758: }
13759: 
13760: sub fetch_dns_checksums {
13761:     my %checksums;
13762:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13763:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13764:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13765:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13766:              \%checksums);
13767:     return \%checksums;
13768: }
13769: 
13770: sub fetch_crl_pemfile {
13771:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
13772: }
13773: 
13774: sub save_crl_pem {
13775:     my ($response) = @_;
13776:     my ($msg,$hadchanges);
13777:     if (ref($response)) {
13778:         my $now = time;
13779:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
13780:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
13781:         if (open(my $fh,'>',"$tmpcrl")) {
13782:             print $fh $response->content;
13783:             close($fh);
13784:             if (-e $lonca) {
13785:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
13786:                     my $check = <PIPE>;
13787:                     close(PIPE);
13788:                     chomp($check);
13789:                     if ($check eq 'verify OK') {
13790:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13791:                         my $backup;
13792:                         if (-e $dest) {
13793:                             if (&File::Copy::move($dest,"$dest.bak")) {
13794:                                 $backup = 'ok';
13795:                             }
13796:                         }
13797:                         if (&File::Copy::move($tmpcrl,$dest)) {
13798:                             $msg = 'ok';
13799:                             if ($backup) {
13800:                                 my (%oldnums,%newnums);
13801:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
13802:                                     while (<PIPE>) {
13803:                                         $oldnums{(split(/:/))[1]} = 1;
13804:                                     }
13805:                                     close(PIPE);
13806:                                 }
13807:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
13808:                                     while(<PIPE>) {
13809:                                         $newnums{(split(/:/))[1]} = 1;
13810:                                     }
13811:                                     close(PIPE);
13812:                                 }
13813:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
13814:                                     unless (exists($oldnums{$key})) {
13815:                                         $hadchanges = 1;
13816:                                         last;
13817:                                     }
13818:                                 }
13819:                                 unless ($hadchanges) {
13820:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
13821:                                         unless (exists($newnums{$key})) {
13822:                                             $hadchanges = 1;
13823:                                             last;
13824:                                         }
13825:                                     }
13826:                                 }
13827:                             }
13828:                         }
13829:                     } else {
13830:                         unlink($tmpcrl);
13831:                     }
13832:                 } else {
13833:                     unlink($tmpcrl);
13834:                 }
13835:             } else {
13836:                 unlink($tmpcrl);
13837:             }
13838:         }
13839:     }
13840:     return ($msg,$hadchanges);
13841: }
13842: 
13843: # ------------------------------------------------------------ Read domain file
13844: {
13845:     my $loaded;
13846:     my %domain;
13847: 
13848:     sub parse_domain_tab {
13849: 	my ($lines) = @_;
13850: 	foreach my $line (@$lines) {
13851: 	    next if ($line =~ /^(\#|\s*$ )/x);
13852: 
13853: 	    chomp($line);
13854: 	    my ($name,@elements) = split(/:/,$line,9);
13855: 	    my %this_domain;
13856: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13857: 			       'lang_def', 'city', 'longi', 'lati',
13858: 			       'primary') {
13859: 		$this_domain{$field} = shift(@elements);
13860: 	    }
13861: 	    $domain{$name} = \%this_domain;
13862: 	}
13863:     }
13864: 
13865:     sub reset_domain_info {
13866: 	undef($loaded);
13867: 	undef(%domain);
13868:     }
13869: 
13870:     sub load_domain_tab {
13871: 	my ($ignore_cache,$nocache) = @_;
13872: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13873: 	my $fh;
13874: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13875: 	    my @lines = <$fh>;
13876: 	    &parse_domain_tab(\@lines);
13877: 	}
13878: 	close($fh);
13879: 	$loaded = 1;
13880:     }
13881: 
13882:     sub domain {
13883: 	&load_domain_tab() if (!$loaded);
13884: 
13885: 	my ($name,$what) = @_;
13886: 	return if ( !exists($domain{$name}) );
13887: 
13888: 	if (!$what) {
13889: 	    return $domain{$name}{'description'};
13890: 	}
13891: 	return $domain{$name}{$what};
13892:     }
13893: 
13894:     sub domain_info {
13895:         &load_domain_tab() if (!$loaded);
13896:         return %domain;
13897:     }
13898: 
13899: }
13900: 
13901: 
13902: # ------------------------------------------------------------- Read hosts file
13903: {
13904:     my %hostname;
13905:     my %hostdom;
13906:     my %libserv;
13907:     my $loaded;
13908:     my %name_to_host;
13909:     my %internetdom;
13910:     my %LC_dns_serv;
13911: 
13912:     sub parse_hosts_tab {
13913: 	my ($file) = @_;
13914: 	foreach my $configline (@$file) {
13915: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13916:             chomp($configline);
13917: 	    if ($configline =~ /^\^/) {
13918:                 if ($configline =~ /^\^([\w.\-]+)/) {
13919:                     $LC_dns_serv{$1} = 1;
13920:                 }
13921:                 next;
13922:             }
13923: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13924: 	    $name=~s/\s//g;
13925: 	    if ($id && $domain && $role && $name) {
13926:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13927:                     my $curr = $hostname{$id};
13928:                     my $skip;
13929:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13930:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13931:                             $skip = 1;
13932:                         } else {
13933:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13934:                         }
13935:                     }
13936:                     unless ($skip) {
13937:                         push(@{$name_to_host{$name}},$id);
13938:                     }
13939:                 } else {
13940:                     push(@{$name_to_host{$name}},$id);
13941:                 }
13942: 		$hostname{$id}=$name;
13943: 		$hostdom{$id}=$domain;
13944: 		if ($role eq 'library') { $libserv{$id}=$name; }
13945:                 if (defined($protocol)) {
13946:                     if ($protocol eq 'https') {
13947:                         $protocol{$id} = $protocol;
13948:                     } else {
13949:                         $protocol{$id} = 'http'; 
13950:                     }
13951:                 } else {
13952:                     $protocol{$id} = 'http';
13953:                 }
13954:                 if (defined($intdom)) {
13955:                     $internetdom{$id} = $intdom;
13956:                 }
13957: 	    }
13958: 	}
13959:     }
13960:     
13961:     sub reset_hosts_info {
13962: 	&purge_remembered();
13963: 	&reset_domain_info();
13964: 	&reset_hosts_ip_info();
13965:         undef(%internetdom);
13966: 	undef(%name_to_host);
13967: 	undef(%hostname);
13968: 	undef(%hostdom);
13969: 	undef(%libserv);
13970: 	undef($loaded);
13971:     }
13972: 
13973:     sub load_hosts_tab {
13974: 	my ($ignore_cache,$nocache) = @_;
13975: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13976: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13977: 	my @config = <$config>;
13978: 	&parse_hosts_tab(\@config);
13979: 	close($config);
13980: 	$loaded=1;
13981:     }
13982: 
13983:     sub hostname {
13984: 	&load_hosts_tab() if (!$loaded);
13985: 
13986: 	my ($lonid) = @_;
13987: 	return $hostname{$lonid};
13988:     }
13989: 
13990:     sub all_hostnames {
13991: 	&load_hosts_tab() if (!$loaded);
13992: 
13993: 	return %hostname;
13994:     }
13995: 
13996:     sub all_names {
13997:         my ($ignore_cache,$nocache) = @_;
13998: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13999: 
14000: 	return %name_to_host;
14001:     }
14002: 
14003:     sub all_host_domain {
14004:         &load_hosts_tab() if (!$loaded);
14005:         return %hostdom;
14006:     }
14007: 
14008:     sub all_host_intdom {
14009:         &load_hosts_tab() if (!$loaded);
14010:         return %internetdom;
14011:     }
14012: 
14013:     sub is_library {
14014: 	&load_hosts_tab() if (!$loaded);
14015: 
14016: 	return exists($libserv{$_[0]});
14017:     }
14018: 
14019:     sub all_library {
14020: 	&load_hosts_tab() if (!$loaded);
14021: 
14022: 	return %libserv;
14023:     }
14024: 
14025:     sub unique_library {
14026: 	#2x reverse removes all hostnames that appear more than once
14027:         my %unique = reverse &all_library();
14028:         return reverse %unique;
14029:     }
14030: 
14031:     sub get_servers {
14032: 	&load_hosts_tab() if (!$loaded);
14033: 
14034: 	my ($domain,$type) = @_;
14035: 	my %possible_hosts = ($type eq 'library') ? %libserv
14036: 	                                          : %hostname;
14037: 	my %result;
14038: 	if (ref($domain) eq 'ARRAY') {
14039: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14040: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14041: 		    $result{$host} = $hostname;
14042: 		}
14043: 	    }
14044: 	} else {
14045: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14046: 		if ($hostdom{$host} eq $domain) {
14047: 		    $result{$host} = $hostname;
14048: 		}
14049: 	    }
14050: 	}
14051: 	return %result;
14052:     }
14053: 
14054:     sub get_unique_servers {
14055:         my %unique = reverse &get_servers(@_);
14056: 	return reverse %unique;
14057:     }
14058: 
14059:     sub host_domain {
14060: 	&load_hosts_tab() if (!$loaded);
14061: 
14062: 	my ($lonid) = @_;
14063: 	return $hostdom{$lonid};
14064:     }
14065: 
14066:     sub all_domains {
14067: 	&load_hosts_tab() if (!$loaded);
14068: 
14069: 	my %seen;
14070: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14071: 	return @uniq;
14072:     }
14073: 
14074:     sub internet_dom {
14075:         &load_hosts_tab() if (!$loaded);
14076: 
14077:         my ($lonid) = @_;
14078:         return $internetdom{$lonid};
14079:     }
14080: 
14081:     sub is_LC_dns {
14082:         &load_hosts_tab() if (!$loaded);
14083: 
14084:         my ($hostname) = @_;
14085:         return exists($LC_dns_serv{$hostname});
14086:     }
14087: 
14088: }
14089: 
14090: { 
14091:     my %iphost;
14092:     my %name_to_ip;
14093:     my %lonid_to_ip;
14094: 
14095:     sub get_hosts_from_ip {
14096: 	my ($ip) = @_;
14097: 	my %iphosts = &get_iphost();
14098: 	if (ref($iphosts{$ip})) {
14099: 	    return @{$iphosts{$ip}};
14100: 	}
14101: 	return;
14102:     }
14103:     
14104:     sub reset_hosts_ip_info {
14105: 	undef(%iphost);
14106: 	undef(%name_to_ip);
14107: 	undef(%lonid_to_ip);
14108:     }
14109: 
14110:     sub get_host_ip {
14111: 	my ($lonid) = @_;
14112: 	if (exists($lonid_to_ip{$lonid})) {
14113: 	    return $lonid_to_ip{$lonid};
14114: 	}
14115: 	my $name=&hostname($lonid);
14116:    	my $ip = gethostbyname($name);
14117: 	return if (!$ip || length($ip) ne 4);
14118: 	$ip=inet_ntoa($ip);
14119: 	$name_to_ip{$name}   = $ip;
14120: 	$lonid_to_ip{$lonid} = $ip;
14121: 	return $ip;
14122:     }
14123:     
14124:     sub get_iphost {
14125: 	my ($ignore_cache,$nocache) = @_;
14126: 
14127: 	if (!$ignore_cache) {
14128: 	    if (%iphost) {
14129: 		return %iphost;
14130: 	    }
14131: 	    my ($ip_info,$cached)=
14132: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14133: 	    if ($cached) {
14134: 		%iphost      = %{$ip_info->[0]};
14135: 		%name_to_ip  = %{$ip_info->[1]};
14136: 		%lonid_to_ip = %{$ip_info->[2]};
14137: 		return %iphost;
14138: 	    }
14139: 	}
14140: 
14141: 	# get yesterday's info for fallback
14142: 	my %old_name_to_ip;
14143: 	my ($ip_info,$cached)=
14144: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14145: 	if ($cached) {
14146: 	    %old_name_to_ip = %{$ip_info->[1]};
14147: 	}
14148: 
14149: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14150: 	foreach my $name (keys(%name_to_host)) {
14151: 	    my $ip;
14152: 	    if (!exists($name_to_ip{$name})) {
14153: 		$ip = gethostbyname($name);
14154: 		if (!$ip || length($ip) ne 4) {
14155: 		    if (defined($old_name_to_ip{$name})) {
14156: 			$ip = $old_name_to_ip{$name};
14157: 			&logthis("Can't find $name defaulting to old $ip");
14158: 		    } else {
14159: 			&logthis("Name $name no IP found");
14160: 			next;
14161: 		    }
14162: 		} else {
14163: 		    $ip=inet_ntoa($ip);
14164: 		}
14165: 		$name_to_ip{$name} = $ip;
14166: 	    } else {
14167: 		$ip = $name_to_ip{$name};
14168: 	    }
14169: 	    foreach my $id (@{ $name_to_host{$name} }) {
14170: 		$lonid_to_ip{$id} = $ip;
14171: 	    }
14172: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14173: 	}
14174:         unless ($nocache) {
14175: 	    &do_cache_new('iphost','iphost',
14176: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14177: 		          48*60*60);
14178:         }
14179: 
14180: 	return %iphost;
14181:     }
14182: 
14183:     #
14184:     #  Given a DNS returns the loncapa host name for that DNS 
14185:     # 
14186:     sub host_from_dns {
14187:         my ($dns) = @_;
14188:         my @hosts;
14189:         my $ip;
14190: 
14191:         if (exists($name_to_ip{$dns})) {
14192:             $ip = $name_to_ip{$dns};
14193:         }
14194:         if (!$ip) {
14195:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14196:             if (length($ip) == 4) { 
14197: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14198:             }
14199:         }
14200:         if ($ip) {
14201: 	    @hosts = get_hosts_from_ip($ip);
14202: 	    return $hosts[0];
14203:         }
14204:         return undef;
14205:     }
14206: 
14207:     sub get_internet_names {
14208:         my ($lonid) = @_;
14209:         return if ($lonid eq '');
14210:         my ($idnref,$cached)=
14211:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14212:         if ($cached) {
14213:             return $idnref;
14214:         }
14215:         my $ip = &get_host_ip($lonid);
14216:         my @hosts = &get_hosts_from_ip($ip);
14217:         my %iphost = &get_iphost();
14218:         my (@idns,%seen);
14219:         foreach my $id (@hosts) {
14220:             my $dom = &host_domain($id);
14221:             my $prim_id = &domain($dom,'primary');
14222:             my $prim_ip = &get_host_ip($prim_id);
14223:             next if ($seen{$prim_ip});
14224:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14225:                 foreach my $id (@{$iphost{$prim_ip}}) {
14226:                     my $intdom = &internet_dom($id);
14227:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14228:                         push(@idns,$intdom);
14229:                     }
14230:                 }
14231:             }
14232:             $seen{$prim_ip} = 1;
14233:         }
14234:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14235:     }
14236: 
14237: }
14238: 
14239: sub all_loncaparevs {
14240:     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);
14241: }
14242: 
14243: # ---------------------------------------------------------- Read loncaparev table
14244: {
14245:     sub load_loncaparevs { 
14246:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14247:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14248:                 while (my $configline=<$config>) {
14249:                     chomp($configline);
14250:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14251:                     $loncaparevs{$hostid}=$loncaparev;
14252:                 }
14253:                 close($config);
14254:             }
14255:         }
14256:     }
14257: }
14258: 
14259: # ---------------------------------------------------------- Read serverhostID table
14260: {
14261:     sub load_serverhomeIDs {
14262:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14263:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14264:                 while (my $configline=<$config>) {
14265:                     chomp($configline);
14266:                     my ($name,$id)=split(/:/,$configline);
14267:                     $serverhomeIDs{$name}=$id;
14268:                 }
14269:                 close($config);
14270:             }
14271:         }
14272:     }
14273: }
14274: 
14275: 
14276: BEGIN {
14277: 
14278: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14279:     unless ($readit) {
14280: {
14281:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14282:     %perlvar = (%perlvar,%{$configvars});
14283: }
14284: 
14285: 
14286: # ------------------------------------------------------ Read spare server file
14287: {
14288:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14289: 
14290:     while (my $configline=<$config>) {
14291:        chomp($configline);
14292:        if ($configline) {
14293: 	   my ($host,$type) = split(':',$configline,2);
14294: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14295: 	   push(@{ $spareid{$type} }, $host);
14296:        }
14297:     }
14298:     close($config);
14299: }
14300: # ------------------------------------------------------------ Read permissions
14301: {
14302:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14303: 
14304:     while (my $configline=<$config>) {
14305: 	chomp($configline);
14306: 	if ($configline) {
14307: 	    my ($role,$perm)=split(/ /,$configline);
14308: 	    if ($perm ne '') { $pr{$role}=$perm; }
14309: 	}
14310:     }
14311:     close($config);
14312: }
14313: 
14314: # -------------------------------------------- Read plain texts for permissions
14315: {
14316:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14317: 
14318:     while (my $configline=<$config>) {
14319: 	chomp($configline);
14320: 	if ($configline) {
14321: 	    my ($short,@plain)=split(/:/,$configline);
14322:             %{$prp{$short}} = ();
14323: 	    if (@plain > 0) {
14324:                 $prp{$short}{'std'} = $plain[0];
14325:                 for (my $i=1; $i<@plain; $i++) {
14326:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14327:                 }
14328:             }
14329: 	}
14330:     }
14331:     close($config);
14332: }
14333: 
14334: # ---------------------------------------------------------- Read package table
14335: {
14336:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14337: 
14338:     while (my $configline=<$config>) {
14339: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14340: 	chomp($configline);
14341: 	my ($short,$plain)=split(/:/,$configline);
14342: 	my ($pack,$name)=split(/\&/,$short);
14343: 	if ($plain ne '') {
14344: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14345: 	    $packagetab{$short}=$plain; 
14346: 	}
14347:     }
14348:     close($config);
14349: }
14350: 
14351: # ---------------------------------------------------------- Read loncaparev table
14352: 
14353: &load_loncaparevs();
14354: 
14355: # ---------------------------------------------------------- Read serverhostID table
14356: 
14357: &load_serverhomeIDs();
14358: 
14359: # ---------------------------------------------------------- Read releaseslist XML
14360: {
14361:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14362:     if (-e $file) {
14363:         my $parser = HTML::LCParser->new($file);
14364:         while (my $token = $parser->get_token()) {
14365:             if ($token->[0] eq 'S') {
14366:                 my $item = $token->[1];
14367:                 my $name = $token->[2]{'name'};
14368:                 my $value = $token->[2]{'value'};
14369:                 my $valuematch = $token->[2]{'valuematch'};
14370:                 my $namematch = $token->[2]{'namematch'};
14371:                 if ($item eq 'parameter') {
14372:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14373:                         my $release = $parser->get_text();
14374:                         $release =~ s/(^\s*|\s*$ )//gx;
14375:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14376:                     }
14377:                 } elsif ($item ne '' && $name ne '') {
14378:                     my $release = $parser->get_text();
14379:                     $release =~ s/(^\s*|\s*$ )//gx;
14380:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14381:                 }
14382:             }
14383:         }
14384:     }
14385: }
14386: 
14387: # ---------------------------------------------------------- Read managers table
14388: {
14389:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14390:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14391:             while (my $configline=<$config>) {
14392:                 chomp($configline);
14393:                 next if ($configline =~ /^\#/);
14394:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14395:                     $managerstab{$configline} = 1;
14396:                 }
14397:             }
14398:             close($config);
14399:         }
14400:     }
14401: }
14402: 
14403: # ------------- set up temporary directory
14404: {
14405:     $tmpdir = LONCAPA::tempdir();
14406: 
14407: }
14408: 
14409: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14410: 				'compress_threshold'=> 20_000,
14411:  			        });
14412: 
14413: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14414: $dumpcount=0;
14415: $locknum=0;
14416: 
14417: &logtouch();
14418: &logthis('<font color="yellow">INFO: Read configuration</font>');
14419: $readit=1;
14420:     {
14421: 	use integer;
14422: 	my $test=(2**32)+1;
14423: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14424: 	&logthis(" Detected 64bit platform ($_64bit)");
14425:     }
14426: }
14427: }
14428: 
14429: 1;
14430: __END__
14431: 
14432: =pod
14433: 
14434: =head1 NAME
14435: 
14436: Apache::lonnet - Subroutines to ask questions about things in the network.
14437: 
14438: =head1 SYNOPSIS
14439: 
14440: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14441: 
14442:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14443: 
14444: Common parameters:
14445: 
14446: =over 4
14447: 
14448: =item *
14449: 
14450: $uname : an internal username (if $cname expecting a course Id specifically)
14451: 
14452: =item *
14453: 
14454: $udom : a domain (if $cdom expecting a course's domain specifically)
14455: 
14456: =item *
14457: 
14458: $symb : a resource instance identifier
14459: 
14460: =item *
14461: 
14462: $namespace : the name of a .db file that contains the data needed or
14463: being set.
14464: 
14465: =back
14466: 
14467: =head1 OVERVIEW
14468: 
14469: lonnet provides subroutines which interact with the
14470: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14471: about classes, users, and resources.
14472: 
14473: For many of these objects you can also use this to store data about
14474: them or modify them in various ways.
14475: 
14476: =head2 Symbs
14477: 
14478: To identify a specific instance of a resource, LON-CAPA uses symbols
14479: or "symbs"X<symb>. These identifiers are built from the URL of the
14480: map, the resource number of the resource in the map, and the URL of
14481: the resource itself. The latter is somewhat redundant, but might help
14482: if maps change.
14483: 
14484: An example is
14485: 
14486:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14487: 
14488: The respective map entry is
14489: 
14490:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14491:   title="Problem 2">
14492:  </resource>
14493: 
14494: Symbs are used by the random number generator, as well as to store and
14495: restore data specific to a certain instance of for example a problem.
14496: 
14497: =head2 Storing And Retrieving Data
14498: 
14499: X<store()>X<cstore()>X<restore()>Three of the most important functions
14500: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14501: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14502: is is the non-critical message twin of cstore. These functions are for
14503: handlers to store a perl hash to a user's permanent data space in an
14504: easy manner, and to retrieve it again on another call. It is expected
14505: that a handler would use this once at the beginning to retrieve data,
14506: and then again once at the end to send only the new data back.
14507: 
14508: The data is stored in the user's data directory on the user's
14509: homeserver under the ID of the course.
14510: 
14511: The hash that is returned by restore will have all of the previous
14512: value for all of the elements of the hash.
14513: 
14514: Example:
14515: 
14516:  #creating a hash
14517:  my %hash;
14518:  $hash{'foo'}='bar';
14519: 
14520:  #storing it
14521:  &Apache::lonnet::cstore(\%hash);
14522: 
14523:  #changing a value
14524:  $hash{'foo'}='notbar';
14525: 
14526:  #adding a new value
14527:  $hash{'bar'}='foo';
14528:  &Apache::lonnet::cstore(\%hash);
14529: 
14530:  #retrieving the hash
14531:  my %history=&Apache::lonnet::restore();
14532: 
14533:  #print the hash
14534:  foreach my $key (sort(keys(%history))) {
14535:    print("\%history{$key} = $history{$key}");
14536:  }
14537: 
14538: Will print out:
14539: 
14540:  %history{1:foo} = bar
14541:  %history{1:keys} = foo:timestamp
14542:  %history{1:timestamp} = 990455579
14543:  %history{2:bar} = foo
14544:  %history{2:foo} = notbar
14545:  %history{2:keys} = foo:bar:timestamp
14546:  %history{2:timestamp} = 990455580
14547:  %history{bar} = foo
14548:  %history{foo} = notbar
14549:  %history{timestamp} = 990455580
14550:  %history{version} = 2
14551: 
14552: Note that the special hash entries C<keys>, C<version> and
14553: C<timestamp> were added to the hash. C<version> will be equal to the
14554: total number of versions of the data that have been stored. The
14555: C<timestamp> attribute will be the UNIX time the hash was
14556: stored. C<keys> is available in every historical section to list which
14557: keys were added or changed at a specific historical revision of a
14558: hash.
14559: 
14560: B<Warning>: do not store the hash that restore returns directly. This
14561: will cause a mess since it will restore the historical keys as if the
14562: were new keys. I.E. 1:foo will become 1:1:foo etc.
14563: 
14564: Calling convention:
14565: 
14566:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14567:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14568: 
14569: For more detailed information, see lonnet specific documentation.
14570: 
14571: =head1 RETURN MESSAGES
14572: 
14573: =over 4
14574: 
14575: =item * B<con_lost>: unable to contact remote host
14576: 
14577: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14578: when the connection is brought back up
14579: 
14580: =item * B<con_failed>: unable to contact remote host and unable to save message
14581: for later delivery
14582: 
14583: =item * B<error:>: an error a occurred, a description of the error follows the :
14584: 
14585: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14586: that was requested
14587: 
14588: =back
14589: 
14590: =head1 PUBLIC SUBROUTINES
14591: 
14592: =head2 Session Environment Functions
14593: 
14594: =over 4
14595: 
14596: =item * 
14597: X<appenv()>
14598: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14599: the user envirnoment file, and will be restored for each access this
14600: user makes during this session, also modifies the %env for the current
14601: process. Optional rolesarrayref - if defined contains a reference to an array
14602: of roles which are exempt from the restriction on modifying user.role entries 
14603: in the user's environment.db and in %env.    
14604: 
14605: =item *
14606: X<delenv()>
14607: B<delenv($delthis,$regexp)>: removes all items from the session
14608: environment file that begin with $delthis. If the 
14609: optional second arg - $regexp - is true, $delthis is treated as a 
14610: regular expression, otherwise \Q$delthis\E is used. 
14611: The values are also deleted from the current processes %env.
14612: 
14613: =item * get_env_multiple($name) 
14614: 
14615: gets $name from the %env hash, it seemlessly handles the cases where multiple
14616: values may be defined and end up as an array ref.
14617: 
14618: returns an array of values
14619: 
14620: =back
14621: 
14622: =head2 User Information
14623: 
14624: =over 4
14625: 
14626: =item *
14627: X<queryauthenticate()>
14628: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14629: authentication scheme
14630: 
14631: =item *
14632: X<authenticate()>
14633: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14634: authenticate user from domain's lib servers (first use the current
14635: one). C<$upass> should be the users password.
14636: $checkdefauth is optional (value is 1 if a check should be made to
14637:    authenticate user using default authentication method, and allow
14638:    account creation if username does not have account in the domain).
14639: $clientcancheckhost is optional (value is 1 if checking whether the
14640:    server can host will occur on the client side in lonauth.pm).   
14641: 
14642: =item *
14643: X<homeserver()>
14644: B<homeserver($uname,$udom)>: find the server which has
14645: the user's directory and files (there must be only one), this caches
14646: the answer, and also caches if there is a borken connection.
14647: 
14648: =item *
14649: X<idget()>
14650: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14651: a list of student/employee IDs or clicker IDs
14652: (student/employee IDs are a unique resource in a domain, there must be 
14653: only 1 ID per username, and only 1 username per ID in a specific domain).
14654: clickerIDs are not necessarily unique, as students might share clickers.
14655: (returns hash: id=>name,id=>name)
14656: 
14657: =item *
14658: X<idrget()>
14659: B<idrget($udom,@unames)>: find the IDs behind a list of
14660: usernames (returns hash: name=>id,name=>id)
14661: 
14662: =item *
14663: X<idput()>
14664: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14665: names and associated student/employee IDs or clicker IDs.
14666: 
14667: =item *
14668: X<iddel()>
14669: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14670: student/employee ID or clicker ID username look-ups from domain.
14671: The homeserver ($uhome) and namespace ($namespace) are optional.
14672: If no $uhome is provided, it will be determined usig &homeserver()
14673: for each user.  If no $namespace is provided, the default is ids.
14674: 
14675: =item *
14676: X<updateclickers()>
14677: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14678: clicker ID-to-username look-ups in clickers.db on library server.
14679: Permitted actions are add or del (i.e., add or delete). The 
14680: clickers.db contains clickerID as keys (escaped), and each corresponding
14681: value is an escaped comma-separated list of usernames (for whom the
14682: library server is the homeserver), who registered that particular ID.
14683: If $critical is true, the update will be sent via &critical, otherwise
14684: &reply() will be used.
14685: 
14686: =item *
14687: X<rolesinit()>
14688: B<rolesinit($udom,$username)>: get user privileges.
14689: returns user role, first access and timer interval hashes
14690: 
14691: =item *
14692: X<privileged()>
14693: B<privileged($username,$domain)>: returns a true if user has a
14694: privileged and active role (i.e. su or dc), false otherwise.
14695: 
14696: =item *
14697: X<getsection()>
14698: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14699: course $cname, return section name/number or '' for "not in course"
14700: and '-1' for "no section"
14701: 
14702: =item *
14703: X<userenvironment()>
14704: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14705: passed in @what from the requested user's environment, returns a hash
14706: 
14707: =item * 
14708: X<userlog_query()>
14709: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14710: activity.log file. %filters defines filters applied when parsing the
14711: log file. These can be start or end timestamps, or the type of action
14712: - log to look for Login or Logout events, check for Checkin or
14713: Checkout, role for role selection. The response is in the form
14714: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14715: escaped strings of the action recorded in the activity.log file.
14716: 
14717: =back
14718: 
14719: =head2 User Roles
14720: 
14721: =over 4
14722: 
14723: =item *
14724: 
14725: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14726: returns codes for allowed actions.
14727: 
14728: The first argument is required, all others are optional.
14729: 
14730: $priv is the privilege being checked.
14731: $uri contains additional information about what is being checked for access (e.g.,
14732: URL, course ID etc.). 
14733: $symb is the unique resource instance identifier in a course; if needed,
14734: but not provided, it will be retrieved via a call to &symbread(). 
14735: $role is the role for which a priv is being checked (only used if priv is evb). 
14736: $clientip is the user's IP address (only used when checking for access to portfolio 
14737: files).
14738: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14739: prevents recursive calls to &allowed.
14740: 
14741:  F: full access
14742:  U,I,K: authentication modes (cxx only)
14743:  '': forbidden
14744:  1: user needs to choose course
14745:  2: browse allowed
14746:  A: passphrase authentication needed
14747:  B: access temporarily blocked because of a blocking event in a course.
14748: 
14749: =item *
14750: 
14751: constructaccess($url,$setpriv) : check for access to construction space URL
14752: 
14753: See if the owner domain and name in the URL match those in the
14754: expected environment.  If so, return three element list
14755: ($ownername,$ownerdomain,$ownerhome).
14756: 
14757: Otherwise return the null string.
14758: 
14759: If second argument 'setpriv' is true, it assigns the privileges,
14760: and returns the same three element list, unless the owner has
14761: blocked "ad hoc" Domain Coordinator access to the Author Space,
14762: in which case the null string is returned.
14763: 
14764: =item *
14765: 
14766: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14767: define a custom role rolename set privileges in format of lonTabs/roles.tab
14768: for system, domain, and course level. $uname and $udom are optional (current
14769: user's username and domain will be used when either of $uname or $udom are absent.
14770: 
14771: =item *
14772: 
14773: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14774: (rolesplain.tab); plain text explanation of a user role term.
14775: $type is Course (default) or Community.
14776: If $forcedefault evaluates to true, text returned will be default 
14777: text for $type. Otherwise, if this is a course, the text returned 
14778: will be a custom name for the role (if defined in the course's 
14779: environment).  If no custom name is defined the default is returned.
14780:    
14781: =item *
14782: 
14783: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14784: All arguments are optional. Returns a hash of a roles, either for
14785: co-author/assistant author roles for a user's Construction Space
14786: (default), or if $context is 'userroles', roles for the user himself,
14787: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14788: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14789: For each key, value is set to colon-separated start and end times for
14790: the role.  If no username and domain are specified, will default to
14791: current user/domain. Types, roles, and roledoms are references to arrays
14792: of role statuses (active, future or previous), roles 
14793: (e.g., cc,in, st etc.) and domains of the roles which can be used
14794: to restrict the list of roles reported. If no array ref is 
14795: provided for types, will default to return only active roles.
14796: 
14797: =item *
14798: 
14799: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14800: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14801: 
14802: Additional optional arguments are: $type (if role checking is to be restricted 
14803: to certain user status types -- previous (expired roles), active (currently
14804: available roles) or future (roles available in the future), and
14805: $hideprivileged -- if true will not report course roles for users who
14806: have active Domain Coordinator role in course's domain or in additional
14807: domains (specified in 'Domains to check for privileged users' in course
14808: environment -- set via:  Course Settings -> Classlists and staff listing).
14809: 
14810: =item *
14811: 
14812: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14813: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14814: $possdomains and $possroles are optional array refs -- to domains to check and
14815: roles to check.  If $possdomains is not specified, a dump will be done of the
14816: users' roles.db to check for a dc or su role in any domain. This can be
14817: time consuming if &privileged is called repeatedly (e.g., when displaying a
14818: classlist), so in such cases, supplying a $possdomains array is preferred, as
14819: this then allows &privileged_by_domain() to be used, which caches the identity
14820: of privileged users, eliminating the need for repeated calls to &dump().
14821: 
14822: =item *
14823: 
14824: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14825: where the outer hash keys are domains specified in the $possdomains array ref,
14826: next inner hash keys are privileged roles specified in the $roles array ref,
14827: and the innermost hash contains key = value pairs for username:domain = end:start
14828: for active or future "privileged" users with that role in that domain. To avoid
14829: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14830: innerhash are cached using priv_$role and $dom as the identifiers.
14831: 
14832: =back
14833: 
14834: =head2 User Modification
14835: 
14836: =over 4
14837: 
14838: =item *
14839: 
14840: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14841: user for the level given by URL.  Optional start and end dates (leave empty
14842: string or zero for "no date")
14843: 
14844: =item *
14845: 
14846: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14847: change a users, password, possible return values are: ok,
14848: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14849: refused
14850: 
14851: =item *
14852: 
14853: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14854: 
14855: =item *
14856: 
14857: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14858:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14859: 
14860: will update user information (firstname,middlename,lastname,generation,
14861: permanentemail), and if forceid is true, student/employee ID also.
14862: A user's institutional affiliation(s) can also be updated.
14863: User information fields will not be overwritten with empty entries 
14864: unless the field is included in the $candelete array reference.
14865: This array is included when a single user is modified via "Manage Users",
14866: or when Autoupdate.pl is run by cron in a domain.
14867: 
14868: =item *
14869: 
14870: modifystudent
14871: 
14872: modify a student's enrollment and identification information.
14873: The course id is resolved based on the current user's environment.  
14874: This means the invoking user must be a course coordinator or otherwise
14875: associated with a course.
14876: 
14877: This call is essentially a wrapper for lonnet::modifyuser and
14878: lonnet::modify_student_enrollment
14879: 
14880: Inputs: 
14881: 
14882: =over 4
14883: 
14884: =item B<$udom> Student's loncapa domain
14885: 
14886: =item B<$uname> Student's loncapa login name
14887: 
14888: =item B<$uid> Student/Employee ID
14889: 
14890: =item B<$umode> Student's authentication mode
14891: 
14892: =item B<$upass> Student's password
14893: 
14894: =item B<$first> Student's first name
14895: 
14896: =item B<$middle> Student's middle name
14897: 
14898: =item B<$last> Student's last name
14899: 
14900: =item B<$gene> Student's generation
14901: 
14902: =item B<$usec> Student's section in course
14903: 
14904: =item B<$end> Unix time of the roles expiration
14905: 
14906: =item B<$start> Unix time of the roles start date
14907: 
14908: =item B<$forceid> If defined, allow $uid to be changed
14909: 
14910: =item B<$desiredhome> server to use as home server for student
14911: 
14912: =item B<$email> Student's permanent e-mail address
14913: 
14914: =item B<$type> Type of enrollment (auto or manual)
14915: 
14916: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14917: 
14918: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14919: 
14920: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14921: 
14922: =item B<$context> role change context (shown in User Management Logs display in a course)
14923: 
14924: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14925: 
14926: =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.
14927: 
14928: =back
14929: 
14930: =item *
14931: 
14932: modify_student_enrollment
14933: 
14934: Change a student's enrollment status in a class.  The environment variable
14935: 'role.request.course' must be defined for this function to proceed.
14936: 
14937: Inputs:
14938: 
14939: =over 4
14940: 
14941: =item $udom, student's domain
14942: 
14943: =item $uname, student's name
14944: 
14945: =item $uid, student's user id
14946: 
14947: =item $first, student's first name
14948: 
14949: =item $middle
14950: 
14951: =item $last
14952: 
14953: =item $gene
14954: 
14955: =item $usec
14956: 
14957: =item $end
14958: 
14959: =item $start
14960: 
14961: =item $type
14962: 
14963: =item $locktype
14964: 
14965: =item $cid
14966: 
14967: =item $selfenroll
14968: 
14969: =item $context
14970: 
14971: =item $credits, number of credits student will earn from this class
14972: 
14973: =item $instsec, institutional course section code for student
14974: 
14975: =back
14976: 
14977: 
14978: =item *
14979: 
14980: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14981: custom role; give a custom role to a user for the level given by URL.  Specify
14982: name and domain of role author, and role name
14983: 
14984: =item *
14985: 
14986: revokerole($udom,$uname,$url,$role) : revoke a role for url
14987: 
14988: =item *
14989: 
14990: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14991: 
14992: =back
14993: 
14994: =head2 Course Infomation
14995: 
14996: =over 4
14997: 
14998: =item *
14999: 
15000: coursedescription($courseid,$options) : returns a hash of information about the
15001: specified course id, including all environment settings for the
15002: course, the description of the course will be in the hash under the
15003: key 'description'
15004: 
15005: $options is an optional parameter that if supplied is a hash reference that controls
15006: what how this function works.  It has the following key/values:
15007: 
15008: =over 4
15009: 
15010: =item freshen_cache
15011: 
15012: If defined, and the environment cache for the course is valid, it is 
15013: returned in the returned hash.
15014: 
15015: =item one_time
15016: 
15017: If defined, the last cache time is set to _now_
15018: 
15019: =item user
15020: 
15021: If defined, the supplied username is used instead of the current user.
15022: 
15023: 
15024: =back
15025: 
15026: =item *
15027: 
15028: resdata($name,$domain,$type,@which) : request for current parameter
15029: setting for a specific $type, where $type is either 'course' or 'user',
15030: @what should be a list of parameters to ask about. This routine caches
15031: answers for 10 minutes.
15032: 
15033: =item *
15034: 
15035: get_courseresdata($courseid, $domain) : dump the entire course resource
15036: data base, returning a hash that is keyed by the resource name and has
15037: values that are the resource value.  I believe that the timestamps and
15038: versions are also returned.
15039: 
15040: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15041: supplemental content area. This routine caches the number of files for 
15042: 10 minutes.
15043: 
15044: =back
15045: 
15046: =head2 Course Modification
15047: 
15048: =over 4
15049: 
15050: =item *
15051: 
15052: writecoursepref($courseid,%prefs) : write preferences (environment
15053: database) for a course
15054: 
15055: =item *
15056: 
15057: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15058: 
15059: =item *
15060: 
15061: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15062: 
15063: =item *
15064: 
15065: is_course($courseid), is_course($cdom, $cnum)
15066: 
15067: Accepts either a combined $courseid (in the form of domain_courseid) or the
15068: two component version $cdom, $cnum. It checks if the specified course exists.
15069: 
15070: Returns:
15071:     undef if the course doesn't exist, otherwise
15072:     in scalar context the combined courseid.
15073:     in list context the two components of the course identifier, domain and 
15074:     courseid.    
15075: 
15076: =back
15077: 
15078: =head2 Resource Subroutines
15079: 
15080: =over 4
15081: 
15082: =item *
15083: 
15084: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15085: 
15086: =item *
15087: 
15088: repcopy($filename) : subscribes to the requested file, and attempts to
15089: replicate from the owning library server, Might return
15090: 'unavailable', 'not_found', 'forbidden', 'ok', or
15091: 'bad_request', also attempts to grab the metadata for the
15092: resource. Expects the local filesystem pathname
15093: (/home/httpd/html/res/....)
15094: 
15095: =back
15096: 
15097: =head2 Resource Information
15098: 
15099: =over 4
15100: 
15101: =item *
15102: 
15103: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15104: and returns the value of a variety of different possible values,
15105: $varname should be a request string, and the other parameters can be
15106: used to specify who and what one is asking about. Ordinarily, $cid 
15107: does not need to be specified, as it is retrived from 
15108: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15109: within lonuserstate::loadmap() when initializing a course, before
15110: $env{'request.course.id'} has been set, so it needs to be provided
15111: in that one case.
15112: 
15113: Possible values for $varname are environment.lastname (or other item
15114: from the envirnment hash), user.name (or someother aspect about the
15115: user), resource.0.maxtries (or some other part and parameter of a
15116: resource)
15117: 
15118: =item *
15119: 
15120: directcondval($number) : get current value of a condition; reads from a state
15121: string
15122: 
15123: =item *
15124: 
15125: condval($condidx) : value of condition index based on state
15126: 
15127: =item *
15128: 
15129: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15130: resource's metadata, $what should be either a specific key, or either
15131: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15132: packages that this resource currently uses, the last 3 arguments are 
15133: only used internally for recursive metadata.
15134: 
15135: the toolsymb is only used where the uri is for an external tool (for which
15136: the uri as well as the symb are guaranteed to be unique).
15137: 
15138: this function automatically caches all requests except any made recursively
15139: to retrieve a list of metadata keys for an imported library file ($liburi is 
15140: defined).
15141: 
15142: =item *
15143: 
15144: metadata_query($query,$custom,$customshow) : make a metadata query against the
15145: network of library servers; returns file handle of where SQL and regex results
15146: will be stored for query
15147: 
15148: =item *
15149: 
15150: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15151: return symbolic list entry (all arguments optional). 
15152: 
15153: Args: filename is the filename (including path) for the file for which a symb 
15154: is required; donotrecurse, if true will prevent calls to allowed() being made 
15155: to check access status if more than one resource was found in the bighash 
15156: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15157: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15158: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15159: cause possible symbs to be checked to determine if they are subject to content
15160: blocking, if so they will not be included as possible symbs; possibles is a
15161: ref to a hash, which, as a side effect, will be populated with all possible 
15162: symbs (content blocking not tested).
15163:  
15164: returns the data handle
15165: 
15166: =item *
15167: 
15168: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15169: and is a possible symb for the URL in $thisfn, and if is an encrypted
15170: resource that the user accessed using /enc/ returns a 1 on success, 0
15171: on failure, user must be in a course, as it assumes the existence of
15172: the course initial hash, and uses $env('request.course.id'}.  The third
15173: arg is an optional reference to a scalar.  If this arg is passed in the 
15174: call to symbverify, it will be set to 1 if the symb has been set to be 
15175: encrypted; otherwise it will be null.  
15176: 
15177: =item *
15178: 
15179: symbclean($symb) : removes versions numbers from a symb, returns the
15180: cleaned symb
15181: 
15182: =item *
15183: 
15184: is_on_map($uri) : checks if the $uri is somewhere on the current
15185: course map, user must be in a course for it to work.
15186: 
15187: =item *
15188: 
15189: numval($salt) : return random seed value (addend for rndseed)
15190: 
15191: =item *
15192: 
15193: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15194: a random seed, all arguments are optional, if they aren't sent it uses the
15195: environment to derive them. Note: if symb isn't sent and it can't get one
15196: from &symbread it will use the current time as its return value
15197: 
15198: =item *
15199: 
15200: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15201: unfakeable, receipt
15202: 
15203: =item *
15204: 
15205: receipt() : API to ireceipt working off of env values; given out to users
15206: 
15207: =item *
15208: 
15209: countacc($url) : count the number of accesses to a given URL
15210: 
15211: =item *
15212: 
15213: 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
15214: 
15215: =item *
15216: 
15217: 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)
15218: 
15219: =item *
15220: 
15221: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15222: 
15223: =item *
15224: 
15225: devalidate($symb) : devalidate temporary spreadsheet calculations,
15226: forcing spreadsheet to reevaluate the resource scores next time.
15227: 
15228: =item * 
15229: 
15230: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15231: when viewing in course context.
15232: 
15233:  input: six args -- filename (decluttered), course number, course domain,
15234:                     url, symb (if registered) and group (if this is a 
15235:                     group item -- e.g., bulletin board, group page etc.).
15236: 
15237:  output: array of five scalars --
15238:          $cfile -- url for file editing if editable on current server
15239:          $home -- homeserver of resource (i.e., for author if published,
15240:                                           or course if uploaded.).
15241:          $switchserver --  1 if server switch will be needed.
15242:          $forceedit -- 1 if icon/link should be to go to edit mode 
15243:          $forceview -- 1 if icon/link should be to go to view mode
15244: 
15245: =item *
15246: 
15247: is_course_upload($file,$cnum,$cdom)
15248: 
15249: Used in course context to determine if current file was uploaded to 
15250: the course (i.e., would be found in /userfiles/docs on the course's 
15251: homeserver.
15252: 
15253:   input: 3 args -- filename (decluttered), course number and course domain.
15254:   output: boolean -- 1 if file was uploaded.
15255: 
15256: =back
15257: 
15258: =head2 Storing/Retreiving Data
15259: 
15260: =over 4
15261: 
15262: =item *
15263: 
15264: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15265: permanently for this url; hashref needs to be given and should be a \%hashname;
15266: the remaining args aren't required and if they aren't passed or are '' they will
15267: be derived from the env (with the exception of $laststore, which is an 
15268: optional arg used when a user's submission is stored in grading).
15269: $laststore is $version=$timestamp, where $version is the most recent version
15270: number retrieved for the corresponding $symb in the $namespace db file, and
15271: $timestamp is the timestamp for that transaction (UNIX time).
15272: $laststore is currently only passed when cstore() is called by 
15273: structuretags::finalize_storage().
15274: 
15275: =item *
15276: 
15277: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15278: but uses critical subroutine
15279: 
15280: =item *
15281: 
15282: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15283: all args are optional
15284: 
15285: =item *
15286: 
15287: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15288: dumps the complete (or key matching regexp) namespace into a hash
15289: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15290: normally &store()ed into
15291: 
15292: $range should be either an integer '100' (give me the first 100
15293:                                            matching records)
15294:               or be  two integers sperated by a - with no spaces
15295:                  '30-50' (give me the 30th through the 50th matching
15296:                           records)
15297: 
15298: 
15299: =item *
15300: 
15301: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15302: replaces a &store() version of data with a replacement set of data
15303: for a particular resource in a namespace passed in the $storehash hash 
15304: reference. If $tolog is true, the transaction is logged in the courselog
15305: with an action=PUTSTORE.
15306: 
15307: =item *
15308: 
15309: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15310: works very similar to store/cstore, but all data is stored in a
15311: temporary location and can be reset using tmpreset, $storehash should
15312: be a hash reference, returns nothing on success
15313: 
15314: =item *
15315: 
15316: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15317: similar to restore, but all data is stored in a temporary location and
15318: can be reset using tmpreset. Returns a hash of values on success,
15319: error string otherwise.
15320: 
15321: =item *
15322: 
15323: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15324: deltes all keys for $symb form the temporary storage hash.
15325: 
15326: =item *
15327: 
15328: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15329: reference filled in from namesp ($udom and $uname are optional)
15330: 
15331: =item *
15332: 
15333: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15334: namesp ($udom and $uname are optional)
15335: 
15336: =item *
15337: 
15338: dump($namespace,$udom,$uname,$regexp,$range) : 
15339: dumps the complete (or key matching regexp) namespace into a hash
15340: ($udom, $uname, $regexp, $range are optional)
15341: 
15342: $range should be either an integer '100' (give me the first 100
15343:                                            matching records)
15344:               or be  two integers sperated by a - with no spaces
15345:                  '30-50' (give me the 30th through the 50th matching
15346:                           records)
15347: =item *
15348: 
15349: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15350: $store can be a scalar, an array reference, or if the amount to be 
15351: incremented is > 1, a hash reference.
15352: 
15353: ($udom and $uname are optional)
15354: 
15355: =item *
15356: 
15357: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15358: ($udom and $uname are optional)
15359: 
15360: =item *
15361: 
15362: cput($namespace,$storehash,$udom,$uname) : critical put
15363: ($udom and $uname are optional)
15364: 
15365: =item *
15366: 
15367: newput($namespace,$storehash,$udom,$uname) :
15368: 
15369: Attempts to store the items in the $storehash, but only if they don't
15370: currently exist, if this succeeds you can be certain that you have 
15371: successfully created a new key value pair in the $namespace db.
15372: 
15373: 
15374: Args:
15375:  $namespace: name of database to store values to
15376:  $storehash: hashref to store to the db
15377:  $udom: (optional) domain of user containing the db
15378:  $uname: (optional) name of user caontaining the db
15379: 
15380: Returns:
15381:  'ok' -> succeeded in storing all keys of $storehash
15382:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15383:                         least <key> already existed in the db (other
15384:                         requested keys may also already exist)
15385:  'error: <msg>' -> unable to tie the DB or other error occurred
15386:  'con_lost' -> unable to contact request server
15387:  'refused' -> action was not allowed by remote machine
15388: 
15389: 
15390: =item *
15391: 
15392: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15393: reference filled in from namesp (encrypts the return communication)
15394: ($udom and $uname are optional)
15395: 
15396: =item *
15397: 
15398: log($udom,$name,$home,$message) : write to permanent log for user; use
15399: critical subroutine
15400: 
15401: =item *
15402: 
15403: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15404: array reference filled in from namespace found in domain level on either
15405: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15406: 
15407: =item *
15408: 
15409: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15410: domain level either on specified domain server ($uhome) or primary domain 
15411: server ($udom and $uhome are optional)
15412: 
15413: =item * 
15414: 
15415: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15416: for: authentication, language, quotas, timezone, date locale, and portal URL in
15417: the target domain.
15418: 
15419: May also include additional key => value pairs for the following groups:
15420: 
15421: =over
15422: 
15423: =item
15424: disk quotas (MB allocated by default to portfolios and authoring spaces).
15425: 
15426: =over
15427: 
15428: =item defaultquota, authorquota
15429: 
15430: =back
15431: 
15432: =item
15433: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15434: portfolio for users).
15435: 
15436: =over
15437: 
15438: =item
15439: aboutme, blog, webdav, portfolio
15440: 
15441: =back
15442: 
15443: =item
15444: requestcourses: ability to request courses, and how requests are processed.
15445: 
15446: =over
15447: 
15448: =item
15449: official, unofficial, community, textbook, placement
15450: 
15451: =back
15452: 
15453: =item
15454: inststatus: types of institutional affiliation, and order in which they are displayed.
15455: 
15456: =over
15457: 
15458: =item
15459: inststatustypes, inststatusorder, inststatusguest
15460: 
15461: =back
15462: 
15463: =item
15464: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15465: for course's uploaded content.
15466: 
15467: =over
15468: 
15469: =item
15470: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15471: communityquota, textbookquota, placementquota
15472: 
15473: =back
15474: 
15475: =item
15476: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15477: on your servers.
15478: 
15479: =over
15480: 
15481: =item 
15482: remotesessions, hostedsessions
15483: 
15484: =back
15485: 
15486: =back
15487: 
15488: In cases where a domain coordinator has never used the "Set Domain Configuration"
15489: utility to create a configuration.db file on a domain's primary library server 
15490: only the following domain defaults: auth_def, auth_arg_def, lang_def
15491: -- corresponding values are authentication type (internal, krb4, krb5,
15492: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15493: will be available. Values are retrieved from cache (if current), unless the
15494: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15495: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15496: 
15497: Typical usage:
15498: 
15499: %domdefaults = &get_domain_defaults($target_domain);
15500: 
15501: =back
15502: 
15503: =head2 Network Status Functions
15504: 
15505: =over 4
15506: 
15507: =item *
15508: 
15509: dirlist() : return directory list based on URI (first arg).
15510: 
15511: Inputs: 1 required, 5 optional.
15512: 
15513: =over
15514: 
15515: =item 
15516: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15517: 
15518: =item
15519: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15520: 
15521: =item
15522: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15523: 
15524: =item
15525: $getpropath - boolean: 1 if prepend path using &propath(). 
15526: 
15527: =item
15528: $getuserdir - boolean: 1 if prepend path for "userfiles".
15529: 
15530: =item 
15531: $alternateRoot - path to prepend in place of path from $uri.
15532: 
15533: =back
15534: 
15535: Returns: Array of up to two items.
15536: 
15537: =over
15538: 
15539: a reference to an array of files/subdirectories
15540: 
15541: =over
15542: 
15543: Each element in the array of files/subdirectories is a & separated list of
15544: item name and the result of running stat on the item.  If dirlist was requested
15545: for a file instead of a directory, the item name will be ''. For a directory 
15546: listing, if the item is a metadata file, the element will end &N&M 
15547: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15548: default copyright set (1).  
15549: 
15550: =back
15551: 
15552: a scalar containing error condition (if encountered).
15553: 
15554: =over
15555: 
15556: =item 
15557: no_host (no homeserver identified for $username:$domain).
15558: 
15559: =item 
15560: no_such_host (server contacted for listing not identified as valid host).
15561: 
15562: =item 
15563: con_lost (connection to remote server failed).
15564: 
15565: =item 
15566: refused (invalid $username:$domain received on lond side).
15567: 
15568: =item 
15569: no_such_dir (directory at specified path on lond side does not exist). 
15570: 
15571: =item 
15572: empty (directory at specified path on lond side is empty).
15573: 
15574: =over
15575: 
15576: This is currently not encountered because the &ls3, &ls2, 
15577: &ls (_handler) routines on the lond side do not filter out
15578: . and .. from a directory listing. 
15579: 
15580: =back
15581: 
15582: =back
15583: 
15584: =back
15585: 
15586: =item *
15587: 
15588: spareserver() : find server with least workload from spare.tab
15589: 
15590: 
15591: =item *
15592: 
15593: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15594: if there is no corresponding loncapa host.
15595: 
15596: =back
15597: 
15598: 
15599: =head2 Apache Request
15600: 
15601: =over 4
15602: 
15603: =item *
15604: 
15605: ssi($url,%hash) : server side include, does a complete request cycle on url to
15606: localhost, posts hash
15607: 
15608: =back
15609: 
15610: =head2 Data to String to Data
15611: 
15612: =over 4
15613: 
15614: =item *
15615: 
15616: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15617: and '&' separators, supports elements that are arrayrefs and hashrefs
15618: 
15619: =item *
15620: 
15621: hashref2str($hashref) : convert a hashref into a string complete with
15622: escaping and '=' and '&' separators, supports elements that are
15623: arrayrefs and hashrefs
15624: 
15625: =item *
15626: 
15627: arrayref2str($arrayref) : convert an arrayref into a string complete
15628: with escaping and '&' separators, supports elements that are arrayrefs
15629: and hashrefs
15630: 
15631: =item *
15632: 
15633: str2hash($string) : convert string to hash using unescaping and
15634: splitting on '=' and '&', supports elements that are arrayrefs and
15635: hashrefs
15636: 
15637: =item *
15638: 
15639: str2array($string) : convert string to hash using unescaping and
15640: splitting on '&', supports elements that are arrayrefs and hashrefs
15641: 
15642: =back
15643: 
15644: =head2 Logging Routines
15645: 
15646: 
15647: These routines allow one to make log messages in the lonnet.log and
15648: lonnet.perm logfiles.
15649: 
15650: =over 4
15651: 
15652: =item *
15653: 
15654: logtouch() : make sure the logfile, lonnet.log, exists
15655: 
15656: =item *
15657: 
15658: logthis() : append message to the normal lonnet.log file, it gets
15659: preiodically rolled over and deleted.
15660: 
15661: =item *
15662: 
15663: logperm() : append a permanent message to lonnet.perm.log, this log
15664: file never gets deleted by any automated portion of the system, only
15665: messages of critical importance should go in here.
15666: 
15667: 
15668: =back
15669: 
15670: =head2 General File Helper Routines
15671: 
15672: =over 4
15673: 
15674: =item *
15675: 
15676: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15677: (a) files in /uploaded
15678:   (i) If a local copy of the file exists - 
15679:       compares modification date of local copy with last-modified date for 
15680:       definitive version stored on home server for course. If local copy is 
15681:       stale, requests a new version from the home server and stores it. 
15682:       If the original has been removed from the home server, then local copy 
15683:       is unlinked.
15684:   (ii) If local copy does not exist -
15685:       requests the file from the home server and stores it. 
15686:   
15687:   If $caller is 'uploadrep':  
15688:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15689:     for request for files originally uploaded via DOCS. 
15690:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15691:   
15692:   Otherwise:
15693:      This indicates a call from the content generation phase of the request.
15694:      -  returns the entire contents of the file or -1.
15695:      
15696: (b) files in /res
15697:    - returns the entire contents of a file or -1; 
15698:    it properly subscribes to and replicates the file if neccessary.
15699: 
15700: 
15701: =item *
15702: 
15703: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15704:                   reference
15705: 
15706: returns either a stat() list of data about the file or an empty list
15707: if the file doesn't exist or couldn't find out about it (connection
15708: problems or user unknown)
15709: 
15710: =item *
15711: 
15712: filelocation($dir,$file) : returns file system location of a file
15713: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15714: directory that relative $file lookups are to looked in ($dir of /a/dir
15715: and a file of ../bob will become /a/bob)
15716: 
15717: =item *
15718: 
15719: hreflocation($dir,$file) : returns file system location or a URL; same as
15720: filelocation except for hrefs
15721: 
15722: =item *
15723: 
15724: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15725: also removes beginning /home/httpd/html unless /priv/ follows it.
15726: 
15727: =back
15728: 
15729: =head2 Usererfile file routines (/uploaded*)
15730: 
15731: =over 4
15732: 
15733: =item *
15734: 
15735: userfileupload(): main rotine for putting a file in a user or course's
15736:                   filespace, arguments are,
15737: 
15738:  formname - required - this is the name of the element in $env where the
15739:            filename, and the contents of the file to create/modifed exist
15740:            the filename is in $env{'form.'.$formname.'.filename'} and the
15741:            contents of the file is located in $env{'form.'.$formname}
15742:  context - if coursedoc, store the file in the course of the active role
15743:              of the current user; 
15744:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15745:            if 'canceloverwrite': delete file in tmp/overwrites directory
15746:  subdir - required - subdirectory to put the file in under ../userfiles/
15747:          if undefined, it will be placed in "unknown"
15748: 
15749:  (This routine calls clean_filename() to remove any dangerous
15750:  characters from the filename, and then calls finuserfileupload() to
15751:  complete the transaction)
15752: 
15753:  returns either the url of the uploaded file (/uploaded/....) if successful
15754:  and /adm/notfound.html if unsuccessful
15755: 
15756: =item *
15757: 
15758: clean_filename(): routine for cleaing a filename up for storage in
15759:                  userfile space, argument is:
15760: 
15761:  filename - proposed filename
15762: 
15763: returns: the new clean filename
15764: 
15765: =item *
15766: 
15767: finishuserfileupload(): routine that creates and sends the file to
15768: userspace, probably shouldn't be called directly
15769: 
15770:   docuname: username or courseid of destination for the file
15771:   docudom: domain of user/course of destination for the file
15772:   formname: same as for userfileupload()
15773:   fname: filename (including subdirectories) for the file
15774:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15775:   allfiles: reference to hash used to store objects found by parser
15776:   codebase: reference to hash used for codebases of java objects found by parser
15777:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15778:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15779:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15780:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15781:   context: if 'overwrite', will move the uploaded file from its temporary location to
15782:             userfiles to facilitate overwriting a previously uploaded file with same name.
15783:   mimetype: reference to scalar to accommodate mime type determined
15784:             from File::MMagic if $parser = parse.
15785: 
15786:  returns either the url of the uploaded file (/uploaded/....) if successful
15787:  and /adm/notfound.html if unsuccessful (or an error message if context 
15788:  was 'overwrite').
15789:  
15790: 
15791: =item *
15792: 
15793: renameuserfile(): renames an existing userfile to a new name
15794: 
15795:   Args:
15796:    docuname: username or courseid of destination for the file
15797:    docudom: domain of user/course of destination for the file
15798:    old: current file name (including any subdirs under userfiles)
15799:    new: desired file name (including any subdirs under userfiles)
15800: 
15801: =item *
15802: 
15803: mkdiruserfile(): creates a directory is a userfiles dir
15804: 
15805:   Args:
15806:    docuname: username or courseid of destination for the file
15807:    docudom: domain of user/course of destination for the file
15808:    dir: dir to create (including any subdirs under userfiles)
15809: 
15810: =item *
15811: 
15812: removeuserfile(): removes a file that exists in userfiles
15813: 
15814:   Args:
15815:    docuname: username or courseid of destination for the file
15816:    docudom: domain of user/course of destination for the file
15817:    fname: filname to delete (including any subdirs under userfiles)
15818: 
15819: =item *
15820: 
15821: removeuploadedurl(): convience function for removeuserfile()
15822: 
15823:   Args:
15824:    url:  a full /uploaded/... url to delete
15825: 
15826: =item * 
15827: 
15828: get_portfile_permissions():
15829:   Args:
15830:     domain: domain of user or course contain the portfolio files
15831:     user: name of user or num of course contain the portfolio files
15832:   Returns:
15833:     hashref of a dump of the proper file_permissions.db
15834:    
15835: 
15836: =item * 
15837: 
15838: get_access_controls():
15839: 
15840: Args:
15841:   current_permissions: the hash ref returned from get_portfile_permissions()
15842:   group: (optional) the group you want the files associated with
15843:   file: (optional) the file you want access info on
15844: 
15845: Returns:
15846:     a hash (keys are file names) of hashes containing
15847:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15848:         values are XML containing access control settings (see below) 
15849: 
15850: Internal notes:
15851: 
15852:  access controls are stored in file_permissions.db as key=value pairs.
15853:     key -> path to file/file_name\0uniqueID:scope_end_start
15854:         where scope -> public,guest,course,group,domains or users.
15855:               end -> UNIX time for end of access (0 -> no end date)
15856:               start -> UNIX time for start of access
15857: 
15858:     value -> XML description of access control
15859:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15860:             <start></start>
15861:             <end></end>
15862: 
15863:             <password></password>  for scope type = guest
15864: 
15865:             <domain></domain>     for scope type = course or group
15866:             <number></number>
15867:             <roles id="">
15868:              <role></role>
15869:              <access></access>
15870:              <section></section>
15871:              <group></group>
15872:             </roles>
15873: 
15874:             <dom></dom>         for scope type = domains
15875: 
15876:             <users>             for scope type = users
15877:              <user>
15878:               <uname></uname>
15879:               <udom></udom>
15880:              </user>
15881:             </users>
15882:            </scope> 
15883:               
15884:  Access data is also aggregated for each file in an additional key=value pair:
15885:  key -> path to file/file_name\0accesscontrol 
15886:  value -> reference to hash
15887:           hash contains key = value pairs
15888:           where key = uniqueID:scope_end_start
15889:                 value = UNIX time record was last updated
15890: 
15891:           Used to improve speed of look-ups of access controls for each file.  
15892:  
15893:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15894: 
15895: =item *
15896: 
15897: modify_access_controls():
15898: 
15899: Modifies access controls for a portfolio file
15900: Args
15901: 1. file name
15902: 2. reference to hash of required changes,
15903: 3. domain
15904: 4. username
15905:   where domain,username are the domain of the portfolio owner 
15906:   (either a user or a course) 
15907: 
15908: Returns:
15909: 1. result of additions or updates ('ok' or 'error', with error message). 
15910: 2. result of deletions ('ok' or 'error', with error message).
15911: 3. reference to hash of any new or updated access controls.
15912: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15913:    key = integer (inbound ID)
15914:    value = uniqueID
15915: 
15916: =item *
15917: 
15918: get_timebased_id():
15919: 
15920: Attempts to get a unique timestamp-based suffix for use with items added to a 
15921: course via the Course Editor (e.g., folders, composite pages, 
15922: group bulletin boards).
15923: 
15924: Args: (first three required; six others optional)
15925: 
15926: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15927:    docssequence, or name of group
15928: 
15929: 2. keyid (alphanumeric): name of temporary locking key in hash,
15930:    e.g., num, boardids
15931: 
15932: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15933:    file will be named nohist_namespace.db
15934: 
15935: 4. cdom: domain of course; default is current course domain from %env
15936: 
15937: 5. cnum: course number; default is current course number from %env
15938: 
15939: 6. idtype: set to concat if an additional digit is to be appended to the 
15940:    unix timestamp to form the suffix, if the plain timestamp is already
15941:    in use.  Default is to not do this, but simply increment the unix 
15942:    timestamp by 1 until a unique key is obtained.
15943: 
15944: 7. who: holder of locking key; defaults to user:domain for user.
15945: 
15946: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15947:    retrying); default is 3.
15948: 
15949: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15950: 
15951: Returns:
15952: 
15953: 1. suffix obtained (numeric)
15954: 
15955: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15956: 
15957: 3. error: contains (localized) error message if an error occurred.
15958: 
15959: 
15960: =back
15961: 
15962: =head2 HTTP Helper Routines
15963: 
15964: =over 4
15965: 
15966: =item *
15967: 
15968: escape() : unpack non-word characters into CGI-compatible hex codes
15969: 
15970: =item *
15971: 
15972: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15973: 
15974: =back
15975: 
15976: =head1 PRIVATE SUBROUTINES
15977: 
15978: =head2 Underlying communication routines (Shouldn't call)
15979: 
15980: =over 4
15981: 
15982: =item *
15983: 
15984: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15985: 
15986: =item *
15987: 
15988: reply() : uses subreply to send a message to remote machine, logs all failures
15989: 
15990: =item *
15991: 
15992: critical() : passes a critical message to another server; if cannot
15993: get through then place message in connection buffer directory and
15994: returns con_delayed, if incapable of saving message, returns
15995: con_failed
15996: 
15997: =item *
15998: 
15999: reconlonc() : tries to reconnect lonc client processes.
16000: 
16001: =back
16002: 
16003: =head2 Resource Access Logging
16004: 
16005: =over 4
16006: 
16007: =item *
16008: 
16009: flushcourselogs() : flush (save) buffer logs and access logs
16010: 
16011: =item *
16012: 
16013: courselog($what) : save message for course in hash
16014: 
16015: =item *
16016: 
16017: courseacclog($what) : save message for course using &courselog().  Perform
16018: special processing for specific resource types (problems, exams, quizzes, etc).
16019: 
16020: =item *
16021: 
16022: goodbye() : flush course logs and log shutting down; it is called in srm.conf
16023: as a PerlChildExitHandler
16024: 
16025: =back
16026: 
16027: =head2 Other
16028: 
16029: =over 4
16030: 
16031: =item *
16032: 
16033: symblist($mapname,%newhash) : update symbolic storage links
16034: 
16035: =back
16036: 
16037: =cut
16038: 

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