File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1388: download - view: text, annotated - select for diffs
Thu Nov 1 18:20:40 2018 UTC (5 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Typo.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1388 2018/11/01 18:20:40 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: 
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$hostname,$context) = @_;
  234:     return if ($lonhost eq '');
  235:     if ($hostname eq '') {
  236:         $hostname = &hostname($lonhost);
  237:     }
  238:     return if ($hostname eq '');
  239:     my ($rep,$uselocal);
  240:     if ($context eq 'install') {
  241:         $uselocal = 1;
  242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  243:         $uselocal = 1;
  244:     }
  245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  247:         if ($distro eq '') {
  248:             $uselocal = 0;
  249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  250:             if ($1 < 6) {
  251:                 $uselocal = 0;
  252:             }
  253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  254:             if ($1 < 12) {
  255:                 $uselocal = 0;
  256:             }
  257:         }
  258:     }
  259:     if ($uselocal) {
  260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  261:     } else {
  262:         $rep=&reply('servercerts',$lonhost);
  263:     }
  264:     my ($result,%returnhash);
  265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  266:         ($rep eq 'unknown_cmd')) {
  267:         $result = $rep;
  268:     } else {
  269:         $result = 'ok';
  270:         my @pairs=split(/\&/,$rep);
  271:         foreach my $item (@pairs) {
  272:             my ($key,$value)=split(/=/,$item,2);
  273:             my $what = &unescape($key);
  274:             $returnhash{$what}=&thaw_unescape($value);
  275:         }
  276:     }
  277:     return ($result,\%returnhash);
  278: }
  279: 
  280: sub get_server_loncaparev {
  281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  282:     if (defined($lonhost)) {
  283:         if (!defined(&hostname($lonhost))) {
  284:             undef($lonhost);
  285:         }
  286:     }
  287:     if (!defined($lonhost)) {
  288:         if (defined(&domain($dom,'primary'))) {
  289:             $lonhost=&domain($dom,'primary');
  290:             if ($lonhost eq 'no_host') {
  291:                 undef($lonhost);
  292:             }
  293:         }
  294:     }
  295:     if (defined($lonhost)) {
  296:         my $cachetime = 12*3600;
  297:         if (!$ignore_cache) {
  298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  299:             if (defined($cached)) {
  300:                 return $loncaparev;
  301:             }
  302:         }
  303:         my ($answer,$loncaparev);
  304:         my @ids=&current_machine_ids();
  305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  306:             $answer = $perlvar{'lonVersion'};
  307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  308:                 $loncaparev = $1;
  309:             }
  310:         } else {
  311:             $answer = &reply('serverloncaparev',$lonhost);
  312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  313:                 if ($caller eq 'loncron') {
  314:                     my $protocol = $protocol{$lonhost};
  315:                     $protocol = 'http' if ($protocol ne 'https');
  316:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  317:                     my $request=new HTTP::Request('GET',$url);
  318:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  319:                     unless ($response->is_error()) {
  320:                         my $content = $response->content;
  321:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  322:                             $loncaparev = $1;
  323:                         }
  324:                     }
  325:                 } else {
  326:                     $loncaparev = $loncaparevs{$lonhost};
  327:                 }
  328:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  329:                 $loncaparev = $1;
  330:             }
  331:         }
  332:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  333:     }
  334: }
  335: 
  336: sub get_server_homeID {
  337:     my ($hostname,$ignore_cache,$caller) = @_;
  338:     unless ($ignore_cache) {
  339:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  340:         if (defined($cached)) {
  341:             return $serverhomeID;
  342:         }
  343:     }
  344:     my $cachetime = 12*3600;
  345:     my $serverhomeID;
  346:     if ($caller eq 'loncron') { 
  347:         my @machine_ids = &machine_ids($hostname);
  348:         foreach my $id (@machine_ids) {
  349:             my $response = &reply('serverhomeID',$id);
  350:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  351:                 $serverhomeID = $response;
  352:                 last;
  353:             }
  354:         }
  355:         if ($serverhomeID eq '') {
  356:             $serverhomeID = $machine_ids[-1];
  357:         }
  358:     } else {
  359:         $serverhomeID = $serverhomeIDs{$hostname};
  360:     }
  361:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  362: }
  363: 
  364: sub get_remote_globals {
  365:     my ($lonhost,$whathash,$ignore_cache) = @_;
  366:     my ($result,%returnhash,%whatneeded);
  367:     if (ref($whathash) eq 'HASH') {
  368:         foreach my $what (sort(keys(%{$whathash}))) {
  369:             my $hashid = $lonhost.'-'.$what;
  370:             my ($response,$cached);
  371:             unless ($ignore_cache) {
  372:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  373:             }
  374:             if (defined($cached)) {
  375:                 $returnhash{$what} = $response;
  376:             } else {
  377:                 $whatneeded{$what} = 1;
  378:             }
  379:         }
  380:         if (keys(%whatneeded) == 0) {
  381:             $result = 'ok';
  382:         } else {
  383:             my $requested = &freeze_escape(\%whatneeded);
  384:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  385:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  386:                 ($rep eq 'unknown_cmd')) {
  387:                 $result = $rep;
  388:             } else {
  389:                 $result = 'ok';
  390:                 my @pairs=split(/\&/,$rep);
  391:                 foreach my $item (@pairs) {
  392:                     my ($key,$value)=split(/=/,$item,2);
  393:                     my $what = &unescape($key);
  394:                     my $hashid = $lonhost.'-'.$what;
  395:                     $returnhash{$what}=&thaw_unescape($value);
  396:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  397:                 }
  398:             }
  399:         }
  400:     }
  401:     return ($result,\%returnhash);
  402: }
  403: 
  404: sub remote_devalidate_cache {
  405:     my ($lonhost,$cachekeys) = @_;
  406:     my $items;
  407:     return unless (ref($cachekeys) eq 'ARRAY');
  408:     my $cachestr = join('&',@{$cachekeys});
  409:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  410:     return $response;
  411: }
  412: 
  413: # -------------------------------------------------- Non-critical communication
  414: sub subreply {
  415:     my ($cmd,$server)=@_;
  416:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  417:     #
  418:     #  With loncnew process trimming, there's a timing hole between lonc server
  419:     #  process exit and the master server picking up the listen on the AF_UNIX
  420:     #  socket.  In that time interval, a lock file will exist:
  421: 
  422:     my $lockfile=$peerfile.".lock";
  423:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  424: 	sleep(0.1);
  425:     }
  426:     # At this point, either a loncnew parent is listening or an old lonc
  427:     # or loncnew child is listening so we can connect or everything's dead.
  428:     #
  429:     #   We'll give the connection a few tries before abandoning it.  If
  430:     #   connection is not possible, we'll con_lost back to the client.
  431:     #   
  432:     my $client;
  433:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  434: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  435: 				      Type    => SOCK_STREAM,
  436: 				      Timeout => 10);
  437: 	if ($client) {
  438: 	    last;		# Connected!
  439: 	} else {
  440: 	    &create_connection(&hostname($server),$server);
  441: 	}
  442:         sleep(0.1);	# Try again later if failed connection.
  443:     }
  444:     my $answer;
  445:     if ($client) {
  446: 	print $client "sethost:$server:$cmd\n";
  447: 	$answer=<$client>;
  448: 	if (!$answer) { $answer="con_lost"; }
  449: 	chomp($answer);
  450:     } else {
  451: 	$answer = 'con_lost';	# Failed connection.
  452:     }
  453:     return $answer;
  454: }
  455: 
  456: sub reply {
  457:     my ($cmd,$server)=@_;
  458:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  459:     my $answer=subreply($cmd,$server);
  460:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  461:        &logthis("<font color=\"blue\">WARNING:".
  462:                 " $cmd to $server returned $answer</font>");
  463:     }
  464:     return $answer;
  465: }
  466: 
  467: # ----------------------------------------------------------- Send USR1 to lonc
  468: 
  469: sub reconlonc {
  470:     my ($lonid) = @_;
  471:     if ($lonid) {
  472:         my $hostname = &hostname($lonid);
  473: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  474: 	if ($hostname && -e $peerfile) {
  475: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  476: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  477: 					     Type    => SOCK_STREAM,
  478: 					     Timeout => 10);
  479: 	    if ($client) {
  480: 		print $client ("reset_retries\n");
  481: 		my $answer=<$client>;
  482: 		#reset just this one.
  483: 	    }
  484: 	}
  485: 	return;
  486:     }
  487: 
  488:     &logthis("Trying to reconnect lonc");
  489:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  490:     if (open(my $fh,"<",$loncfile)) {
  491: 	my $loncpid=<$fh>;
  492:         chomp($loncpid);
  493:         if (kill 0 => $loncpid) {
  494: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  495:             kill USR1 => $loncpid;
  496:             sleep 1;
  497:         } else {
  498: 	    &logthis(
  499:                "<font color=\"blue\">WARNING:".
  500:                " lonc at pid $loncpid not responding, giving up</font>");
  501:         }
  502:     } else {
  503: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  504:     }
  505: }
  506: 
  507: # ------------------------------------------------------ Critical communication
  508: 
  509: sub critical {
  510:     my ($cmd,$server)=@_;
  511:     unless (&hostname($server)) {
  512:         &logthis("<font color=\"blue\">WARNING:".
  513:                " Critical message to unknown server ($server)</font>");
  514:         return 'no_such_host';
  515:     }
  516:     my $answer=reply($cmd,$server);
  517:     if ($answer eq 'con_lost') {
  518: 	&reconlonc($server);
  519: 	my $answer=reply($cmd,$server);
  520:         if ($answer eq 'con_lost') {
  521:             my $now=time;
  522:             my $middlename=$cmd;
  523:             $middlename=substr($middlename,0,16);
  524:             $middlename=~s/\W//g;
  525:             my $dfilename=
  526:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  527:             $dumpcount++;
  528:             {
  529: 		my $dfh;
  530: 		if (open($dfh,">",$dfilename)) {
  531: 		    print $dfh "$cmd\n"; 
  532: 		    close($dfh);
  533: 		}
  534:             }
  535:             sleep 1;
  536:             my $wcmd='';
  537:             {
  538: 		my $dfh;
  539: 		if (open($dfh,"<",$dfilename)) {
  540: 		    $wcmd=<$dfh>; 
  541: 		    close($dfh);
  542: 		}
  543:             }
  544:             chomp($wcmd);
  545:             if ($wcmd eq $cmd) {
  546: 		&logthis("<font color=\"blue\">WARNING: ".
  547:                          "Connection buffer $dfilename: $cmd</font>");
  548:                 &logperm("D:$server:$cmd");
  549: 	        return 'con_delayed';
  550:             } else {
  551:                 &logthis("<font color=\"red\">CRITICAL:"
  552:                         ." Critical connection failed: $server $cmd</font>");
  553:                 &logperm("F:$server:$cmd");
  554:                 return 'con_failed';
  555:             }
  556:         }
  557:     }
  558:     return $answer;
  559: }
  560: 
  561: # ------------------------------------------- check if return value is an error
  562: 
  563: sub error {
  564:     my ($result) = @_;
  565:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  566: 	if ($2 == 2) { return undef; }
  567: 	return $1;
  568:     }
  569:     return undef;
  570: }
  571: 
  572: sub convert_and_load_session_env {
  573:     my ($lonidsdir,$handle)=@_;
  574:     my @profile;
  575:     {
  576: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  577: 	if (!$opened) {
  578: 	    return 0;
  579: 	}
  580: 	flock($idf,LOCK_SH);
  581: 	@profile=<$idf>;
  582: 	close($idf);
  583:     }
  584:     my %temp_env;
  585:     foreach my $line (@profile) {
  586: 	if ($line !~ m/=/) {
  587: 	    return 0;
  588: 	}
  589: 	chomp($line);
  590: 	my ($envname,$envvalue)=split(/=/,$line,2);
  591: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  592:     }
  593:     unlink("$lonidsdir/$handle.id");
  594:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  595: 	    0640)) {
  596: 	%disk_env = %temp_env;
  597: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  598: 	untie(%disk_env);
  599:     }
  600:     return 1;
  601: }
  602: 
  603: # ------------------------------------------- Transfer profile into environment
  604: my $env_loaded;
  605: sub transfer_profile_to_env {
  606:     my ($lonidsdir,$handle,$force_transfer) = @_;
  607:     if (!$force_transfer && $env_loaded) { return; } 
  608: 
  609:     if (!defined($lonidsdir)) {
  610: 	$lonidsdir = $perlvar{'lonIDsDir'};
  611:     }
  612:     if (!defined($handle)) {
  613:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  614:     }
  615: 
  616:     my $convert;
  617:     {
  618:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  619: 	if (!$opened) {
  620: 	    return;
  621: 	}
  622: 	flock($idf,LOCK_SH);
  623: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  624: 		&GDBM_READER(),0640)) {
  625: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  626: 	    untie(%disk_env);
  627: 	} else {
  628: 	    $convert = 1;
  629: 	}
  630:     }
  631:     if ($convert) {
  632: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  633: 	    &logthis("Failed to load session, or convert session.");
  634: 	}
  635:     }
  636: 
  637:     my %remove;
  638:     while ( my $envname = each(%env) ) {
  639:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  640:             if ($time < time-300) {
  641:                 $remove{$key}++;
  642:             }
  643:         }
  644:     }
  645: 
  646:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  647:     $env_loaded=1;
  648:     foreach my $expired_key (keys(%remove)) {
  649:         &delenv($expired_key);
  650:     }
  651: }
  652: 
  653: # ---------------------------------------------------- Check for valid session 
  654: sub check_for_valid_session {
  655:     my ($r,$name,$userhashref,$domref) = @_;
  656:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  657:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  658:     if ($name eq 'lonDAV') {
  659:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  660:     } else {
  661:         $lonidsdir=$r->dir_config('lonIDsDir');
  662:         if ($name eq '') {
  663:             $name = 'lonID';
  664:         }
  665:     }
  666:     if ($name eq 'lonID') {
  667:         $secure = 'lonSID';
  668:         $linkname = 'lonLinkID';
  669:         $pubname = 'lonPubID';
  670:         if (exists($cookies{$secure})) {
  671:             $lonid=$cookies{$secure};
  672:         } elsif (exists($cookies{$name})) {
  673:             $lonid=$cookies{$name};
  674:         } elsif (exists($cookies{$linkname})) {
  675:             $lonid=$cookies{$linkname};
  676:         } elsif (exists($cookies{$pubname})) {
  677:             $lonid=$cookies{$pubname};
  678:         }
  679:     } else {
  680:         $lonid=$cookies{$name};
  681:     }
  682:     return undef if (!$lonid);
  683: 
  684:     my $handle=&LONCAPA::clean_handle($lonid->value);
  685:     if (-l "$lonidsdir/$handle.id") {
  686:         my $link = readlink("$lonidsdir/$handle.id");
  687:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  688:             $handle = $1;
  689:         }
  690:     }
  691:     if (!-e "$lonidsdir/$handle.id") {
  692:         if ((ref($domref)) && ($name eq 'lonID') && 
  693:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  694:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  695:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  696:                 $$domref = $possudom;
  697:             }
  698:         }
  699:         return undef;
  700:     }
  701: 
  702:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  703:     return undef if (!$opened);
  704: 
  705:     flock($idf,LOCK_SH);
  706:     my %disk_env;
  707:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  708: 	    &GDBM_READER(),0640)) {
  709: 	return undef;	
  710:     }
  711: 
  712:     if (!defined($disk_env{'user.name'})
  713: 	|| !defined($disk_env{'user.domain'})) {
  714: 	return undef;
  715:     }
  716: 
  717:     if (ref($userhashref) eq 'HASH') {
  718:         $userhashref->{'name'} = $disk_env{'user.name'};
  719:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  720:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  721:         if ($userhashref->{'lti'}) {
  722:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  723:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  724:         }
  725:     }
  726: 
  727:     return $handle;
  728: }
  729: 
  730: sub timed_flock {
  731:     my ($file,$lock_type) = @_;
  732:     my $failed=0;
  733:     eval {
  734: 	local $SIG{__DIE__}='DEFAULT';
  735: 	local $SIG{ALRM}=sub {
  736: 	    $failed=1;
  737: 	    die("failed lock");
  738: 	};
  739: 	alarm(13);
  740: 	flock($file,$lock_type);
  741: 	alarm(0);
  742:     };
  743:     if ($failed) {
  744: 	return undef;
  745:     } else {
  746: 	return 1;
  747:     }
  748: }
  749: 
  750: # ---------------------------------------------------------- Append Environment
  751: 
  752: sub appenv {
  753:     my ($newenv,$roles) = @_;
  754:     if (ref($newenv) eq 'HASH') {
  755:         foreach my $key (keys(%{$newenv})) {
  756:             my $refused = 0;
  757: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  758:                 $refused = 1;
  759:                 if (ref($roles) eq 'ARRAY') {
  760:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  761:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  762:                         $refused = 0;
  763:                     }
  764:                 }
  765:             }
  766:             if ($refused) {
  767:                 &logthis("<font color=\"blue\">WARNING: ".
  768:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  769:                          .'</font>');
  770: 	        delete($newenv->{$key});
  771:             } else {
  772:                 $env{$key}=$newenv->{$key};
  773:             }
  774:         }
  775:         my $lonids = $perlvar{'lonIDsDir'};
  776:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  777:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  778:             if ($opened
  779: 	        && &timed_flock($env_file,LOCK_EX)
  780: 	        &&
  781: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  782: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  783: 	        while (my ($key,$value) = each(%{$newenv})) {
  784: 	            $disk_env{$key} = $value;
  785: 	        }
  786: 	        untie(%disk_env);
  787:             }
  788:         }
  789:     }
  790:     return 'ok';
  791: }
  792: # ----------------------------------------------------- Delete from Environment
  793: 
  794: sub delenv {
  795:     my ($delthis,$regexp,$roles) = @_;
  796:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  797:         my $refused = 1;
  798:         if (ref($roles) eq 'ARRAY') {
  799:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  800:             if (grep(/^\Q$role\E$/,@{$roles})) {
  801:                 $refused = 0;
  802:             }
  803:         }
  804:         if ($refused) {
  805:             &logthis("<font color=\"blue\">WARNING: ".
  806:                      "Attempt to delete from environment ".$delthis);
  807:             return 'error';
  808:         }
  809:     }
  810:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  811:     if ($opened
  812: 	&& &timed_flock($env_file,LOCK_EX)
  813: 	&&
  814: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  815: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  816: 	foreach my $key (keys(%disk_env)) {
  817: 	    if ($regexp) {
  818:                 if ($key=~/^$delthis/) {
  819:                     delete($env{$key});
  820:                     delete($disk_env{$key});
  821:                 } 
  822:             } else {
  823:                 if ($key=~/^\Q$delthis\E/) {
  824: 		    delete($env{$key});
  825: 		    delete($disk_env{$key});
  826: 	        }
  827:             }
  828: 	}
  829: 	untie(%disk_env);
  830:     }
  831:     return 'ok';
  832: }
  833: 
  834: sub get_env_multiple {
  835:     my ($name) = @_;
  836:     my @values;
  837:     if (defined($env{$name})) {
  838:         # exists is it an array
  839:         if (ref($env{$name})) {
  840:             @values=@{ $env{$name} };
  841:         } else {
  842:             $values[0]=$env{$name};
  843:         }
  844:     }
  845:     return(@values);
  846: }
  847: 
  848: # ------------------------------------------------------------------- Locking
  849: 
  850: sub set_lock {
  851:     my ($text)=@_;
  852:     $locknum++;
  853:     my $id=$$.'-'.$locknum;
  854:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  855:              'session.lock.'.$id => $text});
  856:     return $id;
  857: }
  858: 
  859: sub get_locks {
  860:     my $num=0;
  861:     my %texts=();
  862:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  863:        if ($lock=~/\w/) {
  864:           $num++;
  865:           $texts{$lock}=$env{'session.lock.'.$lock};
  866:        }
  867:    }
  868:    return ($num,%texts);
  869: }
  870: 
  871: sub remove_lock {
  872:     my ($id)=@_;
  873:     my $newlocks='';
  874:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  875:        if (($lock=~/\w/) && ($lock ne $id)) {
  876:           $newlocks.=','.$lock;
  877:        }
  878:     }
  879:     &appenv({'session.locks' => $newlocks});
  880:     &delenv('session.lock.'.$id);
  881: }
  882: 
  883: sub remove_all_locks {
  884:     my $activelocks=$env{'session.locks'};
  885:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  886:        if ($lock=~/\w/) {
  887:           &remove_lock($lock);
  888:        }
  889:     }
  890: }
  891: 
  892: 
  893: # ------------------------------------------ Find out current server userload
  894: sub userload {
  895:     my $numusers=0;
  896:     {
  897: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  898: 	my $filename;
  899: 	my $curtime=time;
  900: 	while ($filename=readdir(LONIDS)) {
  901: 	    next if ($filename eq '.' || $filename eq '..');
  902: 	    next if ($filename =~ /publicuser_\d+\.id/);
  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  905: 	}
  906: 	closedir(LONIDS);
  907:     }
  908:     my $userloadpercent=0;
  909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  910:     if ($maxuserload) {
  911: 	$userloadpercent=100*$numusers/$maxuserload;
  912:     }
  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  914:     return $userloadpercent;
  915: }
  916: 
  917: # ------------------------------ Find server with least workload from spare.tab
  918: 
  919: sub spareserver {
  920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  921:     my $spare_server;
  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  924:                                                      :  $userloadpercent;
  925:     my ($uint_dom,$remotesessions);
  926:     if (($udom ne '') && (&domain($udom) ne '')) {
  927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  930:         $remotesessions = $udomdefaults{'remotesessions'};
  931:     }
  932:     my $spareshash = &this_host_spares($udom);
  933:     if (ref($spareshash) eq 'HASH') {
  934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  937:                                              $try_server));
  938: 	        ($spare_server, $lowest_load) =
  939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  940:             }
  941:         }
  942: 
  943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  944: 
  945:         if (!$found_server) {
  946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  948:                     next unless (&spare_can_host($udom,$uint_dom,
  949:                                                  $remotesessions,$try_server));
  950: 	            ($spare_server, $lowest_load) =
  951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  952:                 }
  953: 	    }
  954:         }
  955:     }
  956: 
  957:     if (!$want_server_name) {
  958:         my $protocol = 'http';
  959:         if ($protocol{$spare_server} eq 'https') {
  960:             $protocol = $protocol{$spare_server};
  961:         }
  962:         if (defined($spare_server)) {
  963:             my $hostname = &hostname($spare_server);
  964:             if (defined($hostname)) {
  965: 	        $spare_server = $protocol.'://'.$hostname;
  966:             }
  967:         }
  968:     }
  969:     return $spare_server;
  970: }
  971: 
  972: sub compare_server_load {
  973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  974: 
  975:     if ($required) {
  976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  979:         if (($major eq '' && $minor eq '') ||
  980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  981:             return ($spare_server,$lowest_load);
  982:         }
  983:     }
  984: 
  985:     my $loadans     = &reply('load',    $try_server);
  986:     my $userloadans = &reply('userload',$try_server);
  987: 
  988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  990:     }
  991: 
  992:     my $load;
  993:     if ($loadans =~ /\d/) {
  994: 	if ($userloadans =~ /\d/) {
  995: 	    #both are numbers, pick the bigger one
  996: 	    $load = ($loadans > $userloadans) ? $loadans 
  997: 		                              : $userloadans;
  998: 	} else {
  999: 	    $load = $loadans;
 1000: 	}
 1001:     } else {
 1002: 	$load = $userloadans;
 1003:     }
 1004: 
 1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1006: 	$spare_server = $try_server;
 1007: 	$lowest_load  = $load;
 1008:     }
 1009:     return ($spare_server,$lowest_load);
 1010: }
 1011: 
 1012: # --------------------------- ask offload servers if user already has a session
 1013: sub find_existing_session {
 1014:     my ($udom,$uname) = @_;
 1015:     my $spareshash = &this_host_spares($udom);
 1016:     if (ref($spareshash) eq 'HASH') {
 1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1020:             }
 1021:         }
 1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1025:             }
 1026:         }
 1027:     }
 1028:     return;
 1029: }
 1030: 
 1031: # -------------------------------- ask if server already has a session for user
 1032: sub has_user_session {
 1033:     my ($lonid,$udom,$uname) = @_;
 1034:     my $result = &reply(join(':','userhassession',
 1035: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1036:     return 1 if ($result eq 'ok');
 1037: 
 1038:     return 0;
 1039: }
 1040: 
 1041: # --------- determine least loaded server in a user's domain which allows login
 1042: 
 1043: sub choose_server {
 1044:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1045:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1046:     my %servers = &get_servers($udom);
 1047:     my $lowest_load = 30000;
 1048:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1049:     if ($skiploadbal) {
 1050:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1051:         unless (defined($cached)) {
 1052:             my $cachetime = 60*60*24;
 1053:             my %domconfig =
 1054:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1055:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1056:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1057:                                            $cachetime);
 1058:             }
 1059:         }
 1060:     }
 1061:     foreach my $lonhost (keys(%servers)) {
 1062:         if ($skiploadbal) {
 1063:             if (ref($balancers) eq 'HASH') {
 1064:                 next if (exists($balancers->{$lonhost}));
 1065:             }
 1066:         }   
 1067:         my $loginvia;
 1068:         if ($checkloginvia) {
 1069:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1070:             if ($loginvia) {
 1071:                 my ($server,$path) = split(/:/,$loginvia);
 1072:                 ($login_host, $lowest_load) =
 1073:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1074:                 if ($login_host eq $server) {
 1075:                     $portal_path = $path;
 1076:                     $isredirect = 1;
 1077:                 }
 1078:             } else {
 1079:                 ($login_host, $lowest_load) =
 1080:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1081:                 if ($login_host eq $lonhost) {
 1082:                     $portal_path = '';
 1083:                     $isredirect = ''; 
 1084:                 }
 1085:             }
 1086:         } else {
 1087:             ($login_host, $lowest_load) =
 1088:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1089:         }
 1090:     }
 1091:     if ($login_host ne '') {
 1092:         $hostname = &hostname($login_host);
 1093:     }
 1094:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1095: }
 1096: 
 1097: # --------------------------------------------- Try to change a user's password
 1098: 
 1099: sub changepass {
 1100:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1101:     $currentpass = &escape($currentpass);
 1102:     $newpass     = &escape($newpass);
 1103:     my $lonhost = $perlvar{'lonHostID'};
 1104:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1105: 		       $server);
 1106:     if (! $answer) {
 1107: 	&logthis("No reply on password change request to $server ".
 1108: 		 "by $uname in domain $udom.");
 1109:     } elsif ($answer =~ "^ok") {
 1110:         &logthis("$uname in $udom successfully changed their password ".
 1111: 		 "on $server.");
 1112:     } elsif ($answer =~ "^pwchange_failure") {
 1113: 	&logthis("$uname in $udom was unable to change their password ".
 1114: 		 "on $server.  The action was blocked by either lcpasswd ".
 1115: 		 "or pwchange");
 1116:     } elsif ($answer =~ "^non_authorized") {
 1117:         &logthis("$uname in $udom did not get their password correct when ".
 1118: 		 "attempting to change it on $server.");
 1119:     } elsif ($answer =~ "^auth_mode_error") {
 1120:         &logthis("$uname in $udom attempted to change their password despite ".
 1121: 		 "not being locally or internally authenticated on $server.");
 1122:     } elsif ($answer =~ "^unknown_user") {
 1123:         &logthis("$uname in $udom attempted to change their password ".
 1124: 		 "on $server but were unable to because $server is not ".
 1125: 		 "their home server.");
 1126:     } elsif ($answer =~ "^refused") {
 1127: 	&logthis("$server refused to change $uname in $udom password because ".
 1128: 		 "it was sent an unencrypted request to change the password.");
 1129:     } elsif ($answer =~ "invalid_client") {
 1130:         &logthis("$server refused to change $uname in $udom password because ".
 1131:                  "it was a reset by e-mail originating from an invalid server.");
 1132:     }
 1133:     return $answer;
 1134: }
 1135: 
 1136: # ----------------------- Try to determine user's current authentication scheme
 1137: 
 1138: sub queryauthenticate {
 1139:     my ($uname,$udom)=@_;
 1140:     my $uhome=&homeserver($uname,$udom);
 1141:     if (!$uhome) {
 1142: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1143: 	return 'no_host';
 1144:     }
 1145:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1146:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1147: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1148:     }
 1149:     return $answer;
 1150: }
 1151: 
 1152: # --------- Try to authenticate user from domain's lib servers (first this one)
 1153: 
 1154: sub authenticate {
 1155:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1156:     $upass=&escape($upass);
 1157:     $uname= &LONCAPA::clean_username($uname);
 1158:     my $uhome=&homeserver($uname,$udom,1);
 1159:     my $newhome;
 1160:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1161: # Maybe the machine was offline and only re-appeared again recently?
 1162:         &reconlonc();
 1163: # One more
 1164: 	$uhome=&homeserver($uname,$udom,1);
 1165:         if (($uhome eq 'no_host') && $checkdefauth) {
 1166:             if (defined(&domain($udom,'primary'))) {
 1167:                 $newhome=&domain($udom,'primary');
 1168:             }
 1169:             if ($newhome ne '') {
 1170:                 $uhome = $newhome;
 1171:             }
 1172:         }
 1173: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1174: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1175: 	    return 'no_host';
 1176:         }
 1177:     }
 1178:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1179:     if ($answer eq 'authorized') {
 1180:         if ($newhome) {
 1181:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1182:             return 'no_account_on_host'; 
 1183:         } else {
 1184:             &logthis("User $uname at $udom authorized by $uhome");
 1185:             return $uhome;
 1186:         }
 1187:     }
 1188:     if ($answer eq 'non_authorized') {
 1189: 	&logthis("User $uname at $udom rejected by $uhome");
 1190: 	return 'no_host'; 
 1191:     }
 1192:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1193:     return 'no_host';
 1194: }
 1195: 
 1196: sub can_host_session {
 1197:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1198:     my $canhost = 1;
 1199:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1200:     if (ref($remotesessions) eq 'HASH') {
 1201:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1202:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1203:                 $canhost = 0;
 1204:             } else {
 1205:                 $canhost = 1;
 1206:             }
 1207:         }
 1208:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1209:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1210:                 $canhost = 1;
 1211:             } else {
 1212:                 $canhost = 0;
 1213:             }
 1214:         }
 1215:         if ($canhost) {
 1216:             if ($remotesessions->{'version'} ne '') {
 1217:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1218:                 if ($reqmajor ne '' && $reqminor ne '') {
 1219:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1220:                         my $major = $1;
 1221:                         my $minor = $2;
 1222:                         if (($major < $reqmajor ) ||
 1223:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1224:                             $canhost = 0;
 1225:                         }
 1226:                     } else {
 1227:                         $canhost = 0;
 1228:                     }
 1229:                 }
 1230:             }
 1231:         }
 1232:     }
 1233:     if ($canhost) {
 1234:         if (ref($hostedsessions) eq 'HASH') {
 1235:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1236:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1237:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1238:                 if (($uint_dom ne '') && 
 1239:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1240:                     $canhost = 0;
 1241:                 } else {
 1242:                     $canhost = 1;
 1243:                 }
 1244:             }
 1245:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1246:                 if (($uint_dom ne '') && 
 1247:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1248:                     $canhost = 1;
 1249:                 } else {
 1250:                     $canhost = 0;
 1251:                 }
 1252:             }
 1253:         }
 1254:     }
 1255:     return $canhost;
 1256: }
 1257: 
 1258: sub spare_can_host {
 1259:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1260:     my $canhost=1;
 1261:     my $try_server_hostname = &hostname($try_server);
 1262:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1263:     my $serverhomedom = &host_domain($serverhomeID);
 1264:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1265:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1266:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1267:             $canhost = 0;
 1268:         }
 1269:     }
 1270:     if (($canhost) && ($uint_dom)) {
 1271:         my @intdoms;
 1272:         my $internet_names = &get_internet_names($try_server);
 1273:         if (ref($internet_names) eq 'ARRAY') {
 1274:             @intdoms = @{$internet_names};
 1275:         }
 1276:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1277:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1278:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1279:                                          $remotesessions,
 1280:                                          $defdomdefaults{'hostedsessions'});
 1281:         }
 1282:     }
 1283:     return $canhost;
 1284: }
 1285: 
 1286: sub this_host_spares {
 1287:     my ($dom) = @_;
 1288:     my ($dom_in_use,$lonhost_in_use,$result);
 1289:     my @hosts = &current_machine_ids();
 1290:     foreach my $lonhost (@hosts) {
 1291:         if (&host_domain($lonhost) eq $dom) {
 1292:             $dom_in_use = $dom;
 1293:             $lonhost_in_use = $lonhost;
 1294:             last;
 1295:         }
 1296:     }
 1297:     if ($dom_in_use ne '') {
 1298:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1299:     }
 1300:     if (ref($result) ne 'HASH') {
 1301:         $lonhost_in_use = $perlvar{'lonHostID'};
 1302:         $dom_in_use = &host_domain($lonhost_in_use);
 1303:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1304:         if (ref($result) ne 'HASH') {
 1305:             $result = \%spareid;
 1306:         }
 1307:     }
 1308:     return $result;
 1309: }
 1310: 
 1311: sub spares_for_offload  {
 1312:     my ($dom_in_use,$lonhost_in_use) = @_;
 1313:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1314:     if (defined($cached)) {
 1315:         return $result;
 1316:     } else {
 1317:         my $cachetime = 60*60*24;
 1318:         my %domconfig =
 1319:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1320:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1321:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1322:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1323:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1324:                 }
 1325:             }
 1326:         }
 1327:     }
 1328:     return;
 1329: }
 1330: 
 1331: sub get_lonbalancer_config {
 1332:     my ($servers) = @_;
 1333:     my ($currbalancer,$currtargets);
 1334:     if (ref($servers) eq 'HASH') {
 1335:         foreach my $server (keys(%{$servers})) {
 1336:             my %what = (
 1337:                          spareid => 1,
 1338:                          perlvar => 1,
 1339:                        );
 1340:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1341:             if ($result eq 'ok') {
 1342:                 if (ref($returnhash) eq 'HASH') {
 1343:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1344:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1345:                             $currbalancer = $server;
 1346:                             $currtargets = {};
 1347:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1348:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1349:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1350:                                 }
 1351:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1352:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1353:                                 }
 1354:                             }
 1355:                             last;
 1356:                         }
 1357:                     }
 1358:                 }
 1359:             }
 1360:         }
 1361:     }
 1362:     return ($currbalancer,$currtargets);
 1363: }
 1364: 
 1365: sub check_loadbalancing {
 1366:     my ($uname,$udom,$caller) = @_;
 1367:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1368:         $rule_in_effect,$offloadto,$otherserver);
 1369:     my $lonhost = $perlvar{'lonHostID'};
 1370:     my @hosts = &current_machine_ids();
 1371:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1372:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1373:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1374:     my $serverhomedom = &host_domain($lonhost);
 1375:     my $domneedscache;
 1376:     my $cachetime = 60*60*24;
 1377: 
 1378:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1379:         $dom_in_use = $udom;
 1380:         $homeintdom = 1;
 1381:     } else {
 1382:         $dom_in_use = $serverhomedom;
 1383:     }
 1384:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1385:     unless (defined($cached)) {
 1386:         my %domconfig =
 1387:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1388:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1389:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1390:         } else {
 1391:             $domneedscache = $dom_in_use;
 1392:         }
 1393:     }
 1394:     if (ref($result) eq 'HASH') {
 1395:         ($is_balancer,$currtargets,$currrules) = 
 1396:             &check_balancer_result($result,@hosts);
 1397:         if ($is_balancer) {
 1398:             if (ref($currrules) eq 'HASH') {
 1399:                 if ($homeintdom) {
 1400:                     if ($uname ne '') {
 1401:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1402:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1403:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1404:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1405:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1406:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1407:                             }
 1408:                         }
 1409:                         if ($rule_in_effect eq '') {
 1410:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1411:                             if ($userenv{'inststatus'} ne '') {
 1412:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1413:                                 my ($othertitle,$usertypes,$types) =
 1414:                                     &Apache::loncommon::sorted_inst_types($udom);
 1415:                                 if (ref($types) eq 'ARRAY') {
 1416:                                     foreach my $type (@{$types}) {
 1417:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1418:                                             if (exists($currrules->{$type})) {
 1419:                                                 $rule_in_effect = $currrules->{$type};
 1420:                                             }
 1421:                                         }
 1422:                                     }
 1423:                                 }
 1424:                             } else {
 1425:                                 if (exists($currrules->{'default'})) {
 1426:                                     $rule_in_effect = $currrules->{'default'};
 1427:                                 }
 1428:                             }
 1429:                         }
 1430:                     } else {
 1431:                         if (exists($currrules->{'default'})) {
 1432:                             $rule_in_effect = $currrules->{'default'};
 1433:                         }
 1434:                     }
 1435:                 } else {
 1436:                     if ($currrules->{'_LC_external'} ne '') {
 1437:                         $rule_in_effect = $currrules->{'_LC_external'};
 1438:                     }
 1439:                 }
 1440:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1441:                                                        $uname,$udom);
 1442:             }
 1443:         }
 1444:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1445:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1446:         unless (defined($cached)) {
 1447:             my %domconfig =
 1448:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1449:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1450:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1451:             } else {
 1452:                 $domneedscache = $serverhomedom;
 1453:             }
 1454:         }
 1455:         if (ref($result) eq 'HASH') {
 1456:             ($is_balancer,$currtargets,$currrules) = 
 1457:                 &check_balancer_result($result,@hosts);
 1458:             if ($is_balancer) {
 1459:                 if (ref($currrules) eq 'HASH') {
 1460:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1461:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1462:                     }
 1463:                 }
 1464:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1465:                                                        $uname,$udom);
 1466:             }
 1467:         } else {
 1468:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1469:                 $is_balancer = 1;
 1470:                 $offloadto = &this_host_spares($dom_in_use);
 1471:             }
 1472:             unless (defined($cached)) {
 1473:                 $domneedscache = $serverhomedom;
 1474:             }
 1475:         }
 1476:     } else {
 1477:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1478:             $is_balancer = 1;
 1479:             $offloadto = &this_host_spares($dom_in_use);
 1480:         }
 1481:         unless (defined($cached)) {
 1482:             $domneedscache = $serverhomedom;
 1483:         }
 1484:     }
 1485:     if ($domneedscache) {
 1486:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1487:     }
 1488:     if ($is_balancer) {
 1489:         my $lowest_load = 30000;
 1490:         if (ref($offloadto) eq 'HASH') {
 1491:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1492:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1493:                     ($otherserver,$lowest_load) =
 1494:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1495:                 }
 1496:             }
 1497:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1498: 
 1499:             if (!$found_server) {
 1500:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1501:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1502:                         ($otherserver,$lowest_load) =
 1503:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1504:                     }
 1505:                 }
 1506:             }
 1507:         } elsif (ref($offloadto) eq 'ARRAY') {
 1508:             if (@{$offloadto} == 1) {
 1509:                 $otherserver = $offloadto->[0];
 1510:             } elsif (@{$offloadto} > 1) {
 1511:                 foreach my $try_server (@{$offloadto}) {
 1512:                     ($otherserver,$lowest_load) =
 1513:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1514:                 }
 1515:             }
 1516:         }
 1517:         unless ($caller eq 'login') {
 1518:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1519:                 $is_balancer = 0;
 1520:                 if ($uname ne '' && $udom ne '') {
 1521:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1522:                     
 1523:                         &appenv({'user.loadbalexempt'     => $lonhost,  
 1524:                                  'user.loadbalcheck.time' => time});
 1525:                     }
 1526:                 }
 1527:             }
 1528:         }
 1529:     }
 1530:     return ($is_balancer,$otherserver);
 1531: }
 1532: 
 1533: sub check_balancer_result {
 1534:     my ($result,@hosts) = @_;
 1535:     my ($is_balancer,$currtargets,$currrules);
 1536:     if (ref($result) eq 'HASH') {
 1537:         if ($result->{'lonhost'} ne '') {
 1538:             my $currbalancer = $result->{'lonhost'};
 1539:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1540:                 $is_balancer = 1;
 1541:                 $currtargets = $result->{'targets'};
 1542:                 $currrules = $result->{'rules'};
 1543:             }
 1544:         } else {
 1545:             foreach my $key (keys(%{$result})) {
 1546:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1547:                     (ref($result->{$key}) eq 'HASH')) {
 1548:                     $is_balancer = 1;
 1549:                     $currrules = $result->{$key}{'rules'};
 1550:                     $currtargets = $result->{$key}{'targets'};
 1551:                     last;
 1552:                 }
 1553:             }
 1554:         }
 1555:     }
 1556:     return ($is_balancer,$currtargets,$currrules);
 1557: }
 1558: 
 1559: sub get_loadbalancer_targets {
 1560:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1561:     my $offloadto;
 1562:     if ($rule_in_effect eq 'none') {
 1563:         return [$perlvar{'lonHostID'}];
 1564:     } elsif ($rule_in_effect eq '') {
 1565:         $offloadto = $currtargets;
 1566:     } else {
 1567:         if ($rule_in_effect eq 'homeserver') {
 1568:             my $homeserver = &homeserver($uname,$udom);
 1569:             if ($homeserver ne 'no_host') {
 1570:                 $offloadto = [$homeserver];
 1571:             }
 1572:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1573:             my %domconfig =
 1574:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1575:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1576:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1577:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1578:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1579:                     }
 1580:                 }
 1581:             } else {
 1582:                 my %servers = &internet_dom_servers($udom);
 1583:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1584:                 if (&hostname($remotebalancer) ne '') {
 1585:                     $offloadto = [$remotebalancer];
 1586:                 }
 1587:             }
 1588:         } elsif (&hostname($rule_in_effect) ne '') {
 1589:             $offloadto = [$rule_in_effect];
 1590:         }
 1591:     }
 1592:     return $offloadto;
 1593: }
 1594: 
 1595: sub internet_dom_servers {
 1596:     my ($dom) = @_;
 1597:     my (%uniqservers,%servers);
 1598:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1599:     my @machinedoms = &machine_domains($primaryserver);
 1600:     foreach my $mdom (@machinedoms) {
 1601:         my %currservers = %servers;
 1602:         my %server = &get_servers($mdom);
 1603:         %servers = (%currservers,%server);
 1604:     }
 1605:     my %by_hostname;
 1606:     foreach my $id (keys(%servers)) {
 1607:         push(@{$by_hostname{$servers{$id}}},$id);
 1608:     }
 1609:     foreach my $hostname (sort(keys(%by_hostname))) {
 1610:         if (@{$by_hostname{$hostname}} > 1) {
 1611:             my $match = 0;
 1612:             foreach my $id (@{$by_hostname{$hostname}}) {
 1613:                 if (&host_domain($id) eq $dom) {
 1614:                     $uniqservers{$id} = $hostname;
 1615:                     $match = 1;
 1616:                 }
 1617:             }
 1618:             unless ($match) {
 1619:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1620:             }
 1621:         } else {
 1622:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1623:         }
 1624:     }
 1625:     return %uniqservers;
 1626: }
 1627: 
 1628: sub trusted_domains {
 1629:     my ($cmdtype,$calldom) = @_;
 1630:     my ($trusted,$untrusted);
 1631:     if (&domain($calldom) eq '') {
 1632:         return ($trusted,$untrusted);
 1633:     }
 1634:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1635:         return ($trusted,$untrusted);
 1636:     }
 1637:     my $callprimary = &domain($calldom,'primary');
 1638:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1639:     if ($intcalldom eq '') {
 1640:         return ($trusted,$untrusted);
 1641:     }
 1642: 
 1643:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1644:     unless (defined($cached)) {
 1645:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1646:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1647:         $trustconfig = $domconfig{'trust'};
 1648:     }
 1649:     if (ref($trustconfig)) {
 1650:         my (%possexc,%possinc,@allexc,@allinc); 
 1651:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1652:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1653:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1654:             }
 1655:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1656:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1657:             }
 1658:         }
 1659:         if (keys(%possexc)) {
 1660:             if (keys(%possinc)) {
 1661:                 foreach my $key (sort(keys(%possexc))) {
 1662:                     next if ($key eq $intcalldom);
 1663:                     unless ($possinc{$key}) {
 1664:                         push(@allexc,$key);
 1665:                     }
 1666:                 }
 1667:             } else {
 1668:                 @allexc = sort(keys(%possexc));
 1669:             }
 1670:         }
 1671:         if (keys(%possinc)) {
 1672:             $possinc{$intcalldom} = 1;
 1673:             @allinc = sort(keys(%possinc));
 1674:         }
 1675:         if ((@allexc > 0) || (@allinc > 0)) {
 1676:             my %doms_by_intdom;
 1677:             my %allintdoms = &all_host_intdom();
 1678:             my %alldoms = &all_host_domain();
 1679:             foreach my $key (%allintdoms) {
 1680:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1681:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1682:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1683:                     }
 1684:                 } else {
 1685:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1686:                 }
 1687:             }
 1688:             foreach my $exc (@allexc) {
 1689:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1690:                     $untrusted = $doms_by_intdom{$exc};
 1691:                 }
 1692:             }
 1693:             foreach my $inc (@allinc) {
 1694:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1695:                     $trusted = $doms_by_intdom{$inc};
 1696:                 }
 1697:             }
 1698:         }
 1699:     }
 1700:     return ($trusted,$untrusted);
 1701: }
 1702: 
 1703: sub will_trust {
 1704:     my ($cmdtype,$domain,$possdom) = @_;
 1705:     return 1 if ($domain eq $possdom);
 1706:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1707:     my $willtrust; 
 1708:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1709:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1710:             $willtrust = 1;
 1711:         }
 1712:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1713:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1714:             $willtrust = 1;
 1715:         }
 1716:     } else {
 1717:         $willtrust = 1;
 1718:     }
 1719:     return $willtrust;
 1720: }
 1721: 
 1722: # ---------------------- Find the homebase for a user from domain's lib servers
 1723: 
 1724: my %homecache;
 1725: sub homeserver {
 1726:     my ($uname,$udom,$ignoreBadCache)=@_;
 1727:     my $index="$uname:$udom";
 1728: 
 1729:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1730: 
 1731:     my %servers = &get_servers($udom,'library');
 1732:     foreach my $tryserver (keys(%servers)) {
 1733:         next if ($ignoreBadCache ne 'true' && 
 1734: 		 exists($badServerCache{$tryserver}));
 1735: 
 1736: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1737: 	if ($answer eq 'found') {
 1738: 	    delete($badServerCache{$tryserver}); 
 1739: 	    return $homecache{$index}=$tryserver;
 1740: 	} elsif ($answer eq 'no_host') {
 1741: 	    $badServerCache{$tryserver}=1;
 1742: 	}
 1743:     }    
 1744:     return 'no_host';
 1745: }
 1746: 
 1747: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1748: 
 1749: sub idget {
 1750:     my ($udom,$idsref,$namespace)=@_;
 1751:     my %returnhash=();
 1752:     my @ids=(); 
 1753:     if (ref($idsref) eq 'ARRAY') {
 1754:         @ids = @{$idsref};
 1755:     } else {
 1756:         return %returnhash; 
 1757:     }
 1758:     if ($namespace eq '') {
 1759:         $namespace = 'ids';
 1760:     }
 1761:     
 1762:     my %servers = &get_servers($udom,'library');
 1763:     foreach my $tryserver (keys(%servers)) {
 1764: 	my $idlist=join('&', map { &escape($_); } @ids);
 1765: 	if ($namespace eq 'ids') {
 1766: 	    $idlist=~tr/A-Z/a-z/;
 1767: 	}
 1768: 	my $reply;
 1769: 	if ($namespace eq 'ids') {
 1770: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1771: 	} else {
 1772: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1773: 	}
 1774: 	my @answer=();
 1775: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1776: 	    @answer=split(/\&/,$reply);
 1777: 	}                    ;
 1778: 	my $i;
 1779: 	for ($i=0;$i<=$#ids;$i++) {
 1780: 	    if ($answer[$i]) {
 1781: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1782: 	    }
 1783: 	}
 1784:     }
 1785:     return %returnhash;
 1786: }
 1787: 
 1788: # ------------------------------------- Find the IDs behind a list of usernames
 1789: 
 1790: sub idrget {
 1791:     my ($udom,@unames)=@_;
 1792:     my %returnhash=();
 1793:     foreach my $uname (@unames) {
 1794:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1795:     }
 1796:     return %returnhash;
 1797: }
 1798: 
 1799: # Store away a list of names and associated student/employee IDs or clicker IDs
 1800: 
 1801: sub idput {
 1802:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1803:     my %servers=();
 1804:     my %ids=();
 1805:     my %byid = ();
 1806:     if (ref($idsref) eq 'HASH') {
 1807:         %ids=%{$idsref};
 1808:     }
 1809:     if ($namespace eq '') {
 1810:         $namespace = 'ids'; 
 1811:     }
 1812:     foreach my $uname (keys(%ids)) {
 1813: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1814:         if ($uhom eq '') {
 1815:             $uhom=&homeserver($uname,$udom);
 1816:         }
 1817:         if ($uhom ne 'no_host') {
 1818:             my $esc_unam=&escape($uname);
 1819:             if ($namespace eq 'ids') {
 1820:                 my $id=&escape($ids{$uname});
 1821:                 $id=~tr/A-Z/a-z/;
 1822:                 my $esc_unam=&escape($uname);
 1823:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1824:             } else {
 1825:                 my @currids = split(/,/,$ids{$uname});
 1826:                 foreach my $id (@currids) {
 1827:                     $byid{$uhom}{$id} .= $uname.',';
 1828:                 }
 1829:             }
 1830:         }
 1831:     }
 1832:     if ($namespace eq 'clickers') {
 1833:         foreach my $server (keys(%byid)) {
 1834:             if (ref($byid{$server}) eq 'HASH') {
 1835:                 foreach my $id (keys(%{$byid{$server}})) {
 1836:                     $byid{$server} =~ s/,$//;
 1837:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1838:                 }
 1839:             }
 1840:         }
 1841:     }
 1842:     foreach my $server (keys(%servers)) {
 1843:         $servers{$server} =~ s/\&$//;
 1844:         if ($namespace eq 'ids') {     
 1845:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1846:         } else {
 1847:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1848:         }
 1849:     }
 1850: }
 1851: 
 1852: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1853: 
 1854: sub iddel {
 1855:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1856:     my %result=();
 1857:     my %ids=();
 1858:     my %byid = ();
 1859:     if (ref($idshashref) eq 'HASH') {
 1860:         %ids=%{$idshashref};
 1861:     } else {
 1862:         return %result;
 1863:     }
 1864:     if ($namespace eq '') {
 1865:         $namespace = 'ids';
 1866:     }
 1867:     my %servers=();
 1868:     while (my ($id,$unamestr) = each(%ids)) {
 1869:         if ($namespace eq 'ids') {
 1870:             my $uhom = $uhome;
 1871:             if ($uhom eq '') { 
 1872:                 $uhom=&homeserver($unamestr,$udom);
 1873:             }
 1874:             if ($uhom ne 'no_host') {
 1875:                 $servers{$uhom}.='&'.&escape($id);
 1876:             }
 1877:          } else {
 1878:             my @curritems = split(/,/,$ids{$id});
 1879:             foreach my $uname (@curritems) {
 1880:                 my $uhom = $uhome;
 1881:                 if ($uhom eq '') {
 1882:                     $uhom=&homeserver($uname,$udom);
 1883:                 }
 1884:                 if ($uhom ne 'no_host') { 
 1885:                     $byid{$uhom}{$id} .= $uname.',';
 1886:                 }
 1887:             }
 1888:         }
 1889:     }
 1890:     if ($namespace eq 'clickers') {
 1891:         foreach my $server (keys(%byid)) {
 1892:             if (ref($byid{$server}) eq 'HASH') {
 1893:                 foreach my $id (keys(%{$byid{$server}})) {
 1894:                     $byid{$server}{$id} =~ s/,$//;
 1895:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1896:                 }
 1897:             }
 1898:         }
 1899:     }
 1900:     foreach my $server (keys(%servers)) {
 1901:         $servers{$server} =~ s/\&$//;
 1902:         if ($namespace eq 'ids') {
 1903:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1904:         } elsif ($namespace eq 'clickers') {
 1905:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1906:         }
 1907:     }
 1908:     return %result;
 1909: }
 1910: 
 1911: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1912: 
 1913: sub updateclickers {
 1914:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1915:     my %clickers;
 1916:     if (ref($idshashref) eq 'HASH') {
 1917:         %clickers=%{$idshashref};
 1918:     } else {
 1919:         return;
 1920:     }
 1921:     my $items='';
 1922:     foreach my $item (keys(%clickers)) {
 1923:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1924:     }
 1925:     $items=~s/\&$//;
 1926:     my $request = "updateclickers:$udom:$action:$items";
 1927:     if ($critical) {
 1928:         return &critical($request,$uhome);
 1929:     } else {
 1930:         return &reply($request,$uhome);
 1931:     }
 1932: }
 1933: 
 1934: # ------------------------------dump from db file owned by domainconfig user
 1935: sub dump_dom {
 1936:     my ($namespace, $udom, $regexp) = @_;
 1937: 
 1938:     $udom ||= $env{'user.domain'};
 1939: 
 1940:     return () unless $udom;
 1941: 
 1942:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1943: }
 1944: 
 1945: # ------------------------------------------ get items from domain db files   
 1946: 
 1947: sub get_dom {
 1948:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1949:     return if ($udom eq 'public');
 1950:     my $items='';
 1951:     foreach my $item (@$storearr) {
 1952:         $items.=&escape($item).'&';
 1953:     }
 1954:     $items=~s/\&$//;
 1955:     if (!$udom) {
 1956:         $udom=$env{'user.domain'};
 1957:         return if ($udom eq 'public');
 1958:         if (defined(&domain($udom,'primary'))) {
 1959:             $uhome=&domain($udom,'primary');
 1960:         } else {
 1961:             undef($uhome);
 1962:         }
 1963:     } else {
 1964:         if (!$uhome) {
 1965:             if (defined(&domain($udom,'primary'))) {
 1966:                 $uhome=&domain($udom,'primary');
 1967:             }
 1968:         }
 1969:     }
 1970:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1971:         my $rep;
 1972:         if ($namespace =~ /^enc/) {
 1973:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1974:         } else {
 1975:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1976:         }
 1977:         my %returnhash;
 1978:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1979:             return %returnhash;
 1980:         }
 1981:         my @pairs=split(/\&/,$rep);
 1982:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1983:             return @pairs;
 1984:         }
 1985:         my $i=0;
 1986:         foreach my $item (@$storearr) {
 1987:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1988:             $i++;
 1989:         }
 1990:         return %returnhash;
 1991:     } else {
 1992:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1993:     }
 1994: }
 1995: 
 1996: # -------------------------------------------- put items in domain db files 
 1997: 
 1998: sub put_dom {
 1999:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2000:     if (!$udom) {
 2001:         $udom=$env{'user.domain'};
 2002:         if (defined(&domain($udom,'primary'))) {
 2003:             $uhome=&domain($udom,'primary');
 2004:         } else {
 2005:             undef($uhome);
 2006:         }
 2007:     } else {
 2008:         if (!$uhome) {
 2009:             if (defined(&domain($udom,'primary'))) {
 2010:                 $uhome=&domain($udom,'primary');
 2011:             }
 2012:         }
 2013:     } 
 2014:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2015:         my $items='';
 2016:         foreach my $item (keys(%$storehash)) {
 2017:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2018:         }
 2019:         $items=~s/\&$//;
 2020:         if ($namespace =~ /^enc/) {
 2021:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2022:         } else {
 2023:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2024:         }
 2025:     } else {
 2026:         &logthis("put_dom failed - no homeserver and/or domain");
 2027:     }
 2028: }
 2029: 
 2030: # --------------------- newput for items in db file owned by domainconfig user
 2031: sub newput_dom {
 2032:     my ($namespace,$storehash,$udom) = @_;
 2033:     my $result;
 2034:     if (!$udom) {
 2035:         $udom=$env{'user.domain'};
 2036:     }
 2037:     if ($udom) {
 2038:         my $uname = &get_domainconfiguser($udom);
 2039:         $result = &newput($namespace,$storehash,$udom,$uname);
 2040:     }
 2041:     return $result;
 2042: }
 2043: 
 2044: # --------------------- delete for items in db file owned by domainconfig user
 2045: sub del_dom {
 2046:     my ($namespace,$storearr,$udom)=@_;
 2047:     if (ref($storearr) eq 'ARRAY') {
 2048:         if (!$udom) {
 2049:             $udom=$env{'user.domain'};
 2050:         }
 2051:         if ($udom) {
 2052:             my $uname = &get_domainconfiguser($udom); 
 2053:             return &del($namespace,$storearr,$udom,$uname);
 2054:         }
 2055:     }
 2056: }
 2057: 
 2058: # ----------------------------------construct domainconfig user for a domain 
 2059: sub get_domainconfiguser {
 2060:     my ($udom) = @_;
 2061:     return $udom.'-domainconfig';
 2062: }
 2063: 
 2064: sub retrieve_inst_usertypes {
 2065:     my ($udom) = @_;
 2066:     my (%returnhash,@order);
 2067:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2068:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2069:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2070:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2071:     } else {
 2072:         if (defined(&domain($udom,'primary'))) {
 2073:             my $uhome=&domain($udom,'primary');
 2074:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2075:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2076:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2077:                 return (\%returnhash,\@order);
 2078:             }
 2079:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2080:             my @pairs=split(/\&/,$hashitems);
 2081:             foreach my $item (@pairs) {
 2082:                 my ($key,$value)=split(/=/,$item,2);
 2083:                 $key = &unescape($key);
 2084:                 next if ($key =~ /^error: 2 /);
 2085:                 $returnhash{$key}=&thaw_unescape($value);
 2086:             }
 2087:             my @esc_order = split(/\&/,$orderitems);
 2088:             foreach my $item (@esc_order) {
 2089:                 push(@order,&unescape($item));
 2090:             }
 2091:         } else {
 2092:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2093:         }
 2094:         return (\%returnhash,\@order);
 2095:     }
 2096: }
 2097: 
 2098: sub is_domainimage {
 2099:     my ($url) = @_;
 2100:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2101:         if (&domain($1) ne '') {
 2102:             return '1';
 2103:         }
 2104:     }
 2105:     return;
 2106: }
 2107: 
 2108: sub inst_directory_query {
 2109:     my ($srch) = @_;
 2110:     my $udom = $srch->{'srchdomain'};
 2111:     my %results;
 2112:     my $homeserver = &domain($udom,'primary');
 2113:     my $outcome;
 2114:     if ($homeserver ne '') {
 2115:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2116:             if ($srch->{'srchby'} eq 'email') {
 2117:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2118:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2119:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2120:                     (($major == 2) && ($minor < 12))) {
 2121:                     return;
 2122:                 }
 2123:             }
 2124:         }
 2125: 	my $queryid=&reply("querysend:instdirsearch:".
 2126: 			   &escape($srch->{'srchby'}).':'.
 2127: 			   &escape($srch->{'srchterm'}).':'.
 2128: 			   &escape($srch->{'srchtype'}),$homeserver);
 2129: 	my $host=&hostname($homeserver);
 2130: 	if ($queryid !~/^\Q$host\E\_/) {
 2131: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2132: 	    return;
 2133: 	}
 2134: 	my $response = &get_query_reply($queryid);
 2135: 	my $maxtries = 5;
 2136: 	my $tries = 1;
 2137: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2138: 	    $response = &get_query_reply($queryid);
 2139: 	    $tries ++;
 2140: 	}
 2141: 
 2142:         if (!&error($response) && $response ne 'refused') {
 2143:             if ($response eq 'unavailable') {
 2144:                 $outcome = $response;
 2145:             } else {
 2146:                 $outcome = 'ok';
 2147:                 my @matches = split(/\n/,$response);
 2148:                 foreach my $match (@matches) {
 2149:                     my ($key,$value) = split(/=/,$match);
 2150:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2151:                 }
 2152:             }
 2153:         }
 2154:     }
 2155:     return ($outcome,%results);
 2156: }
 2157: 
 2158: sub usersearch {
 2159:     my ($srch) = @_;
 2160:     my $dom = $srch->{'srchdomain'};
 2161:     my %results;
 2162:     my %libserv = &all_library();
 2163:     my $query = 'usersearch';
 2164:     foreach my $tryserver (keys(%libserv)) {
 2165:         if (&host_domain($tryserver) eq $dom) {
 2166:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2167:                 if ($srch->{'srchby'} eq 'email') {
 2168:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2169:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2170:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2171:                              (($major == 2) && ($minor < 12)));
 2172:                 }
 2173:             }
 2174:             my $host=&hostname($tryserver);
 2175:             my $queryid=
 2176:                 &reply("querysend:".&escape($query).':'.
 2177:                        &escape($srch->{'srchby'}).':'.
 2178:                        &escape($srch->{'srchtype'}).':'.
 2179:                        &escape($srch->{'srchterm'}),$tryserver);
 2180:             if ($queryid !~/^\Q$host\E\_/) {
 2181:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2182:                 next;
 2183:             }
 2184:             my $reply = &get_query_reply($queryid);
 2185:             my $maxtries = 1;
 2186:             my $tries = 1;
 2187:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2188:                 $reply = &get_query_reply($queryid);
 2189:                 $tries ++;
 2190:             }
 2191:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2192:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2193:             } else {
 2194:                 my @matches;
 2195:                 if ($reply =~ /\n/) {
 2196:                     @matches = split(/\n/,$reply);
 2197:                 } else {
 2198:                     @matches = split(/\&/,$reply);
 2199:                 }
 2200:                 foreach my $match (@matches) {
 2201:                     my ($uname,$udom,%userhash);
 2202:                     foreach my $entry (split(/:/,$match)) {
 2203:                         my ($key,$value) =
 2204:                             map {&unescape($_);} split(/=/,$entry);
 2205:                         $userhash{$key} = $value;
 2206:                         if ($key eq 'username') {
 2207:                             $uname = $value;
 2208:                         } elsif ($key eq 'domain') {
 2209:                             $udom = $value;
 2210:                         }
 2211:                     }
 2212:                     $results{$uname.':'.$udom} = \%userhash;
 2213:                 }
 2214:             }
 2215:         }
 2216:     }
 2217:     return %results;
 2218: }
 2219: 
 2220: sub get_instuser {
 2221:     my ($udom,$uname,$id) = @_;
 2222:     my $homeserver = &domain($udom,'primary');
 2223:     my ($outcome,%results);
 2224:     if ($homeserver ne '') {
 2225:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2226:                            &escape($id).':'.&escape($udom),$homeserver);
 2227:         my $host=&hostname($homeserver);
 2228:         if ($queryid !~/^\Q$host\E\_/) {
 2229:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2230:             return;
 2231:         }
 2232:         my $response = &get_query_reply($queryid);
 2233:         my $maxtries = 5;
 2234:         my $tries = 1;
 2235:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2236:             $response = &get_query_reply($queryid);
 2237:             $tries ++;
 2238:         }
 2239:         if (!&error($response) && $response ne 'refused') {
 2240:             if ($response eq 'unavailable') {
 2241:                 $outcome = $response;
 2242:             } else {
 2243:                 $outcome = 'ok';
 2244:                 my @matches = split(/\n/,$response);
 2245:                 foreach my $match (@matches) {
 2246:                     my ($key,$value) = split(/=/,$match);
 2247:                     $results{&unescape($key)} = &thaw_unescape($value);
 2248:                 }
 2249:             }
 2250:         }
 2251:     }
 2252:     my %userinfo;
 2253:     if (ref($results{$uname}) eq 'HASH') {
 2254:         %userinfo = %{$results{$uname}};
 2255:     } 
 2256:     return ($outcome,%userinfo);
 2257: }
 2258: 
 2259: sub get_multiple_instusers {
 2260:     my ($udom,$users,$caller) = @_;
 2261:     my ($outcome,$results);
 2262:     if (ref($users) eq 'HASH') {
 2263:         my $count = keys(%{$users}); 
 2264:         my $requested = &freeze_escape($users);
 2265:         my $homeserver = &domain($udom,'primary');
 2266:         if ($homeserver ne '') {
 2267:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2268:             my $host=&hostname($homeserver);
 2269:             if ($queryid !~/^\Q$host\E\_/) {
 2270:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2271:                          ' for host: '.$homeserver.'in domain '.$udom);
 2272:                 return ($outcome,$results);
 2273:             }
 2274:             my $response = &get_query_reply($queryid);
 2275:             my $maxtries = 5;
 2276:             if ($count > 100) {
 2277:                 $maxtries = 1+int($count/20);
 2278:             }
 2279:             my $tries = 1;
 2280:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2281:                 $response = &get_query_reply($queryid);
 2282:                 $tries ++;
 2283:             }
 2284:             if ($response eq '') {
 2285:                 $results = {};
 2286:                 foreach my $key (keys(%{$users})) {
 2287:                     my ($uname,$id);
 2288:                     if ($caller eq 'id') {
 2289:                         $id = $key;
 2290:                     } else {
 2291:                         $uname = $key;
 2292:                     }
 2293:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2294:                     $outcome = $resp;
 2295:                     if ($resp eq 'ok') {
 2296:                         %{$results} = (%{$results}, %info);
 2297:                     } else {
 2298:                         last;
 2299:                     }
 2300:                 }
 2301:             } elsif(!&error($response) && ($response ne 'refused')) {
 2302:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2303:                     $outcome = $response;
 2304:                 } else {
 2305:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2306:                     if ($outcome eq 'ok') {
 2307:                         $results = &thaw_unescape($userdata); 
 2308:                     }
 2309:                 }
 2310:             }
 2311:         }
 2312:     }
 2313:     return ($outcome,$results);
 2314: }
 2315: 
 2316: sub inst_rulecheck {
 2317:     my ($udom,$uname,$id,$item,$rules) = @_;
 2318:     my %returnhash;
 2319:     if ($udom ne '') {
 2320:         if (ref($rules) eq 'ARRAY') {
 2321:             @{$rules} = map {&escape($_);} (@{$rules});
 2322:             my $rulestr = join(':',@{$rules});
 2323:             my $homeserver=&domain($udom,'primary');
 2324:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2325:                 my $response;
 2326:                 if ($item eq 'username') {                
 2327:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2328:                                               ':'.&escape($uname).':'.$rulestr,
 2329:                                               $homeserver));
 2330:                 } elsif ($item eq 'id') {
 2331:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2332:                                               ':'.&escape($id).':'.$rulestr,
 2333:                                               $homeserver));
 2334:                 } elsif ($item eq 'selfcreate') {
 2335:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2336:                                                &escape($udom).':'.&escape($uname).
 2337:                                               ':'.$rulestr,$homeserver));
 2338:                 }
 2339:                 if ($response ne 'refused') {
 2340:                     my @pairs=split(/\&/,$response);
 2341:                     foreach my $item (@pairs) {
 2342:                         my ($key,$value)=split(/=/,$item,2);
 2343:                         $key = &unescape($key);
 2344:                         next if ($key =~ /^error: 2 /);
 2345:                         $returnhash{$key}=&thaw_unescape($value);
 2346:                     }
 2347:                 }
 2348:             }
 2349:         }
 2350:     }
 2351:     return %returnhash;
 2352: }
 2353: 
 2354: sub inst_userrules {
 2355:     my ($udom,$check) = @_;
 2356:     my (%ruleshash,@ruleorder);
 2357:     if ($udom ne '') {
 2358:         my $homeserver=&domain($udom,'primary');
 2359:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2360:             my $response;
 2361:             if ($check eq 'id') {
 2362:                 $response=&reply('instidrules:'.&escape($udom),
 2363:                                  $homeserver);
 2364:             } elsif ($check eq 'email') {
 2365:                 $response=&reply('instemailrules:'.&escape($udom),
 2366:                                  $homeserver);
 2367:             } else {
 2368:                 $response=&reply('instuserrules:'.&escape($udom),
 2369:                                  $homeserver);
 2370:             }
 2371:             if (($response ne 'refused') && ($response ne 'error') && 
 2372:                 ($response ne 'unknown_cmd') && 
 2373:                 ($response ne 'no_such_host')) {
 2374:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2375:                 my @pairs=split(/\&/,$hashitems);
 2376:                 foreach my $item (@pairs) {
 2377:                     my ($key,$value)=split(/=/,$item,2);
 2378:                     $key = &unescape($key);
 2379:                     next if ($key =~ /^error: 2 /);
 2380:                     $ruleshash{$key}=&thaw_unescape($value);
 2381:                 }
 2382:                 my @esc_order = split(/\&/,$orderitems);
 2383:                 foreach my $item (@esc_order) {
 2384:                     push(@ruleorder,&unescape($item));
 2385:                 }
 2386:             }
 2387:         }
 2388:     }
 2389:     return (\%ruleshash,\@ruleorder);
 2390: }
 2391: 
 2392: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2393: 
 2394: sub get_domain_defaults {
 2395:     my ($domain,$ignore_cache) = @_;
 2396:     return if (($domain eq '') || ($domain eq 'public'));
 2397:     my $cachetime = 60*60*24;
 2398:     unless ($ignore_cache) {
 2399:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2400:         if (defined($cached)) {
 2401:             if (ref($result) eq 'HASH') {
 2402:                 return %{$result};
 2403:             }
 2404:         }
 2405:     }
 2406:     my %domdefaults;
 2407:     my %domconfig =
 2408:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2409:                                   'requestcourses','inststatus',
 2410:                                   'coursedefaults','usersessions',
 2411:                                   'requestauthor','selfenrollment',
 2412:                                   'coursecategories','ssl','autoenroll',
 2413:                                   'trust','helpsettings'],$domain);
 2414:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2415:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2416:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2417:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2418:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2419:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2420:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2421:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2422:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2423:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2424:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2425:     } else {
 2426:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2427:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2428:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2429:     }
 2430:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2431:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2432:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2433:         } else {
 2434:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2435:         }
 2436:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2437:         foreach my $item (@usertools) {
 2438:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2439:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2440:             }
 2441:         }
 2442:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2443:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2444:         }
 2445:     }
 2446:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2447:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2448:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2449:         }
 2450:     }
 2451:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2452:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2453:     }
 2454:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2455:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2456:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2457:         }
 2458:     }
 2459:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2460:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2461:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2462:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2463:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2464:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2465:         }
 2466:         foreach my $type (@coursetypes) {
 2467:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2468:                 unless ($type eq 'community') {
 2469:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2470:                 }
 2471:             }
 2472:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2473:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2474:             }
 2475:             if ($domdefaults{'postsubmit'} eq 'on') {
 2476:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2477:                     $domdefaults{$type.'postsubtimeout'} = 
 2478:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2479:                 }
 2480:             }
 2481:         }
 2482:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2483:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2484:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2485:                 if (@clonecodes) {
 2486:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2487:                 }
 2488:             }
 2489:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2490:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2491:         }
 2492:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2493:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2494:         } 
 2495:     }
 2496:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2497:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2498:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2499:         }
 2500:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2501:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2502:         }
 2503:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2504:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2505:         }
 2506:     }
 2507:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2508:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2509:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2510:                             'approval','limit');
 2511:             foreach my $type (@coursetypes) {
 2512:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2513:                     my @mgrdc = ();
 2514:                     foreach my $item (@settings) {
 2515:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2516:                             push(@mgrdc,$item);
 2517:                         }
 2518:                     }
 2519:                     if (@mgrdc) {
 2520:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2521:                     }
 2522:                 }
 2523:             }
 2524:         }
 2525:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2526:             foreach my $type (@coursetypes) {
 2527:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2528:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2529:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2530:                     }
 2531:                 }
 2532:             }
 2533:         }
 2534:     }
 2535:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2536:         $domdefaults{'catauth'} = 'std';
 2537:         $domdefaults{'catunauth'} = 'std';
 2538:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2539:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2540:         }
 2541:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2542:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2543:         }
 2544:     }
 2545:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2546:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2547:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2548:         }
 2549:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2550:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2551:         }
 2552:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2553:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2554:         }
 2555:     }
 2556:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2557:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2558:         foreach my $prefix (@prefixes) {
 2559:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2560:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2561:             }
 2562:         }
 2563:     }
 2564:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2565:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2566:     }
 2567:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2568:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2569:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2570:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2571:         }
 2572:     }
 2573:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2574:     return %domdefaults;
 2575: }
 2576: 
 2577: sub course_portal_url {
 2578:     my ($cnum,$cdom) = @_;
 2579:     my $chome = &homeserver($cnum,$cdom);
 2580:     my $hostname = &hostname($chome);
 2581:     my $protocol = $protocol{$chome};
 2582:     $protocol = 'http' if ($protocol ne 'https');
 2583:     my %domdefaults = &get_domain_defaults($cdom);
 2584:     my $firsturl;
 2585:     if ($domdefaults{'portal_def'}) {
 2586:         $firsturl = $domdefaults{'portal_def'};
 2587:     } else {
 2588:         $firsturl = $protocol.'://'.$hostname;
 2589:     }
 2590:     return $firsturl;
 2591: }
 2592: 
 2593: # --------------------------------------------------- Assign a key to a student
 2594: 
 2595: sub assign_access_key {
 2596: #
 2597: # a valid key looks like uname:udom#comments
 2598: # comments are being appended
 2599: #
 2600:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2601:     $kdom=
 2602:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2603:     $knum=
 2604:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2605:     $cdom=
 2606:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2607:     $cnum=
 2608:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2609:     $udom=$env{'user.name'} unless (defined($udom));
 2610:     $uname=$env{'user.domain'} unless (defined($uname));
 2611:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2612:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2613:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2614:                                                   # assigned to this person
 2615:                                                   # - this should not happen,
 2616:                                                   # unless something went wrong
 2617:                                                   # the first time around
 2618: # ready to assign
 2619:         $logentry=$1.'; '.$logentry;
 2620:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2621:                                                  $kdom,$knum) eq 'ok') {
 2622: # key now belongs to user
 2623: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2624:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2625:                 &appenv({'environment.'.$envkey => $ckey});
 2626:                 return 'ok';
 2627:             } else {
 2628:                 return 
 2629:   'error: Count not permanently assign key, will need to be re-entered later.';
 2630: 	    }
 2631:         } else {
 2632:             return 'error: Could not assign key, try again later.';
 2633:         }
 2634:     } elsif (!$existing{$ckey}) {
 2635: # the key does not exist
 2636: 	return 'error: The key does not exist';
 2637:     } else {
 2638: # the key is somebody else's
 2639: 	return 'error: The key is already in use';
 2640:     }
 2641: }
 2642: 
 2643: # ------------------------------------------ put an additional comment on a key
 2644: 
 2645: sub comment_access_key {
 2646: #
 2647: # a valid key looks like uname:udom#comments
 2648: # comments are being appended
 2649: #
 2650:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2651:     $cdom=
 2652:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2653:     $cnum=
 2654:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2655:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2656:     if ($existing{$ckey}) {
 2657:         $existing{$ckey}.='; '.$logentry;
 2658: # ready to assign
 2659:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2660:                                                  $cdom,$cnum) eq 'ok') {
 2661: 	    return 'ok';
 2662:         } else {
 2663: 	    return 'error: Count not store comment.';
 2664:         }
 2665:     } else {
 2666: # the key does not exist
 2667: 	return 'error: The key does not exist';
 2668:     }
 2669: }
 2670: 
 2671: # ------------------------------------------------------ Generate a set of keys
 2672: 
 2673: sub generate_access_keys {
 2674:     my ($number,$cdom,$cnum,$logentry)=@_;
 2675:     $cdom=
 2676:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2677:     $cnum=
 2678:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2679:     unless (&allowed('mky',$cdom)) { return 0; }
 2680:     unless (($cdom) && ($cnum)) { return 0; }
 2681:     if ($number>10000) { return 0; }
 2682:     sleep(2); # make sure don't get same seed twice
 2683:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2684:     my $total=0;
 2685:     for (my $i=1;$i<=$number;$i++) {
 2686:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2687:                   sprintf("%lx",int(100000*rand)).'-'.
 2688:                   sprintf("%lx",int(100000*rand));
 2689:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2690:        $newkey=~s/0/h/g; # and also 0 and O
 2691:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2692:        if ($existing{$newkey}) {
 2693:            $i--;
 2694:        } else {
 2695: 	  if (&put('accesskeys',
 2696:               { $newkey => '# generated '.localtime().
 2697:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2698:                            '; '.$logentry },
 2699: 		   $cdom,$cnum) eq 'ok') {
 2700:               $total++;
 2701: 	  }
 2702:        }
 2703:     }
 2704:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2705:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2706:     return $total;
 2707: }
 2708: 
 2709: # ------------------------------------------------------- Validate an accesskey
 2710: 
 2711: sub validate_access_key {
 2712:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2713:     $cdom=
 2714:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2715:     $cnum=
 2716:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2717:     $udom=$env{'user.domain'} unless (defined($udom));
 2718:     $uname=$env{'user.name'} unless (defined($uname));
 2719:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2720:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2721: }
 2722: 
 2723: # ------------------------------------- Find the section of student in a course
 2724: sub devalidate_getsection_cache {
 2725:     my ($udom,$unam,$courseid)=@_;
 2726:     my $hashid="$udom:$unam:$courseid";
 2727:     &devalidate_cache_new('getsection',$hashid);
 2728: }
 2729: 
 2730: sub courseid_to_courseurl {
 2731:     my ($courseid) = @_;
 2732:     #already url style courseid
 2733:     return $courseid if ($courseid =~ m{^/});
 2734: 
 2735:     if (exists($env{'course.'.$courseid.'.num'})) {
 2736: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2737: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2738: 	return "/$cdom/$cnum";
 2739:     }
 2740: 
 2741:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2742:     if (exists($courseinfo{'num'})) {
 2743: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2744:     }
 2745: 
 2746:     return undef;
 2747: }
 2748: 
 2749: sub getsection {
 2750:     my ($udom,$unam,$courseid)=@_;
 2751:     my $cachetime=1800;
 2752: 
 2753:     my $hashid="$udom:$unam:$courseid";
 2754:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2755:     if (defined($cached)) { return $result; }
 2756: 
 2757:     my %Pending; 
 2758:     my %Expired;
 2759:     #
 2760:     # Each role can either have not started yet (pending), be active, 
 2761:     #    or have expired.
 2762:     #
 2763:     # If there is an active role, we are done.
 2764:     #
 2765:     # If there is more than one role which has not started yet, 
 2766:     #     choose the one which will start sooner
 2767:     # If there is one role which has not started yet, return it.
 2768:     #
 2769:     # If there is more than one expired role, choose the one which ended last.
 2770:     # If there is a role which has expired, return it.
 2771:     #
 2772:     $courseid = &courseid_to_courseurl($courseid);
 2773:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2774:     foreach my $key (keys(%roleshash)) {
 2775:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2776:         my $section=$1;
 2777:         if ($key eq $courseid.'_st') { $section=''; }
 2778:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2779:         my $now=time;
 2780:         if (defined($end) && $end && ($now > $end)) {
 2781:             $Expired{$end}=$section;
 2782:             next;
 2783:         }
 2784:         if (defined($start) && $start && ($now < $start)) {
 2785:             $Pending{$start}=$section;
 2786:             next;
 2787:         }
 2788:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2789:     }
 2790:     #
 2791:     # Presumedly there will be few matching roles from the above
 2792:     # loop and the sorting time will be negligible.
 2793:     if (scalar(keys(%Pending))) {
 2794:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2795:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2796:     } 
 2797:     if (scalar(keys(%Expired))) {
 2798:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2799:         my $time = pop(@sorted);
 2800:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2801:     }
 2802:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2803: }
 2804: 
 2805: sub save_cache {
 2806:     &purge_remembered();
 2807:     #&Apache::loncommon::validate_page();
 2808:     undef(%env);
 2809:     undef($env_loaded);
 2810: }
 2811: 
 2812: my $to_remember=-1;
 2813: my %remembered;
 2814: my %accessed;
 2815: my $kicks=0;
 2816: my $hits=0;
 2817: sub make_key {
 2818:     my ($name,$id) = @_;
 2819:     if (length($id) > 65 
 2820: 	&& length(&escape($id)) > 200) {
 2821: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2822:     }
 2823:     return &escape($name.':'.$id);
 2824: }
 2825: 
 2826: sub devalidate_cache_new {
 2827:     my ($name,$id,$debug) = @_;
 2828:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2829:     my $remembered_id=$name.':'.$id;
 2830:     $id=&make_key($name,$id);
 2831:     $memcache->delete($id);
 2832:     delete($remembered{$remembered_id});
 2833:     delete($accessed{$remembered_id});
 2834: }
 2835: 
 2836: sub is_cached_new {
 2837:     my ($name,$id,$debug) = @_;
 2838:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2839:     if (exists($remembered{$remembered_id})) {
 2840: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2841: 	$accessed{$remembered_id}=[&gettimeofday()];
 2842: 	$hits++;
 2843: 	return ($remembered{$remembered_id},1);
 2844:     }
 2845:     $id=&make_key($name,$id);
 2846:     my $value = $memcache->get($id);
 2847:     if (!(defined($value))) {
 2848: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2849: 	return (undef,undef);
 2850:     }
 2851:     if ($value eq '__undef__') {
 2852: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2853: 	$value=undef;
 2854:     }
 2855:     &make_room($remembered_id,$value,$debug);
 2856:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2857:     return ($value,1);
 2858: }
 2859: 
 2860: sub do_cache_new {
 2861:     my ($name,$id,$value,$time,$debug) = @_;
 2862:     my $remembered_id=$name.':'.$id;
 2863:     $id=&make_key($name,$id);
 2864:     my $setvalue=$value;
 2865:     if (!defined($setvalue)) {
 2866: 	$setvalue='__undef__';
 2867:     }
 2868:     if (!defined($time) ) {
 2869: 	$time=600;
 2870:     }
 2871:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2872:     my $result = $memcache->set($id,$setvalue,$time);
 2873:     if (! $result) {
 2874: 	&logthis("caching of id -> $id  failed");
 2875: 	$memcache->disconnect_all();
 2876:     }
 2877:     # need to make a copy of $value
 2878:     &make_room($remembered_id,$value,$debug);
 2879:     return $value;
 2880: }
 2881: 
 2882: sub make_room {
 2883:     my ($remembered_id,$value,$debug)=@_;
 2884: 
 2885:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2886:                                     : $value;
 2887:     if ($to_remember<0) { return; }
 2888:     $accessed{$remembered_id}=[&gettimeofday()];
 2889:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2890:     my $to_kick;
 2891:     my $max_time=0;
 2892:     foreach my $other (keys(%accessed)) {
 2893: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2894: 	    $to_kick=$other;
 2895: 	    $max_time=&tv_interval($accessed{$other});
 2896: 	}
 2897:     }
 2898:     delete($remembered{$to_kick});
 2899:     delete($accessed{$to_kick});
 2900:     $kicks++;
 2901:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2902:     return;
 2903: }
 2904: 
 2905: sub purge_remembered {
 2906:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2907:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2908:     undef(%remembered);
 2909:     undef(%accessed);
 2910: }
 2911: # ------------------------------------- Read an entry from a user's environment
 2912: 
 2913: sub userenvironment {
 2914:     my ($udom,$unam,@what)=@_;
 2915:     my $items;
 2916:     foreach my $item (@what) {
 2917:         $items.=&escape($item).'&';
 2918:     }
 2919:     $items=~s/\&$//;
 2920:     my %returnhash=();
 2921:     my $uhome = &homeserver($unam,$udom);
 2922:     unless ($uhome eq 'no_host') {
 2923:         my @answer=split(/\&/, 
 2924:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2925:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2926:             return %returnhash;
 2927:         }
 2928:         my $i;
 2929:         for ($i=0;$i<=$#what;$i++) {
 2930: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2931:         }
 2932:     }
 2933:     return %returnhash;
 2934: }
 2935: 
 2936: # ---------------------------------------------------------- Get a studentphoto
 2937: sub studentphoto {
 2938:     my ($udom,$unam,$ext) = @_;
 2939:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2940:     if (defined($env{'request.course.id'})) {
 2941:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2942:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2943:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2944:             } else {
 2945:                 my ($result,$perm_reqd)=
 2946: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2947:                 if ($result eq 'ok') {
 2948:                     if (!($perm_reqd eq 'yes')) {
 2949:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2950:                     }
 2951:                 }
 2952:             }
 2953:         }
 2954:     } else {
 2955:         my ($result,$perm_reqd) = 
 2956: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2957:         if ($result eq 'ok') {
 2958:             if (!($perm_reqd eq 'yes')) {
 2959:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2960:             }
 2961:         }
 2962:     }
 2963:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2964: }
 2965: 
 2966: sub retrievestudentphoto {
 2967:     my ($udom,$unam,$ext,$type) = @_;
 2968:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2969:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2970:     if ($ret eq 'ok') {
 2971:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2972:         if ($type eq 'thumbnail') {
 2973:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2974:         }
 2975:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2976:         return $tokenurl;
 2977:     } else {
 2978:         if ($type eq 'thumbnail') {
 2979:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2980:         } else { 
 2981:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2982:         }
 2983:     }
 2984: }
 2985: 
 2986: # -------------------------------------------------------------------- New chat
 2987: 
 2988: sub chatsend {
 2989:     my ($newentry,$anon,$group)=@_;
 2990:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2991:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2992:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2993:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2994: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2995: 		   &escape($newentry)).':'.$group,$chome);
 2996: }
 2997: 
 2998: # ------------------------------------------ Find current version of a resource
 2999: 
 3000: sub getversion {
 3001:     my $fname=&clutter(shift);
 3002:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3003:     return &currentversion(&filelocation('',$fname));
 3004: }
 3005: 
 3006: sub currentversion {
 3007:     my $fname=shift;
 3008:     my $author=$fname;
 3009:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3010:     my ($udom,$uname)=split(/\//,$author);
 3011:     my $home=&homeserver($uname,$udom);
 3012:     if ($home eq 'no_host') { 
 3013:         return -1; 
 3014:     }
 3015:     my $answer=&reply("currentversion:$fname",$home);
 3016:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3017: 	return -1;
 3018:     }
 3019:     return $answer;
 3020: }
 3021: 
 3022: #
 3023: # Return special version number of resource if set by override, empty otherwise
 3024: #
 3025: sub usedversion {
 3026:     my $fname=shift;
 3027:     unless ($fname) { $fname=$env{'request.uri'}; }
 3028:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3029:     if ($urlversion) { return $urlversion; }
 3030:     return '';
 3031: }
 3032: 
 3033: # ----------------------------- Subscribe to a resource, return URL if possible
 3034: 
 3035: sub subscribe {
 3036:     my $fname=shift;
 3037:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3038:     $fname=~s/[\n\r]//g;
 3039:     my $author=$fname;
 3040:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3041:     my ($udom,$uname)=split(/\//,$author);
 3042:     my $home=homeserver($uname,$udom);
 3043:     if ($home eq 'no_host') {
 3044:         return 'not_found';
 3045:     }
 3046:     my $answer=reply("sub:$fname",$home);
 3047:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3048: 	$answer.=' by '.$home;
 3049:     }
 3050:     return $answer;
 3051: }
 3052:     
 3053: # -------------------------------------------------------------- Replicate file
 3054: 
 3055: sub repcopy {
 3056:     my $filename=shift;
 3057:     $filename=~s/\/+/\//g;
 3058:     my $londocroot = $perlvar{'lonDocRoot'};
 3059:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3060:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3061:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3062: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3063: 	return &repcopy_userfile($filename);
 3064:     }
 3065:     $filename=~s/[\n\r]//g;
 3066:     my $transname="$filename.in.transfer";
 3067: # FIXME: this should flock
 3068:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3069:     my $remoteurl=subscribe($filename);
 3070:     if ($remoteurl =~ /^con_lost by/) {
 3071: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3072:            return 'unavailable';
 3073:     } elsif ($remoteurl eq 'not_found') {
 3074: 	   #&logthis("Subscribe returned not_found: $filename");
 3075: 	   return 'not_found';
 3076:     } elsif ($remoteurl =~ /^rejected by/) {
 3077: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3078:            return 'forbidden';
 3079:     } elsif ($remoteurl eq 'directory') {
 3080:            return 'ok';
 3081:     } else {
 3082:         my $author=$filename;
 3083:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3084:         my ($udom,$uname)=split(/\//,$author);
 3085:         my $home=homeserver($uname,$udom);
 3086:         unless ($home eq $perlvar{'lonHostID'}) {
 3087:            my @parts=split(/\//,$filename);
 3088:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3089:            if ($path ne "$londocroot/res") {
 3090:                &logthis("Malconfiguration for replication: $filename");
 3091: 	       return 'bad_request';
 3092:            }
 3093:            my $count;
 3094:            for ($count=5;$count<$#parts;$count++) {
 3095:                $path.="/$parts[$count]";
 3096:                if ((-e $path)!=1) {
 3097: 		   mkdir($path,0777);
 3098:                }
 3099:            }
 3100:            my $request=new HTTP::Request('GET',"$remoteurl");
 3101:            my $response;
 3102:            if ($remoteurl =~ m{/raw/}) {
 3103:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3104:            } else {
 3105:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3106:            }
 3107:            if ($response->is_error()) {
 3108: 	       unlink($transname);
 3109:                my $message=$response->status_line;
 3110:                &logthis("<font color=\"blue\">WARNING:"
 3111:                        ." LWP get: $message: $filename</font>");
 3112:                return 'unavailable';
 3113:            } else {
 3114: 	       if ($remoteurl!~/\.meta$/) {
 3115:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3116:                   my $mresponse;
 3117:                   if ($remoteurl =~ m{/raw/}) {
 3118:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3119:                   } else {
 3120:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3121:                   }
 3122:                   if ($mresponse->is_error()) {
 3123: 		      unlink($filename.'.meta');
 3124:                       &logthis(
 3125:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3126:                   }
 3127: 	       }
 3128:                rename($transname,$filename);
 3129:                return 'ok';
 3130:            }
 3131:        }
 3132:     }
 3133: }
 3134: 
 3135: # ------------------------------------------------ Get server side include body
 3136: sub ssi_body {
 3137:     my ($filelink,%form)=@_;
 3138:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3139:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3140:     }
 3141:     my $output='';
 3142:     my $response;
 3143:     if ($filelink=~/^https?\:/) {
 3144:        ($output,$response)=&externalssi($filelink);
 3145:     } else {
 3146:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3147:        $filelink .= 'inhibitmenu=yes';
 3148:        ($output,$response)=&ssi($filelink,%form);
 3149:     }
 3150:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3151:     $output=~s/^.*?\<body[^\>]*\>//si;
 3152:     $output=~s/\<\/body\s*\>.*?$//si;
 3153:     if (wantarray) {
 3154:         return ($output, $response);
 3155:     } else {
 3156:         return $output;
 3157:     }
 3158: }
 3159: 
 3160: # --------------------------------------------------------- Server Side Include
 3161: 
 3162: sub absolute_url {
 3163:     my ($host_name) = @_;
 3164:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3165:     if ($host_name eq '') {
 3166: 	$host_name = $ENV{'SERVER_NAME'};
 3167:     }
 3168:     return $protocol.$host_name;
 3169: }
 3170: 
 3171: #
 3172: #   Server side include.
 3173: # Parameters:
 3174: #  fn     Possibly encrypted resource name/id.
 3175: #  form   Hash that describes how the rendering should be done
 3176: #         and other things.
 3177: # Returns:
 3178: #   Scalar context: The content of the response.
 3179: #   Array context:  2 element list of the content and the full response object.
 3180: #     
 3181: sub ssi {
 3182: 
 3183:     my ($fn,%form)=@_;
 3184:     my $request;
 3185: 
 3186:     $form{'no_update_last_known'}=1;
 3187:     &Apache::lonenc::check_encrypt(\$fn);
 3188:     if (%form) {
 3189:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3190:       $request->content(join('&',map { 
 3191:             my $name = escape($_);
 3192:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3193:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3194:             : &escape($form{$_}) );    
 3195:         } keys(%form)));
 3196:     } else {
 3197:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3198:     }
 3199: 
 3200:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3201:     my $lonhost = $perlvar{'lonHostID'};
 3202:     my $islocal;
 3203:     if (($env{'request.course.id'}) &&
 3204:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3205:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3206:         ($form{'grade_symb'} ne '') &&
 3207:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3208:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3209:         $islocal = 1;
 3210:     }
 3211:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3212:                                                 '','','',$islocal);
 3213: 
 3214:     if (wantarray) {
 3215: 	return ($response->content, $response);
 3216:     } else {
 3217: 	return $response->content;
 3218:     }
 3219: }
 3220: 
 3221: sub externalssi {
 3222:     my ($url)=@_;
 3223:     my $request=new HTTP::Request('GET',$url);
 3224:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3225:     if (wantarray) {
 3226:         return ($response->content, $response);
 3227:     } else {
 3228:         return $response->content;
 3229:     }
 3230: }
 3231: 
 3232: 
 3233: # If the local copy of a replicated resource is outdated, trigger a  
 3234: # connection from the homeserver to flush the delayed queue. If no update 
 3235: # happens, remove local copies of outdated resource (and corresponding
 3236: # metadata file).
 3237: 
 3238: sub remove_stale_resfile {
 3239:     my ($url) = @_;
 3240:     my $removed;
 3241:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3242:         my $audom = $1;
 3243:         my $auname = $2;
 3244:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3245:             my $homeserver = &homeserver($auname,$audom);
 3246:             unless (($homeserver eq 'no_host') ||
 3247:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3248:                 my $fname = &filelocation('',$url);
 3249:                 if (-e $fname) {
 3250:                     my $protocol = $protocol{$homeserver};
 3251:                     $protocol = 'http' if ($protocol ne 'https');
 3252:                     my $hostname = &hostname($homeserver);
 3253:                     if ($hostname) {
 3254:                         my $uri = &declutter($url);
 3255:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3256:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3257:                         if ($response->is_success()) {
 3258:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3259:                             my $locmodtime = (stat($fname))[9];
 3260:                             if ($locmodtime < $remmodtime) {
 3261:                                 my $stale;
 3262:                                 my $answer = &reply('pong',$homeserver);
 3263:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3264:                                     sleep(0.2);
 3265:                                     $locmodtime = (stat($fname))[9];
 3266:                                     if ($locmodtime < $remmodtime) {
 3267:                                         my $posstransfer = $fname.'.in.transfer';
 3268:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3269:                                             $removed = 1;
 3270:                                         } else {
 3271:                                             $stale = 1;
 3272:                                         }
 3273:                                     } else {
 3274:                                         $removed = 1;
 3275:                                     }
 3276:                                 } else {
 3277:                                     $stale = 1;
 3278:                                 }
 3279:                                 if ($stale) {
 3280:                                     unlink($fname);
 3281:                                     if ($uri!~/\.meta$/) {
 3282:                                         unlink($fname.'.meta');
 3283:                                     }
 3284:                                     &reply("unsub:$fname",$homeserver);
 3285:                                     $removed = 1;
 3286:                                 }
 3287:                             }
 3288:                         }
 3289:                     }
 3290:                 }
 3291:             }
 3292:         }
 3293:     }
 3294:     return $removed;
 3295: }
 3296: 
 3297: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3298: 
 3299: sub allowuploaded {
 3300:     my ($srcurl,$url)=@_;
 3301:     $url=&clutter(&declutter($url));
 3302:     my $dir=$url;
 3303:     $dir=~s/\/[^\/]+$//;
 3304:     my %httpref=();
 3305:     my $httpurl=&hreflocation('',$url);
 3306:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3307:     &Apache::lonnet::appenv(\%httpref);
 3308: }
 3309: 
 3310: #
 3311: # Determine if the current user should be able to edit a particular resource,
 3312: # when viewing in course context.
 3313: # (a) When viewing resource used to determine if "Edit" item is included in 
 3314: #     Functions.
 3315: # (b) When displaying folder contents in course editor, used to determine if
 3316: #     "Edit" link will be displayed alongside resource.
 3317: #
 3318: #  input: six args -- filename (decluttered), course number, course domain,
 3319: #                   url, symb (if registered) and group (if this is a group
 3320: #                   item -- e.g., bulletin board, group page etc.).
 3321: #  output: array of five scalars -- 
 3322: #          $cfile -- url for file editing if editable on current server
 3323: #          $home -- homeserver of resource (i.e., for author if published,
 3324: #                                           or course if uploaded.).
 3325: #          $switchserver --  1 if server switch will be needed.
 3326: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3327: #          $forceview -- 1 if icon/link should be to go to view mode
 3328: #
 3329: 
 3330: sub can_edit_resource {
 3331:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3332:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3333: #
 3334: # For aboutme pages user can only edit his/her own.
 3335: #
 3336:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3337:         my ($sdom,$sname) = ($1,$2);
 3338:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3339:             $home = $env{'user.home'};
 3340:             $cfile = $resurl;
 3341:             if ($env{'form.forceedit'}) {
 3342:                 $forceview = 1;
 3343:             } else {
 3344:                 $forceedit = 1;
 3345:             }
 3346:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3347:         } else {
 3348:             return;
 3349:         }
 3350:     }
 3351: 
 3352:     if ($env{'request.course.id'}) {
 3353:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3354:         if ($group ne '') {
 3355: # if this is a group homepage or group bulletin board, check group privs
 3356:             my $allowed = 0;
 3357:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3358:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3359:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3360:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3361:                     $allowed = 1;
 3362:                 }
 3363:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3364:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3365:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3366:                     $allowed = 1;
 3367:                 }
 3368:             }
 3369:             if ($allowed) {
 3370:                 $home=&homeserver($cnum,$cdom);
 3371:                 if ($env{'form.forceedit'}) {
 3372:                     $forceview = 1;
 3373:                 } else {
 3374:                     $forceedit = 1;
 3375:                 }
 3376:                 $cfile = $resurl;
 3377:             } else {
 3378:                 return;
 3379:             }
 3380:         } else {
 3381:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3382:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3383:                     return;
 3384:                 }
 3385:             } elsif (!$crsedit) {
 3386: #
 3387: # No edit allowed where CC has switched to student role.
 3388: #
 3389:                 return;
 3390:             }
 3391:         }
 3392:     }
 3393: 
 3394:     if ($file ne '') {
 3395:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3396:             if (&is_course_upload($file,$cnum,$cdom)) {
 3397:                 $uploaded = 1;
 3398:                 $incourse = 1;
 3399:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3400:                     $cfile = &hreflocation('',$file);
 3401:                     if ($env{'form.forceedit'}) {
 3402:                         $forceview = 1;
 3403:                     } else {
 3404:                         $forceedit = 1;
 3405:                     }
 3406:                 }
 3407:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3408:                 $incourse = 1;
 3409:                 if ($env{'form.forceedit'}) {
 3410:                     $forceview = 1;
 3411:                 } else {
 3412:                     $forceedit = 1;
 3413:                 }
 3414:                 $cfile = $resurl;
 3415:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3416:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3417:                     $incourse = 1;
 3418:                     if ($env{'form.forceedit'}) {
 3419:                         $forceview = 1;
 3420:                     } else {
 3421:                         $forceedit = 1;
 3422:                     }
 3423:                     $cfile = $resurl;
 3424:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3425:                     $incourse = 1;
 3426:                     $cfile = $resurl.'/smpedit';
 3427:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3428:                     $incourse = 1;
 3429:                     if ($env{'form.forceedit'}) {
 3430:                         $forceview = 1;
 3431:                     } else {
 3432:                         $forceedit = 1;
 3433:                     }
 3434:                     $cfile = $resurl;
 3435:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3436:                     $incourse = 1;
 3437:                     if ($env{'form.forceedit'}) {
 3438:                         $forceview = 1;
 3439:                     } else {
 3440:                         $forceedit = 1;
 3441:                     }
 3442:                     $cfile = $resurl;
 3443:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3444:                     $incourse = 1;
 3445:                     if ($env{'form.forceedit'}) {
 3446:                         $forceview = 1;
 3447:                     } else {
 3448:                         $forceedit = 1;
 3449:                     }
 3450:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3451:                 }
 3452:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3453:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3454:                 if (&is_on_map($template)) { 
 3455:                     $incourse = 1;
 3456:                     $forceview = 1;
 3457:                     $cfile = $template;
 3458:                 }
 3459:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3460:                     $incourse = 1;
 3461:                     if ($env{'form.forceedit'}) {
 3462:                         $forceview = 1;
 3463:                     } else {
 3464:                         $forceedit = 1;
 3465:                     }
 3466:                     $cfile = $resurl;
 3467:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3468:                 $incourse = 1;
 3469:                 if ($env{'form.forceedit'}) {
 3470:                     $forceview = 1;
 3471:                 } else {
 3472:                     $forceedit = 1;
 3473:                 }
 3474:                 $cfile = $resurl;
 3475:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3476:                 $incourse = 1;
 3477:                 $forceview = 1;
 3478:                 if ($symb) {
 3479:                     my ($map,$id,$res)=&decode_symb($symb);
 3480:                     $env{'request.symb'} = $symb;
 3481:                     $cfile = &clutter($res);
 3482:                 } else {
 3483:                     $cfile = $env{'form.suppurl'};
 3484:                     my $escfile = &unescape($cfile);
 3485:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3486:                         $cfile = '/adm/wrapper'.$escfile;
 3487:                     } else {
 3488:                         $escfile =~ s{^http://}{};
 3489:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3490:                     }
 3491:                 }
 3492:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3493:                 if ($env{'form.forceedit'}) {
 3494:                     $forceview = 1;
 3495:                 } else {
 3496:                     $forceedit = 1;
 3497:                 }
 3498:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3499:             }
 3500:         }
 3501:         if ($uploaded || $incourse) {
 3502:             $home=&homeserver($cnum,$cdom);
 3503:         } elsif ($file !~ m{/$}) {
 3504:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3505:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3506:             # Check that the user has permission to edit this resource
 3507:             my $setpriv = 1;
 3508:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3509:             if (defined($cfudom)) {
 3510:                 $home=&homeserver($cfuname,$cfudom);
 3511:                 $cfile=$file;
 3512:             }
 3513:         }
 3514:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3515:             (($home ne '') && ($home ne 'no_host'))) {
 3516:             my @ids=&current_machine_ids();
 3517:             unless (grep(/^\Q$home\E$/,@ids)) {
 3518:                 $switchserver=1;
 3519:             }
 3520:         }
 3521:     }
 3522:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3523: }
 3524: 
 3525: sub is_course_upload {
 3526:     my ($file,$cnum,$cdom) = @_;
 3527:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3528:     $uploadpath =~ s{^\/}{};
 3529:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3530:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3531:         return 1;
 3532:     }
 3533:     return;
 3534: }
 3535: 
 3536: sub in_course {
 3537:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3538:     if ($hideprivileged) {
 3539:         my $skipuser;
 3540:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3541:         my @possdoms = ($cdom);  
 3542:         if ($coursehash{'checkforpriv'}) { 
 3543:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3544:         }
 3545:         if (&privileged($uname,$udom,\@possdoms)) {
 3546:             $skipuser = 1;
 3547:             if ($coursehash{'nothideprivileged'}) {
 3548:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3549:                     my $user;
 3550:                     if ($item =~ /:/) {
 3551:                         $user = $item;
 3552:                     } else {
 3553:                         $user = join(':',split(/[\@]/,$item));
 3554:                     }
 3555:                     if ($user eq $uname.':'.$udom) {
 3556:                         undef($skipuser);
 3557:                         last;
 3558:                     }
 3559:                 }
 3560:             }
 3561:             if ($skipuser) {
 3562:                 return 0;
 3563:             }
 3564:         }
 3565:     }
 3566:     $type ||= 'any';
 3567:     if (!defined($cdom) || !defined($cnum)) {
 3568:         my $cid  = $env{'request.course.id'};
 3569:         $cdom = $env{'course.'.$cid.'.domain'};
 3570:         $cnum = $env{'course.'.$cid.'.num'};
 3571:     }
 3572:     my $typesref;
 3573:     if (($type eq 'any') || ($type eq 'all')) {
 3574:         $typesref = ['active','previous','future'];
 3575:     } elsif ($type eq 'previous' || $type eq 'future') {
 3576:         $typesref = [$type];
 3577:     }
 3578:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3579:                               $typesref,undef,[$cdom]);
 3580:     my ($tmp) = keys(%roles);
 3581:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3582:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3583:     if (@course_roles > 0) {
 3584:         return 1;
 3585:     }
 3586:     return 0;
 3587: }
 3588: 
 3589: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3590: # input: action, courseID, current domain, intended
 3591: #        path to file, source of file, instruction to parse file for objects,
 3592: #        ref to hash for embedded objects,
 3593: #        ref to hash for codebase of java objects.
 3594: #        reference to scalar to accommodate mime type determined
 3595: #          from File::MMagic if $parser = parse.
 3596: #
 3597: # output: url to file (if action was uploaddoc), 
 3598: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3599: #
 3600: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3601: # course.
 3602: #
 3603: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3604: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3605: #          course's home server.
 3606: #
 3607: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3608: #          be copied from $source (current location) to 
 3609: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3610: #         and will then be copied to
 3611: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3612: #         course's home server.
 3613: #
 3614: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3615: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3616: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3617: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3618: #         in course's home server.
 3619: #
 3620: 
 3621: sub process_coursefile {
 3622:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3623:         $mimetype)=@_;
 3624:     my $fetchresult;
 3625:     my $home=&homeserver($docuname,$docudom);
 3626:     if ($action eq 'propagate') {
 3627:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3628: 			     $home);
 3629:     } else {
 3630:         my $fpath = '';
 3631:         my $fname = $file;
 3632:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3633:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3634:         my $filepath = &build_filepath($fpath);
 3635:         if ($action eq 'copy') {
 3636:             if ($source eq '') {
 3637:                 $fetchresult = 'no source file';
 3638:                 return $fetchresult;
 3639:             } else {
 3640:                 my $destination = $filepath.'/'.$fname;
 3641:                 rename($source,$destination);
 3642:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3643:                                  $home);
 3644:             }
 3645:         } elsif ($action eq 'uploaddoc') {
 3646:             open(my $fh,'>',$filepath.'/'.$fname);
 3647:             print $fh $env{'form.'.$source};
 3648:             close($fh);
 3649:             if ($parser eq 'parse') {
 3650:                 my $mm = new File::MMagic;
 3651:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3652:                 if ($type eq 'text/html') {
 3653:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3654:                     unless ($parse_result eq 'ok') {
 3655:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3656:                     }
 3657:                 }
 3658:                 if (ref($mimetype)) {
 3659:                     $$mimetype = $type;
 3660:                 } 
 3661:             }
 3662:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3663:                                  $home);
 3664:             if ($fetchresult eq 'ok') {
 3665:                 return '/uploaded/'.$fpath.'/'.$fname;
 3666:             } else {
 3667:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3668:                         ' to host '.$home.': '.$fetchresult);
 3669:                 return '/adm/notfound.html';
 3670:             }
 3671:         }
 3672:     }
 3673:     unless ( $fetchresult eq 'ok') {
 3674:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3675:              ' to host '.$home.': '.$fetchresult);
 3676:     }
 3677:     return $fetchresult;
 3678: }
 3679: 
 3680: sub build_filepath {
 3681:     my ($fpath) = @_;
 3682:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3683:     unless ($fpath eq '') {
 3684:         my @parts=split('/',$fpath);
 3685:         foreach my $part (@parts) {
 3686:             $filepath.= '/'.$part;
 3687:             if ((-e $filepath)!=1) {
 3688:                 mkdir($filepath,0777);
 3689:             }
 3690:         }
 3691:     }
 3692:     return $filepath;
 3693: }
 3694: 
 3695: sub store_edited_file {
 3696:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3697:     my $file = $primary_url;
 3698:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3699:     my $fpath = '';
 3700:     my $fname = $file;
 3701:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3702:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3703:     my $filepath = &build_filepath($fpath);
 3704:     open(my $fh,'>',$filepath.'/'.$fname);
 3705:     print $fh $content;
 3706:     close($fh);
 3707:     my $home=&homeserver($docuname,$docudom);
 3708:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3709: 			  $home);
 3710:     if ($$fetchresult eq 'ok') {
 3711:         return '/uploaded/'.$fpath.'/'.$fname;
 3712:     } else {
 3713:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3714: 		 ' to host '.$home.': '.$$fetchresult);
 3715:         return '/adm/notfound.html';
 3716:     }
 3717: }
 3718: 
 3719: sub clean_filename {
 3720:     my ($fname,$args)=@_;
 3721: # Replace Windows backslashes by forward slashes
 3722:     $fname=~s/\\/\//g;
 3723:     if (!$args->{'keep_path'}) {
 3724:         # Get rid of everything but the actual filename
 3725: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3726:     }
 3727: # Replace spaces by underscores
 3728:     $fname=~s/\s+/\_/g;
 3729: # Replace all other weird characters by nothing
 3730:     $fname=~s{[^/\w\.\-]}{}g;
 3731: # Replace all .\d. sequences with _\d. so they no longer look like version
 3732: # numbers
 3733:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3734:     return $fname;
 3735: }
 3736: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3737: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3738: # image with the same aspect ratio as the original, but with dimensions which do 
 3739: # not exceed $resizewidth and $resizeheight.
 3740:  
 3741: sub resizeImage {
 3742:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3743:     my $ima = Image::Magick->new;
 3744:     my $resized;
 3745:     if (-e $img_path) {
 3746:         $ima->Read($img_path);
 3747:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3748:             my $width = $ima->Get('width');
 3749:             my $height = $ima->Get('height');
 3750:             if ($width > $resizewidth) {
 3751: 	        my $factor = $width/$resizewidth;
 3752:                 my $newheight = $height/$factor;
 3753:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3754:                 $resized = 1;
 3755:             }
 3756:         }
 3757:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3758:             my $width = $ima->Get('width');
 3759:             my $height = $ima->Get('height');
 3760:             if ($height > $resizeheight) {
 3761:                 my $factor = $height/$resizeheight;
 3762:                 my $newwidth = $width/$factor;
 3763:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3764:                 $resized = 1;
 3765:             }
 3766:         }
 3767:         if ($resized) {
 3768:             $ima->Write($img_path);
 3769:         }
 3770:     }
 3771:     return;
 3772: }
 3773: 
 3774: # --------------- Take an uploaded file and put it into the userfiles directory
 3775: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3776: #                    the desired filename is in $env{"form.$formname.filename"}
 3777: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3778: #                                    canceloverwrite, or ''. 
 3779: #                   if 'coursedoc': upload to the current course
 3780: #                   if 'existingfile': write file to tmp/overwrites directory 
 3781: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3782: #                   $context is passed as argument to &finishuserfileupload
 3783: #        $subdir - directory in userfile to store the file into
 3784: #        $parser - instruction to parse file for objects ($parser = parse)    
 3785: #        $allfiles - reference to hash for embedded objects
 3786: #        $codebase - reference to hash for codebase of java objects
 3787: #        $desuname - username for permanent storage of uploaded file
 3788: #        $dsetudom - domain for permanaent storage of uploaded file
 3789: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3790: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3791: #        $resizewidth - width (pixels) to which to resize uploaded image
 3792: #        $resizeheight - height (pixels) to which to resize uploaded image
 3793: #        $mimetype - reference to scalar to accommodate mime type determined
 3794: #                    from File::MMagic.
 3795: # 
 3796: # output: url of file in userspace, or error: <message> 
 3797: #             or /adm/notfound.html if failure to upload occurse
 3798: 
 3799: sub userfileupload {
 3800:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3801:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3802:     if (!defined($subdir)) { $subdir='unknown'; }
 3803:     my $fname=$env{'form.'.$formname.'.filename'};
 3804:     $fname=&clean_filename($fname);
 3805:     # See if there is anything left
 3806:     unless ($fname) { return 'error: no uploaded file'; }
 3807:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3808:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3809:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3810:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3811:         my $now = time;
 3812:         my $filepath;
 3813:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3814:              $filepath = 'tmp/helprequests/'.$now;
 3815:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3816:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3817:                          '_'.$env{'user.domain'}.'/pending';
 3818:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3819:             my ($docuname,$docudom);
 3820:             if ($destudom =~ /^$match_domain$/) {
 3821:                 $docudom = $destudom;
 3822:             } else {
 3823:                 $docudom = $env{'user.domain'};
 3824:             }
 3825:             if ($destuname =~ /^$match_username$/) {
 3826:                 $docuname = $destuname;
 3827:             } else {
 3828:                 $docuname = $env{'user.name'};
 3829:             }
 3830:             if (exists($env{'form.group'})) {
 3831:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3832:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3833:             }
 3834:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3835:             if ($context eq 'canceloverwrite') {
 3836:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3837:                 if (-e  $tempfile) {
 3838:                     my @info = stat($tempfile);
 3839:                     if ($info[9] eq $env{'form.timestamp'}) {
 3840:                         unlink($tempfile);
 3841:                     }
 3842:                 }
 3843:                 return;
 3844:             }
 3845:         }
 3846:         # Create the directory if not present
 3847:         my @parts=split(/\//,$filepath);
 3848:         my $fullpath = $perlvar{'lonDaemons'};
 3849:         for (my $i=0;$i<@parts;$i++) {
 3850:             $fullpath .= '/'.$parts[$i];
 3851:             if ((-e $fullpath)!=1) {
 3852:                 mkdir($fullpath,0777);
 3853:             }
 3854:         }
 3855:         open(my $fh,'>',$fullpath.'/'.$fname);
 3856:         print $fh $env{'form.'.$formname};
 3857:         close($fh);
 3858:         if ($context eq 'existingfile') {
 3859:             my @info = stat($fullpath.'/'.$fname);
 3860:             return ($fullpath.'/'.$fname,$info[9]);
 3861:         } else {
 3862:             return $fullpath.'/'.$fname;
 3863:         }
 3864:     }
 3865:     if ($subdir eq 'scantron') {
 3866:         $fname = 'scantron_orig_'.$fname;
 3867:     } else {
 3868:         $fname="$subdir/$fname";
 3869:     }
 3870:     if ($context eq 'coursedoc') {
 3871: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3872: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3873:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3874:             return &finishuserfileupload($docuname,$docudom,
 3875: 					 $formname,$fname,$parser,$allfiles,
 3876: 					 $codebase,$thumbwidth,$thumbheight,
 3877:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3878:         } else {
 3879:             if ($env{'form.folder'}) {
 3880:                 $fname=$env{'form.folder'}.'/'.$fname;
 3881:             }
 3882:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3883: 				       $fname,$formname,$parser,
 3884: 				       $allfiles,$codebase,$mimetype);
 3885:         }
 3886:     } elsif (defined($destuname)) {
 3887:         my $docuname=$destuname;
 3888:         my $docudom=$destudom;
 3889: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3890: 				     $parser,$allfiles,$codebase,
 3891:                                      $thumbwidth,$thumbheight,
 3892:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3893:     } else {
 3894:         my $docuname=$env{'user.name'};
 3895:         my $docudom=$env{'user.domain'};
 3896:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3897:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3898:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3899:         }
 3900: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3901: 				     $parser,$allfiles,$codebase,
 3902:                                      $thumbwidth,$thumbheight,
 3903:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3904:     }
 3905: }
 3906: 
 3907: sub finishuserfileupload {
 3908:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3909:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3910:     my $path=$docudom.'/'.$docuname.'/';
 3911:     my $filepath=$perlvar{'lonDocRoot'};
 3912:   
 3913:     my ($fnamepath,$file,$fetchthumb);
 3914:     $file=$fname;
 3915:     if ($fname=~m|/|) {
 3916:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3917: 	$path.=$fnamepath.'/';
 3918:     }
 3919:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3920:     my $count;
 3921:     for ($count=4;$count<=$#parts;$count++) {
 3922:         $filepath.="/$parts[$count]";
 3923:         if ((-e $filepath)!=1) {
 3924: 	    mkdir($filepath,0777);
 3925:         }
 3926:     }
 3927: 
 3928: # Save the file
 3929:     {
 3930: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3931: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3932: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3933: 	    return '/adm/notfound.html';
 3934: 	}
 3935:         if ($context eq 'overwrite') {
 3936:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3937:             my $target = $filepath.'/'.$file;
 3938:             if (-e $source) {
 3939:                 my @info = stat($source);
 3940:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3941:                     unless (&File::Copy::move($source,$target)) {
 3942:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3943:                         return "Moving from $source failed";
 3944:                     }
 3945:                 } else {
 3946:                     return "Temporary file: $source had unexpected date/time for last modification";
 3947:                 }
 3948:             } else {
 3949:                 return "Temporary file: $source missing";
 3950:             }
 3951:         } elsif (!print FH ($env{'form.'.$formname})) {
 3952: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3953: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3954: 	    return '/adm/notfound.html';
 3955: 	}
 3956: 	close(FH);
 3957:         if ($resizewidth && $resizeheight) {
 3958:             my $mm = new File::MMagic;
 3959:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3960:             if ($mime_type =~ m{^image/}) {
 3961: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3962:             }  
 3963: 	}
 3964:     }
 3965:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3966:         if (ref($mimetype)) {
 3967:             if ($$mimetype eq '') {
 3968:                 my $mm = new File::MMagic;
 3969:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3970:                 $$mimetype = $type;
 3971:             }
 3972:         }
 3973:     }
 3974:     if ($parser eq 'parse') {
 3975:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3976:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3977:                                                        $allfiles,$codebase);
 3978:             unless ($parse_result eq 'ok') {
 3979:                 &logthis('Failed to parse '.$filepath.$file.
 3980: 	   	         ' for embedded media: '.$parse_result); 
 3981:             }
 3982:         }
 3983:     }
 3984:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3985:         my $input = $filepath.'/'.$file;
 3986:         my $output = $filepath.'/'.'tn-'.$file;
 3987:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3988:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 3989:         system({$args[0]} @args);
 3990:         if (-e $filepath.'/'.'tn-'.$file) {
 3991:             $fetchthumb  = 1; 
 3992:         }
 3993:     }
 3994:  
 3995: # Notify homeserver to grep it
 3996: #
 3997:     my $docuhome=&homeserver($docuname,$docudom);	
 3998:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3999:     if ($fetchresult eq 'ok') {
 4000:         if ($fetchthumb) {
 4001:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4002:             if ($thumbresult ne 'ok') {
 4003:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4004:                          $docuhome.': '.$thumbresult);
 4005:             }
 4006:         }
 4007: #
 4008: # Return the URL to it
 4009:         return '/uploaded/'.$path.$file;
 4010:     } else {
 4011:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4012: 		 ': '.$fetchresult);
 4013:         return '/adm/notfound.html';
 4014:     }
 4015: }
 4016: 
 4017: sub extract_embedded_items {
 4018:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4019:     my @state = ();
 4020:     my (%lastids,%related,%shockwave,%flashvars);
 4021:     my %javafiles = (
 4022:                       codebase => '',
 4023:                       code => '',
 4024:                       archive => ''
 4025:                     );
 4026:     my %mediafiles = (
 4027:                       src => '',
 4028:                       movie => '',
 4029:                      );
 4030:     my $p;
 4031:     if ($content) {
 4032:         $p = HTML::LCParser->new($content);
 4033:     } else {
 4034:         $p = HTML::LCParser->new($fullpath);
 4035:     }
 4036:     while (my $t=$p->get_token()) {
 4037: 	if ($t->[0] eq 'S') {
 4038: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4039: 	    push(@state, $tagname);
 4040:             if (lc($tagname) eq 'allow') {
 4041:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4042:             }
 4043: 	    if (lc($tagname) eq 'img') {
 4044: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4045: 	    }
 4046: 	    if (lc($tagname) eq 'a') {
 4047:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4048:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4049:                 }
 4050: 	    }
 4051:             if (lc($tagname) eq 'script') {
 4052:                 my $src;
 4053:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4054:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4055:                 } else {
 4056:                     if ($attr->{'src'} ne '') {
 4057:                         $src = $attr->{'src'};
 4058:                         &add_filetype($allfiles,$src,'src');
 4059:                     }
 4060:                 }
 4061:                 my $text = $p->get_trimmed_text();
 4062:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4063:                     my @swfargs = split(/,/,$1);
 4064:                     foreach my $item (@swfargs) {
 4065:                         $item =~ s/["']//g;
 4066:                         $item =~ s/^\s+//;
 4067:                         $item =~ s/\s+$//;
 4068:                     }
 4069:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4070:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4071:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4072:                         } else {
 4073:                             $related{$swfargs[0]} = [$swfargs[2]];
 4074:                         }
 4075:                     }
 4076:                 }
 4077:             }
 4078:             if (lc($tagname) eq 'link') {
 4079:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4080:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4081:                 }
 4082:             }
 4083: 	    if (lc($tagname) eq 'object' ||
 4084: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4085: 		foreach my $item (keys(%javafiles)) {
 4086: 		    $javafiles{$item} = '';
 4087: 		}
 4088:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4089:                     $lastids{lc($tagname)} = $attr->{'id'};
 4090:                 }
 4091: 	    }
 4092: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4093: 		my $name = lc($attr->{'name'});
 4094: 		foreach my $item (keys(%javafiles)) {
 4095: 		    if ($name eq $item) {
 4096: 			$javafiles{$item} = $attr->{'value'};
 4097: 			last;
 4098: 		    }
 4099: 		}
 4100:                 my $pathfrom;
 4101: 		foreach my $item (keys(%mediafiles)) {
 4102: 		    if ($name eq $item) {
 4103:                         $pathfrom = $attr->{'value'};
 4104:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4105: 			&add_filetype($allfiles,$pathfrom,$name);
 4106: 			last;
 4107: 		    }
 4108: 		}
 4109:                 if ($name eq 'flashvars') {
 4110:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4111:                 }
 4112:                 if ($pathfrom ne '') {
 4113:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4114:                                          $pathfrom);
 4115:                 }
 4116: 	    }
 4117: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4118: 		foreach my $item (keys(%javafiles)) {
 4119: 		    if ($attr->{$item}) {
 4120: 			$javafiles{$item} = $attr->{$item};
 4121: 			last;
 4122: 		    }
 4123: 		}
 4124: 		foreach my $item (keys(%mediafiles)) {
 4125: 		    if ($attr->{$item}) {
 4126: 			&add_filetype($allfiles,$attr->{$item},$item);
 4127: 			last;
 4128: 		    }
 4129: 		}
 4130:                 if (lc($tagname) eq 'embed') {
 4131:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4132:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4133:                                              $attr->{'src'});
 4134:                     }
 4135:                 }
 4136: 	    }
 4137:             if (lc($tagname) eq 'iframe') {
 4138:                 my $src = $attr->{'src'} ;
 4139:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4140:                     &add_filetype($allfiles,$src,'src');
 4141:                 } elsif ($src =~ m{^/}) {
 4142:                     if ($env{'request.course.id'}) {
 4143:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4144:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4145:                         my $url = &hreflocation('',$fullpath);
 4146:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4147:                             my $relpath = $1;
 4148:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4149:                                 &add_filetype($allfiles,$1,'src');
 4150:                             }
 4151:                         }
 4152:                     }
 4153:                 }
 4154:             }
 4155:             if ($t->[4] =~ m{/>$}) {
 4156:                 pop(@state);
 4157:             }
 4158: 	} elsif ($t->[0] eq 'E') {
 4159: 	    my ($tagname) = ($t->[1]);
 4160: 	    if ($javafiles{'codebase'} ne '') {
 4161: 		$javafiles{'codebase'} .= '/';
 4162: 	    }  
 4163: 	    if (lc($tagname) eq 'applet' ||
 4164: 		lc($tagname) eq 'object' ||
 4165: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4166: 		) {
 4167: 		foreach my $item (keys(%javafiles)) {
 4168: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4169: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4170: 			&add_filetype($allfiles,$file,$item);
 4171: 		    }
 4172: 		}
 4173: 	    } 
 4174: 	    pop @state;
 4175: 	}
 4176:     }
 4177:     foreach my $id (sort(keys(%flashvars))) {
 4178:         if ($shockwave{$id} ne '') {
 4179:             my @pairs = split(/\&/,$flashvars{$id});
 4180:             foreach my $pair (@pairs) {
 4181:                 my ($key,$value) = split(/\=/,$pair);
 4182:                 if ($key eq 'thumb') {
 4183:                     &add_filetype($allfiles,$value,$key);
 4184:                 } elsif ($key eq 'content') {
 4185:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4186:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4187:                     if ($ext ne '') {
 4188:                         &add_filetype($allfiles,$path.$value,$ext);
 4189:                     }
 4190:                 }
 4191:             }
 4192:         }
 4193:     }
 4194:     return 'ok';
 4195: }
 4196: 
 4197: sub add_filetype {
 4198:     my ($allfiles,$file,$type)=@_;
 4199:     if (exists($allfiles->{$file})) {
 4200: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4201: 	    push(@{$allfiles->{$file}}, &escape($type));
 4202: 	}
 4203:     } else {
 4204: 	@{$allfiles->{$file}} = (&escape($type));
 4205:     }
 4206: }
 4207: 
 4208: sub embedded_dependency {
 4209:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4210:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4211:         if (($identifier ne '') &&
 4212:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4213:             ($pathfrom ne '')) {
 4214:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4215:             foreach my $dep (@{$related->{$identifier}}) {
 4216:                 &add_filetype($allfiles,$path.$dep,'object');
 4217:             }
 4218:         }
 4219:     }
 4220:     return;
 4221: }
 4222: 
 4223: sub removeuploadedurl {
 4224:     my ($url)=@_;	
 4225:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4226:     return &removeuserfile($uname,$udom,$fname);
 4227: }
 4228: 
 4229: sub removeuserfile {
 4230:     my ($docuname,$docudom,$fname)=@_;
 4231:     my $home=&homeserver($docuname,$docudom);    
 4232:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4233:     if ($result eq 'ok') {	
 4234:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4235:             my $metafile = $fname.'.meta';
 4236:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4237: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4238:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4239:             my $sqlresult = 
 4240:                 &update_portfolio_table($docuname,$docudom,$file,
 4241:                                         'portfolio_metadata',$group,
 4242:                                         'delete');
 4243:         }
 4244:     }
 4245:     return $result;
 4246: }
 4247: 
 4248: sub mkdiruserfile {
 4249:     my ($docuname,$docudom,$dir)=@_;
 4250:     my $home=&homeserver($docuname,$docudom);
 4251:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4252: }
 4253: 
 4254: sub renameuserfile {
 4255:     my ($docuname,$docudom,$old,$new)=@_;
 4256:     my $home=&homeserver($docuname,$docudom);
 4257:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4258:                         &escape("$old").':'.&escape("$new"),$home);
 4259:     if ($result eq 'ok') {
 4260:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4261:             my $oldmeta = $old.'.meta';
 4262:             my $newmeta = $new.'.meta';
 4263:             my $metaresult = 
 4264:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4265: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4266:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4267:             my $sqlresult = 
 4268:                 &update_portfolio_table($docuname,$docudom,$file,
 4269:                                         'portfolio_metadata',$group,
 4270:                                         'delete');
 4271:         }
 4272:     }
 4273:     return $result;
 4274: }
 4275: 
 4276: # ------------------------------------------------------------------------- Log
 4277: 
 4278: sub log {
 4279:     my ($dom,$nam,$hom,$what)=@_;
 4280:     return critical("log:$dom:$nam:$what",$hom);
 4281: }
 4282: 
 4283: # ------------------------------------------------------------------ Course Log
 4284: #
 4285: # This routine flushes several buffers of non-mission-critical nature
 4286: #
 4287: 
 4288: sub flushcourselogs {
 4289:     &logthis('Flushing log buffers');
 4290: #
 4291: # course logs
 4292: # This is a log of all transactions in a course, which can be used
 4293: # for data mining purposes
 4294: #
 4295: # It also collects the courseid database, which lists last transaction
 4296: # times and course titles for all courseids
 4297: #
 4298:     my %courseidbuffer=();
 4299:     foreach my $crsid (keys(%courselogs)) {
 4300:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4301: 		          &escape($courselogs{$crsid}),
 4302: 		          $coursehombuf{$crsid}) eq 'ok') {
 4303: 	    delete $courselogs{$crsid};
 4304:         } else {
 4305:             &logthis('Failed to flush log buffer for '.$crsid);
 4306:             if (length($courselogs{$crsid})>40000) {
 4307:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4308:                         " exceeded maximum size, deleting.</font>");
 4309:                delete $courselogs{$crsid};
 4310:             }
 4311:         }
 4312:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4313:             'description' => $coursedescrbuf{$crsid},
 4314:             'inst_code'    => $courseinstcodebuf{$crsid},
 4315:             'type'        => $coursetypebuf{$crsid},
 4316:             'owner'       => $courseownerbuf{$crsid},
 4317:         };
 4318:     }
 4319: #
 4320: # Write course id database (reverse lookup) to homeserver of courses 
 4321: # Is used in pickcourse
 4322: #
 4323:     foreach my $crs_home (keys(%courseidbuffer)) {
 4324:         my $response = &courseidput(&host_domain($crs_home),
 4325:                                     $courseidbuffer{$crs_home},
 4326:                                     $crs_home,'timeonly');
 4327:     }
 4328: #
 4329: # File accesses
 4330: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4331: #
 4332:     foreach my $entry (keys(%accesshash)) {
 4333:         if ($entry =~ /___count$/) {
 4334:             my ($dom,$name);
 4335:             ($dom,$name,undef)=
 4336: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4337:             if (! defined($dom) || $dom eq '' || 
 4338:                 ! defined($name) || $name eq '') {
 4339:                 my $cid = $env{'request.course.id'};
 4340:                 $dom  = $env{'request.'.$cid.'.domain'};
 4341:                 $name = $env{'request.'.$cid.'.num'};
 4342:             }
 4343:             my $value = $accesshash{$entry};
 4344:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4345:             my %temphash=($url => $value);
 4346:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4347:             if ($result eq 'ok') {
 4348:                 delete $accesshash{$entry};
 4349:             }
 4350:         } else {
 4351:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4352:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4353:             my %temphash=($entry => $accesshash{$entry});
 4354:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4355:                 delete $accesshash{$entry};
 4356:             }
 4357:         }
 4358:     }
 4359: #
 4360: # Roles
 4361: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4362: #
 4363:     foreach my $entry (keys(%userrolehash)) {
 4364:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4365: 	    split(/\:/,$entry);
 4366:         if (&Apache::lonnet::put('nohist_userroles',
 4367:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4368:                 $rudom,$runame) eq 'ok') {
 4369: 	    delete $userrolehash{$entry};
 4370:         }
 4371:     }
 4372: #
 4373: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4374: #
 4375:     my %domrolebuffer = ();
 4376:     foreach my $entry (keys(%domainrolehash)) {
 4377:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4378:         if ($domrolebuffer{$rudom}) {
 4379:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4380:                       '='.&escape($domainrolehash{$entry});
 4381:         } else {
 4382:             $domrolebuffer{$rudom}.=&escape($entry).
 4383:                       '='.&escape($domainrolehash{$entry});
 4384:         }
 4385:         delete $domainrolehash{$entry};
 4386:     }
 4387:     foreach my $dom (keys(%domrolebuffer)) {
 4388: 	my %servers;
 4389: 	if (defined(&domain($dom,'primary'))) {
 4390: 	    my $primary=&domain($dom,'primary');
 4391: 	    my $hostname=&hostname($primary);
 4392: 	    $servers{$primary} = $hostname;
 4393: 	} else { 
 4394: 	    %servers = &get_servers($dom,'library');
 4395: 	}
 4396: 	foreach my $tryserver (keys(%servers)) {
 4397: 	    if (&reply('domroleput:'.$dom.':'.
 4398: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4399: 		last;
 4400: 	    } else {  
 4401: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4402: 	    }
 4403:         }
 4404:     }
 4405:     $dumpcount++;
 4406: }
 4407: 
 4408: sub courselog {
 4409:     my $what=shift;
 4410:     $what=time.':'.$what;
 4411:     unless ($env{'request.course.id'}) { return ''; }
 4412:     $coursedombuf{$env{'request.course.id'}}=
 4413:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4414:     $coursenumbuf{$env{'request.course.id'}}=
 4415:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4416:     $coursehombuf{$env{'request.course.id'}}=
 4417:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4418:     $coursedescrbuf{$env{'request.course.id'}}=
 4419:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4420:     $courseinstcodebuf{$env{'request.course.id'}}=
 4421:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4422:     $courseownerbuf{$env{'request.course.id'}}=
 4423:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4424:     $coursetypebuf{$env{'request.course.id'}}=
 4425:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4426:     if (defined $courselogs{$env{'request.course.id'}}) {
 4427: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4428:     } else {
 4429: 	$courselogs{$env{'request.course.id'}}.=$what;
 4430:     }
 4431:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4432: 	&flushcourselogs();
 4433:     }
 4434: }
 4435: 
 4436: sub courseacclog {
 4437:     my $fnsymb=shift;
 4438:     unless ($env{'request.course.id'}) { return ''; }
 4439:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4440:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4441:         $what.=':POST';
 4442:         # FIXME: Probably ought to escape things....
 4443: 	foreach my $key (keys(%env)) {
 4444:             if ($key=~/^form\.(.*)/) {
 4445:                 my $formitem = $1;
 4446:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4447:                     $what.=':'.$formitem.'='.$env{$key};
 4448:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4449:                     $what.=':'.$formitem.'='.$env{$key};
 4450:                 }
 4451:             }
 4452:         }
 4453:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4454:         # FIXME: We should not be depending on a form parameter that someone
 4455:         # editing lonsearchcat.pm might change in the future.
 4456:         if ($env{'form.phase'} eq 'course_search') {
 4457:             $what.= ':POST';
 4458:             # FIXME: Probably ought to escape things....
 4459:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4460:                                  'crsdiscuss') {
 4461:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4462:             }
 4463:         }
 4464:     }
 4465:     &courselog($what);
 4466: }
 4467: 
 4468: sub countacc {
 4469:     my $url=&declutter(shift);
 4470:     return if (! defined($url) || $url eq '');
 4471:     unless ($env{'request.course.id'}) { return ''; }
 4472: #
 4473: # Mark that this url was used in this course
 4474: #
 4475:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4476: #
 4477: # Increase the access count for this resource in this child process
 4478: #
 4479:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4480:     $accesshash{$key}++;
 4481: }
 4482: 
 4483: sub linklog {
 4484:     my ($from,$to)=@_;
 4485:     $from=&declutter($from);
 4486:     $to=&declutter($to);
 4487:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4488:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4489: }
 4490: 
 4491: sub statslog {
 4492:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4493:     if ($users<2) { return; }
 4494:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4495:             'course'       => $env{'request.course.id'},
 4496:             'sections'     => '"all"',
 4497:             'num_students' => $users,
 4498:             'part'         => $part,
 4499:             'symb'         => $symb,
 4500:             'mean_tries'   => $av_attempts,
 4501:             'deg_of_diff'  => $degdiff});
 4502:     foreach my $key (keys(%dynstore)) {
 4503:         $accesshash{$key}=$dynstore{$key};
 4504:     }
 4505: }
 4506:   
 4507: sub userrolelog {
 4508:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4509:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4510:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4511:        $userrolehash
 4512:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4513:                     =$tend.':'.$tstart;
 4514:     }
 4515:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4516:        $userrolehash
 4517:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4518:                     =$tend.':'.$tstart;
 4519:     }
 4520:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4521:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4522:        $domainrolehash
 4523:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4524:                     = $tend.':'.$tstart;
 4525:     }
 4526: }
 4527: 
 4528: sub courserolelog {
 4529:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4530:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4531:         my $cdom = $1;
 4532:         my $cnum = $2;
 4533:         my $sec = $3;
 4534:         my $namespace = 'rolelog';
 4535:         my %storehash = (
 4536:                            role    => $trole,
 4537:                            start   => $tstart,
 4538:                            end     => $tend,
 4539:                            selfenroll => $selfenroll,
 4540:                            context    => $context,
 4541:                         );
 4542:         if ($trole eq 'gr') {
 4543:             $namespace = 'groupslog';
 4544:             $storehash{'group'} = $sec;
 4545:         } else {
 4546:             $storehash{'section'} = $sec;
 4547:         }
 4548:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4549:                    $domain,$cnum,$cdom);
 4550:         if (($trole ne 'st') || ($sec ne '')) {
 4551:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4552:         }
 4553:     }
 4554:     return;
 4555: }
 4556: 
 4557: sub domainrolelog {
 4558:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4559:     if ($area =~ m{^/($match_domain)/$}) {
 4560:         my $cdom = $1;
 4561:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4562:         my $namespace = 'rolelog';
 4563:         my %storehash = (
 4564:                            role    => $trole,
 4565:                            start   => $tstart,
 4566:                            end     => $tend,
 4567:                            context => $context,
 4568:                         );
 4569:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4570:                    $domain,$domconfiguser,$cdom);
 4571:     }
 4572:     return;
 4573: 
 4574: }
 4575: 
 4576: sub coauthorrolelog {
 4577:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4578:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4579:         my $audom = $1;
 4580:         my $auname = $2;
 4581:         my $namespace = 'rolelog';
 4582:         my %storehash = (
 4583:                            role    => $trole,
 4584:                            start   => $tstart,
 4585:                            end     => $tend,
 4586:                            context => $context,
 4587:                         );
 4588:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4589:                    $domain,$auname,$audom);
 4590:     }
 4591:     return;
 4592: }
 4593: 
 4594: sub get_course_adv_roles {
 4595:     my ($cid,$codes) = @_;
 4596:     $cid=$env{'request.course.id'} unless (defined($cid));
 4597:     my %coursehash=&coursedescription($cid);
 4598:     my $crstype = &Apache::loncommon::course_type($cid);
 4599:     my %nothide=();
 4600:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4601:         if ($user !~ /:/) {
 4602: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4603:         } else {
 4604:             $nothide{$user}=1;
 4605:         }
 4606:     }
 4607:     my @possdoms = ($coursehash{'domain'});
 4608:     if ($coursehash{'checkforpriv'}) {
 4609:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4610:     }
 4611:     my %returnhash=();
 4612:     my %dumphash=
 4613:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4614:     my $now=time;
 4615:     my %privileged;
 4616:     foreach my $entry (keys(%dumphash)) {
 4617: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4618:         if (($tstart) && ($tstart<0)) { next; }
 4619:         if (($tend) && ($tend<$now)) { next; }
 4620:         if (($tstart) && ($now<$tstart)) { next; }
 4621:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4622: 	if ($username eq '' || $domain eq '') { next; }
 4623:         if ((&privileged($username,$domain,\@possdoms)) &&
 4624:             (!$nothide{$username.':'.$domain})) { next; }
 4625: 	if ($role eq 'cr') { next; }
 4626:         if ($codes) {
 4627:             if ($section) { $role .= ':'.$section; }
 4628:             if ($returnhash{$role}) {
 4629:                 $returnhash{$role}.=','.$username.':'.$domain;
 4630:             } else {
 4631:                 $returnhash{$role}=$username.':'.$domain;
 4632:             }
 4633:         } else {
 4634:             my $key=&plaintext($role,$crstype);
 4635:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4636:             if ($returnhash{$key}) {
 4637: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4638:             } else {
 4639:                 $returnhash{$key}=$username.':'.$domain;
 4640:             }
 4641:         }
 4642:     }
 4643:     return %returnhash;
 4644: }
 4645: 
 4646: sub get_my_roles {
 4647:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4648:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4649:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4650:     my (%dumphash,%nothide);
 4651:     if ($context eq 'userroles') {
 4652:         %dumphash = &dump('roles',$udom,$uname);
 4653:     } else {
 4654:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4655:         if ($hidepriv) {
 4656:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4657:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4658:                 if ($user !~ /:/) {
 4659:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4660:                 } else {
 4661:                     $nothide{$user} = 1;
 4662:                 }
 4663:             }
 4664:         }
 4665:     }
 4666:     my %returnhash=();
 4667:     my $now=time;
 4668:     my %privileged;
 4669:     foreach my $entry (keys(%dumphash)) {
 4670:         my ($role,$tend,$tstart);
 4671:         if ($context eq 'userroles') {
 4672:             next if ($entry =~ /^rolesdef/);
 4673: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4674:         } else {
 4675:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4676:         }
 4677:         if (($tstart) && ($tstart<0)) { next; }
 4678:         my $status = 'active';
 4679:         if (($tend) && ($tend<=$now)) {
 4680:             $status = 'previous';
 4681:         } 
 4682:         if (($tstart) && ($now<$tstart)) {
 4683:             $status = 'future';
 4684:         }
 4685:         if (ref($types) eq 'ARRAY') {
 4686:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4687:                 next;
 4688:             } 
 4689:         } else {
 4690:             if ($status ne 'active') {
 4691:                 next;
 4692:             }
 4693:         }
 4694:         my ($rolecode,$username,$domain,$section,$area);
 4695:         if ($context eq 'userroles') {
 4696:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4697:             (undef,$domain,$username,$section) = split(/\//,$area);
 4698:         } else {
 4699:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4700:         }
 4701:         if (ref($roledoms) eq 'ARRAY') {
 4702:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4703:                 next;
 4704:             }
 4705:         }
 4706:         if (ref($roles) eq 'ARRAY') {
 4707:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4708:                 if ($role =~ /^cr\//) {
 4709:                     if (!grep(/^cr$/,@{$roles})) {
 4710:                         next;
 4711:                     }
 4712:                 } elsif ($role =~ /^gr\//) {
 4713:                     if (!grep(/^gr$/,@{$roles})) {
 4714:                         next;
 4715:                     }
 4716:                 } else {
 4717:                     next;
 4718:                 }
 4719:             }
 4720:         }
 4721:         if ($hidepriv) {
 4722:             my @privroles = ('dc','su');
 4723:             if ($context eq 'userroles') {
 4724:                 next if (grep(/^\Q$role\E$/,@privroles));
 4725:             } else {
 4726:                 my $possdoms = [$domain];
 4727:                 if (ref($roledoms) eq 'ARRAY') {
 4728:                    push(@{$possdoms},@{$roledoms}); 
 4729:                 }
 4730:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4731:                     if (!$nothide{$username.':'.$domain}) {
 4732:                         next;
 4733:                     }
 4734:                 }
 4735:             }
 4736:         }
 4737:         if ($withsec) {
 4738:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4739:                 $tstart.':'.$tend;
 4740:         } else {
 4741:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4742:         }
 4743:     }
 4744:     return %returnhash;
 4745: }
 4746: 
 4747: sub get_all_adhocroles {
 4748:     my ($dom) = @_;
 4749:     my @roles_by_num = ();
 4750:     my %domdefaults = &get_domain_defaults($dom);
 4751:     my (%description,%access_in_dom,%access_info);
 4752:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4753:         my $count = 0;
 4754:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4755:         my %ordered;
 4756:         foreach my $role (sort(keys(%domcurrent))) {
 4757:             my ($order,$desc,$access_in_dom);
 4758:             if (ref($domcurrent{$role}) eq 'HASH') {
 4759:                 $order = $domcurrent{$role}{'order'};
 4760:                 $desc = $domcurrent{$role}{'desc'};
 4761:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4762:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4763:             }
 4764:             if ($order eq '') {
 4765:                 $order = $count;
 4766:             }
 4767:             $ordered{$order} = $role;
 4768:             if ($desc ne '') {
 4769:                 $description{$role} = $desc;
 4770:             } else {
 4771:                 $description{$role}= $role;
 4772:             }
 4773:             $count++;
 4774:         }
 4775:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4776:             push(@roles_by_num,$ordered{$item});
 4777:         }
 4778:     }
 4779:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4780: }
 4781: 
 4782: sub get_my_adhocroles {
 4783:     my ($cid,$checkreg) = @_;
 4784:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4785:     if ($env{'request.course.id'} eq $cid) {
 4786:         $cdom = $env{'course.'.$cid.'.domain'};
 4787:         $cnum = $env{'course.'.$cid.'.num'};
 4788:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4789:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4790:         $cdom = $1;
 4791:         $cnum = $2;
 4792:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4793:                                      $cdom,$cnum);
 4794:     }
 4795:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4796:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4797:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4798:         if ($rosterhash{$user} ne '') {
 4799:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4800:             return ([],{}) if ($type eq 'auto');
 4801:         }
 4802:     }
 4803:     if (($cdom ne '') && ($cnum ne ''))  {
 4804:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4805:             my $then=$env{'user.login.time'};
 4806:             my $update=$env{'user.update.time'};
 4807:             if (!$update) {
 4808:                 $update = $then;
 4809:             }
 4810:             my @liveroles;
 4811:             foreach my $role ('dh','da') {
 4812:                 if ($env{"user.role.$role./$cdom/"}) {
 4813:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4814:                     my $limit = $update;
 4815:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4816:                         $limit = $then;
 4817:                     }
 4818:                     my $activerole = 1;
 4819:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4820:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4821:                     if ($activerole) {
 4822:                         push(@liveroles,$role);
 4823:                     }
 4824:                 }
 4825:             }
 4826:             if (@liveroles) {
 4827:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4828:                     my ($accessref,$accessinfo,%access_in_dom);
 4829:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4830:                     if (ref($roles_by_num) eq 'ARRAY') {
 4831:                         if (@{$roles_by_num}) {
 4832:                             my %settings;
 4833:                             if ($env{'request.course.id'} eq $cid) {
 4834:                                 foreach my $envkey (keys(%env)) {
 4835:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4836:                                         $settings{$1} = $env{$envkey};
 4837:                                     }
 4838:                                 }
 4839:                             } else {
 4840:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4841:                             }
 4842:                             my %setincrs;
 4843:                             if ($settings{'internal.adhocaccess'}) {
 4844:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4845:                             }
 4846:                             my @statuses;
 4847:                             if ($env{'environment.inststatus'}) {
 4848:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4849:                             }
 4850:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4851:                             if (ref($accessref) eq 'HASH') {
 4852:                                 %access_in_dom = %{$accessref};
 4853:                             }
 4854:                             foreach my $role (@{$roles_by_num}) {
 4855:                                 my ($curraccess,@okstatus,@personnel);
 4856:                                 if ($setincrs{$role}) {
 4857:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4858:                                     if ($curraccess eq 'status') {
 4859:                                         @okstatus = split(/\&/,$rest);
 4860:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4861:                                         @personnel = split(/\&/,$rest);
 4862:                                     }
 4863:                                 } else {
 4864:                                     $curraccess = $access_in_dom{$role};
 4865:                                     if (ref($accessinfo) eq 'HASH') {
 4866:                                         if ($curraccess eq 'status') {
 4867:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4868:                                                 @okstatus = @{$accessinfo->{$role}};
 4869:                                             }
 4870:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4871:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4872:                                                 @personnel = @{$accessinfo->{$role}};
 4873:                                             }
 4874:                                         }
 4875:                                     }
 4876:                                 }
 4877:                                 if ($curraccess eq 'none') {
 4878:                                     next;
 4879:                                 } elsif ($curraccess eq 'all') {
 4880:                                     push(@possroles,$role);
 4881:                                 } elsif ($curraccess eq 'dh') {
 4882:                                     if (grep(/^dh$/,@liveroles)) {
 4883:                                         push(@possroles,$role);
 4884:                                     } else {
 4885:                                         next;
 4886:                                     }
 4887:                                 } elsif ($curraccess eq 'da') {
 4888:                                     if (grep(/^da$/,@liveroles)) {
 4889:                                         push(@possroles,$role);
 4890:                                     } else {
 4891:                                         next;
 4892:                                     }
 4893:                                 } elsif ($curraccess eq 'status') {
 4894:                                     if (@okstatus) {
 4895:                                         if (!@statuses) {
 4896:                                             if (grep(/^default$/,@okstatus)) {
 4897:                                                 push(@possroles,$role);
 4898:                                             }
 4899:                                         } else {
 4900:                                             foreach my $status (@okstatus) {
 4901:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4902:                                                     push(@possroles,$role);
 4903:                                                     last;
 4904:                                                 }
 4905:                                             }
 4906:                                         }
 4907:                                     }
 4908:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4909:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4910:                                         if ($curraccess eq 'exc') {
 4911:                                             push(@possroles,$role);
 4912:                                         }
 4913:                                     } elsif ($curraccess eq 'inc') {
 4914:                                         push(@possroles,$role);
 4915:                                     }
 4916:                                 }
 4917:                             }
 4918:                         }
 4919:                     }
 4920:                 }
 4921:             }
 4922:         }
 4923:     }
 4924:     unless (ref($description) eq 'HASH') {
 4925:         if (ref($roles_by_num) eq 'ARRAY') {
 4926:             my %desc;
 4927:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4928:             $description = \%desc;
 4929:         } else {
 4930:             $description = {};
 4931:         }
 4932:     }
 4933:     return (\@possroles,$description);
 4934: }
 4935: 
 4936: # ----------------------------------------------------- Frontpage Announcements
 4937: #
 4938: #
 4939: 
 4940: sub postannounce {
 4941:     my ($server,$text)=@_;
 4942:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4943:     unless ($text=~/\w/) { $text=''; }
 4944:     return &reply('setannounce:'.&escape($text),$server);
 4945: }
 4946: 
 4947: sub getannounce {
 4948: 
 4949:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4950: 	my $announcement='';
 4951: 	while (my $line = <$fh>) { $announcement .= $line; }
 4952: 	close($fh);
 4953: 	if ($announcement=~/\w/) { 
 4954: 	    return 
 4955:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4956:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4957: 	} else {
 4958: 	    return '';
 4959: 	}
 4960:     } else {
 4961: 	return '';
 4962:     }
 4963: }
 4964: 
 4965: # ---------------------------------------------------------- Course ID routines
 4966: # Deal with domain's nohist_courseid.db files
 4967: #
 4968: 
 4969: sub courseidput {
 4970:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4971:     return unless (ref($storehash) eq 'HASH');
 4972:     my $outcome;
 4973:     if ($caller eq 'timeonly') {
 4974:         my $cids = '';
 4975:         foreach my $item (keys(%$storehash)) {
 4976:             $cids.=&escape($item).'&';
 4977:         }
 4978:         $cids=~s/\&$//;
 4979:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4980:                           $coursehome);       
 4981:     } else {
 4982:         my $items = '';
 4983:         foreach my $item (keys(%$storehash)) {
 4984:             $items.= &escape($item).'='.
 4985:                      &freeze_escape($$storehash{$item}).'&';
 4986:         }
 4987:         $items=~s/\&$//;
 4988:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4989:                           $coursehome);
 4990:     }
 4991:     if ($outcome eq 'unknown_cmd') {
 4992:         my $what;
 4993:         foreach my $cid (keys(%$storehash)) {
 4994:             $what .= &escape($cid).'=';
 4995:             foreach my $item ('description','inst_code','owner','type') {
 4996:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4997:             }
 4998:             $what =~ s/\:$/&/;
 4999:         }
 5000:         $what =~ s/\&$//;  
 5001:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5002:     } else {
 5003:         return $outcome;
 5004:     }
 5005: }
 5006: 
 5007: sub courseiddump {
 5008:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5009:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5010:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5011:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5012:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5013:     my $as_hash = 1;
 5014:     my %returnhash;
 5015:     if (!$domfilter) { $domfilter=''; }
 5016:     my %libserv = &all_library();
 5017:     foreach my $tryserver (keys(%libserv)) {
 5018:         if ( (  $hostidflag == 1 
 5019: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5020: 	     || (!defined($hostidflag)) ) {
 5021: 
 5022: 	    if (($domfilter eq '') ||
 5023: 		(&host_domain($tryserver) eq $domfilter)) {
 5024:                 my $rep;
 5025:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5026:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5027:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5028:                                 &escape($descfilter), &escape($instcodefilter), 
 5029:                                 &escape($ownerfilter), &escape($coursefilter),
 5030:                                 &escape($typefilter), &escape($regexp_ok), 
 5031:                                 $as_hash, &escape($selfenrollonly), 
 5032:                                 &escape($catfilter), $showhidden, $caller, 
 5033:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5034:                                 &escape($createdbefore), &escape($createdafter), 
 5035:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5036:                                 $reqcrsdom,&escape($reqinstcode))));
 5037:                 } else {
 5038:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5039:                              $sincefilter.':'.&escape($descfilter).':'.
 5040:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5041:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5042:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5043:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5044:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5045:                              &escape($cc_clone).':'.$cloneonly.':'.
 5046:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5047:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5048:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5049:                 }
 5050:                      
 5051:                 my @pairs=split(/\&/,$rep);
 5052:                 foreach my $item (@pairs) {
 5053:                     my ($key,$value)=split(/\=/,$item,2);
 5054:                     $key = &unescape($key);
 5055:                     next if ($key =~ /^error: 2 /);
 5056:                     my $result = &thaw_unescape($value);
 5057:                     if (ref($result) eq 'HASH') {
 5058:                         $returnhash{$key}=$result;
 5059:                     } else {
 5060:                         my @responses = split(/:/,$value);
 5061:                         my @items = ('description','inst_code','owner','type');
 5062:                         for (my $i=0; $i<@responses; $i++) {
 5063:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5064:                         }
 5065:                     }
 5066:                 }
 5067:             }
 5068:         }
 5069:     }
 5070:     return %returnhash;
 5071: }
 5072: 
 5073: sub courselastaccess {
 5074:     my ($cdom,$cnum,$hostidref) = @_;
 5075:     my %returnhash;
 5076:     if ($cdom && $cnum) {
 5077:         my $chome = &homeserver($cnum,$cdom);
 5078:         if ($chome ne 'no_host') {
 5079:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5080:             &extract_lastaccess(\%returnhash,$rep);
 5081:         }
 5082:     } else {
 5083:         if (!$cdom) { $cdom=''; }
 5084:         my %libserv = &all_library();
 5085:         foreach my $tryserver (keys(%libserv)) {
 5086:             if (ref($hostidref) eq 'ARRAY') {
 5087:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5088:             } 
 5089:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5090:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5091:                 &extract_lastaccess(\%returnhash,$rep);
 5092:             }
 5093:         }
 5094:     }
 5095:     return %returnhash;
 5096: }
 5097: 
 5098: sub extract_lastaccess {
 5099:     my ($returnhash,$rep) = @_;
 5100:     if (ref($returnhash) eq 'HASH') {
 5101:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5102:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5103:                  $rep eq '') {
 5104:             my @pairs=split(/\&/,$rep);
 5105:             foreach my $item (@pairs) {
 5106:                 my ($key,$value)=split(/\=/,$item,2);
 5107:                 $key = &unescape($key);
 5108:                 next if ($key =~ /^error: 2 /);
 5109:                 $returnhash->{$key} = &thaw_unescape($value);
 5110:             }
 5111:         }
 5112:     }
 5113:     return;
 5114: }
 5115: 
 5116: # ---------------------------------------------------------- DC e-mail
 5117: 
 5118: sub dcmailput {
 5119:     my ($domain,$msgid,$message,$server)=@_;
 5120:     my $status = &Apache::lonnet::critical(
 5121:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5122:        &escape($message),$server);
 5123:     return $status;
 5124: }
 5125: 
 5126: sub dcmaildump {
 5127:     my ($dom,$startdate,$enddate,$senders) = @_;
 5128:     my %returnhash=();
 5129: 
 5130:     if (defined(&domain($dom,'primary'))) {
 5131:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5132:                                                          &escape($enddate).':';
 5133: 	my @esc_senders=map { &escape($_)} @$senders;
 5134: 	$cmd.=&escape(join('&',@esc_senders));
 5135: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5136:             my ($key,$value) = split(/\=/,$line,2);
 5137:             if (($key) && ($value)) {
 5138:                 $returnhash{&unescape($key)} = &unescape($value);
 5139:             }
 5140:         }
 5141:     }
 5142:     return %returnhash;
 5143: }
 5144: # ---------------------------------------------------------- Domain roles
 5145: 
 5146: sub get_domain_roles {
 5147:     my ($dom,$roles,$startdate,$enddate)=@_;
 5148:     if ((!defined($startdate)) || ($startdate eq '')) {
 5149:         $startdate = '.';
 5150:     }
 5151:     if ((!defined($enddate)) || ($enddate eq '')) {
 5152:         $enddate = '.';
 5153:     }
 5154:     my $rolelist;
 5155:     if (ref($roles) eq 'ARRAY') {
 5156:         $rolelist = join('&',@{$roles});
 5157:     }
 5158:     my %personnel = ();
 5159: 
 5160:     my %servers = &get_servers($dom,'library');
 5161:     foreach my $tryserver (keys(%servers)) {
 5162: 	%{$personnel{$tryserver}}=();
 5163: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5164: 					    &escape($startdate).':'.
 5165: 					    &escape($enddate).':'.
 5166: 					    &escape($rolelist), $tryserver))) {
 5167: 	    my ($key,$value) = split(/\=/,$line,2);
 5168: 	    if (($key) && ($value)) {
 5169: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5170: 	    }
 5171: 	}
 5172:     }
 5173:     return %personnel;
 5174: }
 5175: 
 5176: sub get_active_domroles {
 5177:     my ($dom,$roles) = @_;
 5178:     return () unless (ref($roles) eq 'ARRAY');
 5179:     my $now = time;
 5180:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5181:     my %domroles;
 5182:     foreach my $server (keys(%dompersonnel)) {
 5183:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5184:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5185:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5186:         }
 5187:     }
 5188:     return %domroles;
 5189: }
 5190: 
 5191: # ----------------------------------------------------------- Interval timing 
 5192: 
 5193: {
 5194: # Caches needed for speedup of navmaps
 5195: # We don't want to cache this for very long at all (5 seconds at most)
 5196: # 
 5197: # The user for whom we cache
 5198: my $cachedkey='';
 5199: # The cached times for this user
 5200: my %cachedtimes=();
 5201: # When this was last done
 5202: my $cachedtime='';
 5203: 
 5204: sub load_all_first_access {
 5205:     my ($uname,$udom,$ignorecache)=@_;
 5206:     if (($cachedkey eq $uname.':'.$udom) &&
 5207:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5208:         (!$ignorecache)) {
 5209:         return;
 5210:     }
 5211:     $cachedtime=time;
 5212:     $cachedkey=$uname.':'.$udom;
 5213:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5214: }
 5215: 
 5216: sub get_first_access {
 5217:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5218:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5219:     if ($argsymb) { $symb=$argsymb; }
 5220:     my ($map,$id,$res)=&decode_symb($symb);
 5221:     if ($argmap) { $map = $argmap; }
 5222:     if ($type eq 'course') {
 5223: 	$res='course';
 5224:     } elsif ($type eq 'map') {
 5225: 	$res=&symbread($map);
 5226:     } else {
 5227: 	$res=$symb;
 5228:     }
 5229:     &load_all_first_access($uname,$udom,$ignorecache);
 5230:     return $cachedtimes{"$courseid\0$res"};
 5231: }
 5232: 
 5233: sub set_first_access {
 5234:     my ($type,$interval)=@_;
 5235:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5236:     my ($map,$id,$res)=&decode_symb($symb);
 5237:     if ($type eq 'course') {
 5238: 	$res='course';
 5239:     } elsif ($type eq 'map') {
 5240: 	$res=&symbread($map);
 5241:     } else {
 5242: 	$res=$symb;
 5243:     }
 5244:     $cachedkey='';
 5245:     my $firstaccess=&get_first_access($type,$symb,$map);
 5246:     if ($firstaccess) {
 5247:         &logthis("First access time already set ($firstaccess) when attempting ".
 5248:                  "to set new value (type: $type, extent: $res) for $uname:$udom ". 
 5249:                  "in $courseid"); 
 5250:         return 'already_set';
 5251:     } else {
 5252:         my $start = time;
 5253: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5254:                           $udom,$uname);
 5255:         if ($putres eq 'ok') {
 5256:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5257:                  $udom,$uname); 
 5258:             &appenv(
 5259:                      {
 5260:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5261:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5262:                      }
 5263:                   );
 5264:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5265:                 $cachedtimes{"$courseid\0$res"} = $start;
 5266:             }
 5267:         } elsif ($putres ne 'refused') {
 5268:             &logthis("Result: $putres when attempting to set first access time ".
 5269:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5270:         }
 5271:         return $putres;
 5272:     }
 5273:     return 'already_set';
 5274: }
 5275: }
 5276: 
 5277: # --------------------------------------------- Set Expire Date for Spreadsheet
 5278: 
 5279: sub expirespread {
 5280:     my ($uname,$udom,$stype,$usymb)=@_;
 5281:     my $cid=$env{'request.course.id'}; 
 5282:     if ($cid) {
 5283:        my $now=time;
 5284:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5285:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5286:                             $env{'course.'.$cid.'.num'}.
 5287: 	        	    ':nohist_expirationdates:'.
 5288:                             &escape($key).'='.$now,
 5289:                             $env{'course.'.$cid.'.home'})
 5290:     }
 5291:     return 'ok';
 5292: }
 5293: 
 5294: # ----------------------------------------------------- Devalidate Spreadsheets
 5295: 
 5296: sub devalidate {
 5297:     my ($symb,$uname,$udom)=@_;
 5298:     my $cid=$env{'request.course.id'}; 
 5299:     if ($cid) {
 5300:         # delete the stored spreadsheets for
 5301:         # - the student level sheet of this user in course's homespace
 5302:         # - the assessment level sheet for this resource 
 5303:         #   for this user in user's homespace
 5304: 	# - current conditional state info
 5305: 	my $key=$uname.':'.$udom.':';
 5306:         my $status=
 5307: 	    &del('nohist_calculatedsheets',
 5308: 		 [$key.'studentcalc:'],
 5309: 		 $env{'course.'.$cid.'.domain'},
 5310: 		 $env{'course.'.$cid.'.num'})
 5311: 		.' '.
 5312: 	    &del('nohist_calculatedsheets_'.$cid,
 5313: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5314:         unless ($status eq 'ok ok') {
 5315:            &logthis('Could not devalidate spreadsheet '.
 5316:                     $uname.' at '.$udom.' for '.
 5317: 		    $symb.': '.$status);
 5318:         }
 5319: 	&delenv('user.state.'.$cid);
 5320:     }
 5321: }
 5322: 
 5323: sub get_scalar {
 5324:     my ($string,$end) = @_;
 5325:     my $value;
 5326:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5327: 	$value = $1;
 5328:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5329: 	$value = $1;
 5330:     }
 5331:     return &unescape($value);
 5332: }
 5333: 
 5334: sub array2str {
 5335:   my (@array) = @_;
 5336:   my $result=&arrayref2str(\@array);
 5337:   $result=~s/^__ARRAY_REF__//;
 5338:   $result=~s/__END_ARRAY_REF__$//;
 5339:   return $result;
 5340: }
 5341: 
 5342: sub arrayref2str {
 5343:   my ($arrayref) = @_;
 5344:   my $result='__ARRAY_REF__';
 5345:   foreach my $elem (@$arrayref) {
 5346:     if(ref($elem) eq 'ARRAY') {
 5347:       $result.=&arrayref2str($elem).'&';
 5348:     } elsif(ref($elem) eq 'HASH') {
 5349:       $result.=&hashref2str($elem).'&';
 5350:     } elsif(ref($elem)) {
 5351:       #print("Got a ref of ".(ref($elem))." skipping.");
 5352:     } else {
 5353:       $result.=&escape($elem).'&';
 5354:     }
 5355:   }
 5356:   $result=~s/\&$//;
 5357:   $result .= '__END_ARRAY_REF__';
 5358:   return $result;
 5359: }
 5360: 
 5361: sub hash2str {
 5362:   my (%hash) = @_;
 5363:   my $result=&hashref2str(\%hash);
 5364:   $result=~s/^__HASH_REF__//;
 5365:   $result=~s/__END_HASH_REF__$//;
 5366:   return $result;
 5367: }
 5368: 
 5369: sub hashref2str {
 5370:   my ($hashref)=@_;
 5371:   my $result='__HASH_REF__';
 5372:   foreach my $key (sort(keys(%$hashref))) {
 5373:     if (ref($key) eq 'ARRAY') {
 5374:       $result.=&arrayref2str($key).'=';
 5375:     } elsif (ref($key) eq 'HASH') {
 5376:       $result.=&hashref2str($key).'=';
 5377:     } elsif (ref($key)) {
 5378:       $result.='=';
 5379:       #print("Got a ref of ".(ref($key))." skipping.");
 5380:     } else {
 5381: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5382:     }
 5383: 
 5384:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5385:       $result.=&arrayref2str($hashref->{$key}).'&';
 5386:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5387:       $result.=&hashref2str($hashref->{$key}).'&';
 5388:     } elsif(ref($hashref->{$key})) {
 5389:        $result.='&';
 5390:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5391:     } else {
 5392:       $result.=&escape($hashref->{$key}).'&';
 5393:     }
 5394:   }
 5395:   $result=~s/\&$//;
 5396:   $result .= '__END_HASH_REF__';
 5397:   return $result;
 5398: }
 5399: 
 5400: sub str2hash {
 5401:     my ($string)=@_;
 5402:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5403:     return %$hash;
 5404: }
 5405: 
 5406: sub str2hashref {
 5407:   my ($string) = @_;
 5408: 
 5409:   my %hash;
 5410: 
 5411:   if($string !~ /^__HASH_REF__/) {
 5412:       if (! ($string eq '' || !defined($string))) {
 5413: 	  $hash{'error'}='Not hash reference';
 5414:       }
 5415:       return (\%hash, $string);
 5416:   }
 5417: 
 5418:   $string =~ s/^__HASH_REF__//;
 5419: 
 5420:   while($string !~ /^__END_HASH_REF__/) {
 5421:       #key
 5422:       my $key='';
 5423:       if($string =~ /^__HASH_REF__/) {
 5424:           ($key, $string)=&str2hashref($string);
 5425:           if(defined($key->{'error'})) {
 5426:               $hash{'error'}='Bad data';
 5427:               return (\%hash, $string);
 5428:           }
 5429:       } elsif($string =~ /^__ARRAY_REF__/) {
 5430:           ($key, $string)=&str2arrayref($string);
 5431:           if($key->[0] eq 'Array reference error') {
 5432:               $hash{'error'}='Bad data';
 5433:               return (\%hash, $string);
 5434:           }
 5435:       } else {
 5436:           $string =~ s/^(.*?)=//;
 5437: 	  $key=&unescape($1);
 5438:       }
 5439:       $string =~ s/^=//;
 5440: 
 5441:       #value
 5442:       my $value='';
 5443:       if($string =~ /^__HASH_REF__/) {
 5444:           ($value, $string)=&str2hashref($string);
 5445:           if(defined($value->{'error'})) {
 5446:               $hash{'error'}='Bad data';
 5447:               return (\%hash, $string);
 5448:           }
 5449:       } elsif($string =~ /^__ARRAY_REF__/) {
 5450:           ($value, $string)=&str2arrayref($string);
 5451:           if($value->[0] eq 'Array reference error') {
 5452:               $hash{'error'}='Bad data';
 5453:               return (\%hash, $string);
 5454:           }
 5455:       } else {
 5456: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5457:       }
 5458:       $string =~ s/^&//;
 5459: 
 5460:       $hash{$key}=$value;
 5461:   }
 5462: 
 5463:   $string =~ s/^__END_HASH_REF__//;
 5464: 
 5465:   return (\%hash, $string);
 5466: }
 5467: 
 5468: sub str2array {
 5469:     my ($string)=@_;
 5470:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5471:     return @$array;
 5472: }
 5473: 
 5474: sub str2arrayref {
 5475:   my ($string) = @_;
 5476:   my @array;
 5477: 
 5478:   if($string !~ /^__ARRAY_REF__/) {
 5479:       if (! ($string eq '' || !defined($string))) {
 5480: 	  $array[0]='Array reference error';
 5481:       }
 5482:       return (\@array, $string);
 5483:   }
 5484: 
 5485:   $string =~ s/^__ARRAY_REF__//;
 5486: 
 5487:   while($string !~ /^__END_ARRAY_REF__/) {
 5488:       my $value='';
 5489:       if($string =~ /^__HASH_REF__/) {
 5490:           ($value, $string)=&str2hashref($string);
 5491:           if(defined($value->{'error'})) {
 5492:               $array[0] ='Array reference error';
 5493:               return (\@array, $string);
 5494:           }
 5495:       } elsif($string =~ /^__ARRAY_REF__/) {
 5496:           ($value, $string)=&str2arrayref($string);
 5497:           if($value->[0] eq 'Array reference error') {
 5498:               $array[0] ='Array reference error';
 5499:               return (\@array, $string);
 5500:           }
 5501:       } else {
 5502: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5503:       }
 5504:       $string =~ s/^&//;
 5505: 
 5506:       push(@array, $value);
 5507:   }
 5508: 
 5509:   $string =~ s/^__END_ARRAY_REF__//;
 5510: 
 5511:   return (\@array, $string);
 5512: }
 5513: 
 5514: # -------------------------------------------------------------------Temp Store
 5515: 
 5516: sub tmpreset {
 5517:   my ($symb,$namespace,$domain,$stuname) = @_;
 5518:   if (!$symb) {
 5519:     $symb=&symbread();
 5520:     if (!$symb) { $symb= $env{'request.url'}; }
 5521:   }
 5522:   $symb=escape($symb);
 5523: 
 5524:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5525:   $namespace=~s/\//\_/g;
 5526:   $namespace=~s/\W//g;
 5527: 
 5528:   if (!$domain) { $domain=$env{'user.domain'}; }
 5529:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5530:   if ($domain eq 'public' && $stuname eq 'public') {
 5531:       $stuname=$ENV{'REMOTE_ADDR'};
 5532:   }
 5533:   my $path=LONCAPA::tempdir();
 5534:   my %hash;
 5535:   if (tie(%hash,'GDBM_File',
 5536: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5537: 	  &GDBM_WRCREAT(),0640)) {
 5538:     foreach my $key (keys(%hash)) {
 5539:       if ($key=~ /:$symb/) {
 5540: 	delete($hash{$key});
 5541:       }
 5542:     }
 5543:   }
 5544: }
 5545: 
 5546: sub tmpstore {
 5547:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5548: 
 5549:   if (!$symb) {
 5550:     $symb=&symbread();
 5551:     if (!$symb) { $symb= $env{'request.url'}; }
 5552:   }
 5553:   $symb=escape($symb);
 5554: 
 5555:   if (!$namespace) {
 5556:     # I don't think we would ever want to store this for a course.
 5557:     # it seems this will only be used if we don't have a course.
 5558:     #$namespace=$env{'request.course.id'};
 5559:     #if (!$namespace) {
 5560:       $namespace=$env{'request.state'};
 5561:     #}
 5562:   }
 5563:   $namespace=~s/\//\_/g;
 5564:   $namespace=~s/\W//g;
 5565:   if (!$domain) { $domain=$env{'user.domain'}; }
 5566:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5567:   if ($domain eq 'public' && $stuname eq 'public') {
 5568:       $stuname=$ENV{'REMOTE_ADDR'};
 5569:   }
 5570:   my $now=time;
 5571:   my %hash;
 5572:   my $path=LONCAPA::tempdir();
 5573:   if (tie(%hash,'GDBM_File',
 5574: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5575: 	  &GDBM_WRCREAT(),0640)) {
 5576:     $hash{"version:$symb"}++;
 5577:     my $version=$hash{"version:$symb"};
 5578:     my $allkeys=''; 
 5579:     foreach my $key (keys(%$storehash)) {
 5580:       $allkeys.=$key.':';
 5581:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5582:     }
 5583:     $hash{"$version:$symb:timestamp"}=$now;
 5584:     $allkeys.='timestamp';
 5585:     $hash{"$version:keys:$symb"}=$allkeys;
 5586:     if (untie(%hash)) {
 5587:       return 'ok';
 5588:     } else {
 5589:       return "error:$!";
 5590:     }
 5591:   } else {
 5592:     return "error:$!";
 5593:   }
 5594: }
 5595: 
 5596: # -----------------------------------------------------------------Temp Restore
 5597: 
 5598: sub tmprestore {
 5599:   my ($symb,$namespace,$domain,$stuname) = @_;
 5600: 
 5601:   if (!$symb) {
 5602:     $symb=&symbread();
 5603:     if (!$symb) { $symb= $env{'request.url'}; }
 5604:   }
 5605:   $symb=escape($symb);
 5606: 
 5607:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5608: 
 5609:   if (!$domain) { $domain=$env{'user.domain'}; }
 5610:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5611:   if ($domain eq 'public' && $stuname eq 'public') {
 5612:       $stuname=$ENV{'REMOTE_ADDR'};
 5613:   }
 5614:   my %returnhash;
 5615:   $namespace=~s/\//\_/g;
 5616:   $namespace=~s/\W//g;
 5617:   my %hash;
 5618:   my $path=LONCAPA::tempdir();
 5619:   if (tie(%hash,'GDBM_File',
 5620: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5621: 	  &GDBM_READER(),0640)) {
 5622:     my $version=$hash{"version:$symb"};
 5623:     $returnhash{'version'}=$version;
 5624:     my $scope;
 5625:     for ($scope=1;$scope<=$version;$scope++) {
 5626:       my $vkeys=$hash{"$scope:keys:$symb"};
 5627:       my @keys=split(/:/,$vkeys);
 5628:       my $key;
 5629:       $returnhash{"$scope:keys"}=$vkeys;
 5630:       foreach $key (@keys) {
 5631: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5632: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5633:       }
 5634:     }
 5635:     if (!(untie(%hash))) {
 5636:       return "error:$!";
 5637:     }
 5638:   } else {
 5639:     return "error:$!";
 5640:   }
 5641:   return %returnhash;
 5642: }
 5643: 
 5644: # ----------------------------------------------------------------------- Store
 5645: 
 5646: sub store {
 5647:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5648:     my $home='';
 5649: 
 5650:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5651: 
 5652:     $symb=&symbclean($symb);
 5653:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5654: 
 5655:     if (!$domain) { $domain=$env{'user.domain'}; }
 5656:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5657: 
 5658:     &devalidate($symb,$stuname,$domain);
 5659: 
 5660:     $symb=escape($symb);
 5661:     if (!$namespace) { 
 5662:        unless ($namespace=$env{'request.course.id'}) { 
 5663:           return ''; 
 5664:        } 
 5665:     }
 5666:     if (!$home) { $home=$env{'user.home'}; }
 5667: 
 5668:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5669:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5670: 
 5671:     my $namevalue='';
 5672:     foreach my $key (keys(%$storehash)) {
 5673:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5674:     }
 5675:     $namevalue=~s/\&$//;
 5676:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5677:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5678: }
 5679: 
 5680: # -------------------------------------------------------------- Critical Store
 5681: 
 5682: sub cstore {
 5683:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5684:     my $home='';
 5685: 
 5686:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5687: 
 5688:     $symb=&symbclean($symb);
 5689:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5690: 
 5691:     if (!$domain) { $domain=$env{'user.domain'}; }
 5692:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5693: 
 5694:     &devalidate($symb,$stuname,$domain);
 5695: 
 5696:     $symb=escape($symb);
 5697:     if (!$namespace) { 
 5698:        unless ($namespace=$env{'request.course.id'}) { 
 5699:           return ''; 
 5700:        } 
 5701:     }
 5702:     if (!$home) { $home=$env{'user.home'}; }
 5703: 
 5704:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5705:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5706: 
 5707:     my $namevalue='';
 5708:     foreach my $key (keys(%$storehash)) {
 5709:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5710:     }
 5711:     $namevalue=~s/\&$//;
 5712:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5713:     return critical
 5714:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5715: }
 5716: 
 5717: # --------------------------------------------------------------------- Restore
 5718: 
 5719: sub restore {
 5720:     my ($symb,$namespace,$domain,$stuname) = @_;
 5721:     my $home='';
 5722: 
 5723:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5724: 
 5725:     if (!$symb) {
 5726:         return if ($namespace eq 'courserequests');
 5727:         unless ($symb=escape(&symbread())) { return ''; }
 5728:     } else {
 5729:         unless ($namespace eq 'courserequests') {
 5730:             $symb=&escape(&symbclean($symb));
 5731:         }
 5732:     }
 5733:     if (!$namespace) { 
 5734:        unless ($namespace=$env{'request.course.id'}) { 
 5735:           return ''; 
 5736:        } 
 5737:     }
 5738:     if (!$domain) { $domain=$env{'user.domain'}; }
 5739:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5740:     if (!$home) { $home=$env{'user.home'}; }
 5741:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5742: 
 5743:     my %returnhash=();
 5744:     foreach my $line (split(/\&/,$answer)) {
 5745: 	my ($name,$value)=split(/\=/,$line);
 5746:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5747:     }
 5748:     my $version;
 5749:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5750:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5751:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5752:        }
 5753:     }
 5754:     return %returnhash;
 5755: }
 5756: 
 5757: # ---------------------------------------------------------- Course Description
 5758: #
 5759: #  
 5760: 
 5761: sub coursedescription {
 5762:     my ($courseid,$args)=@_;
 5763:     $courseid=~s/^\///;
 5764:     $courseid=~s/\_/\//g;
 5765:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5766:     my $chome=&homeserver($cnum,$cdomain);
 5767:     my $normalid=$cdomain.'_'.$cnum;
 5768:     # need to always cache even if we get errors otherwise we keep 
 5769:     # trying and trying and trying to get the course description.
 5770:     my %envhash=();
 5771:     my %returnhash=();
 5772:     
 5773:     my $expiretime=600;
 5774:     if ($env{'request.course.id'} eq $normalid) {
 5775: 	$expiretime=120;
 5776:     }
 5777: 
 5778:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5779:     if (!$args->{'freshen_cache'}
 5780: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5781: 	foreach my $key (keys(%env)) {
 5782: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5783: 	    my ($setting) = $1;
 5784: 	    $returnhash{$setting} = $env{$key};
 5785: 	}
 5786: 	return %returnhash;
 5787:     }
 5788: 
 5789:     # get the data again
 5790: 
 5791:     if (!$args->{'one_time'}) {
 5792: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5793:     }
 5794: 
 5795:     if ($chome ne 'no_host') {
 5796:        %returnhash=&dump('environment',$cdomain,$cnum);
 5797:        if (!exists($returnhash{'con_lost'})) {
 5798: 	   my $username = $env{'user.name'}; # Defult username
 5799: 	   if(defined $args->{'user'}) {
 5800: 	       $username = $args->{'user'};
 5801: 	   }
 5802:            $returnhash{'home'}= $chome;
 5803: 	   $returnhash{'domain'} = $cdomain;
 5804: 	   $returnhash{'num'} = $cnum;
 5805:            if (!defined($returnhash{'type'})) {
 5806:                $returnhash{'type'} = 'Course';
 5807:            }
 5808:            while (my ($name,$value) = each %returnhash) {
 5809:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5810:            }
 5811:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5812:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5813: 	       $username.'_'.$cdomain.'_'.$cnum;
 5814:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5815:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5816:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5817:        }
 5818:     }
 5819:     if (!$args->{'one_time'}) {
 5820: 	&appenv(\%envhash);
 5821:     }
 5822:     return %returnhash;
 5823: }
 5824: 
 5825: sub update_released_required {
 5826:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5827:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5828:         $cid = $env{'request.course.id'};
 5829:         $cdom = $env{'course.'.$cid.'.domain'};
 5830:         $cnum = $env{'course.'.$cid.'.num'};
 5831:         $chome = $env{'course.'.$cid.'.home'};
 5832:     }
 5833:     if ($needsrelease) {
 5834:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5835:         my $needsupdate;
 5836:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5837:             $needsupdate = 1;
 5838:         } else {
 5839:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5840:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5841:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5842:                 $needsupdate = 1;
 5843:             }
 5844:         }
 5845:         if ($needsupdate) {
 5846:             my %needshash = (
 5847:                              'internal.releaserequired' => $needsrelease,
 5848:                             );
 5849:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5850:             if ($putresult eq 'ok') {
 5851:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5852:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5853:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5854:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5855:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5856:                 }
 5857:             }
 5858:         }
 5859:     }
 5860:     return;
 5861: }
 5862: 
 5863: # -------------------------------------------------See if a user is privileged
 5864: 
 5865: sub privileged {
 5866:     my ($username,$domain,$possdomains,$possroles)=@_;
 5867:     my $now = time;
 5868:     my $roles;
 5869:     if (ref($possroles) eq 'ARRAY') {
 5870:         $roles = $possroles; 
 5871:     } else {
 5872:         $roles = ['dc','su'];
 5873:     }
 5874:     if (ref($possdomains) eq 'ARRAY') {
 5875:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5876:         foreach my $dom (@{$possdomains}) {
 5877:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5878:                 (ref($privileged{$dom}) eq 'HASH')) {
 5879:                 foreach my $role (@{$roles}) {
 5880:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5881:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5882:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5883:                             return 1 unless (($end && $end < $now) ||
 5884:                                              ($start && $start > $now));
 5885:                         }
 5886:                     }
 5887:                 }
 5888:             }
 5889:         }
 5890:     } else {
 5891:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5892:         my $now = time;
 5893: 
 5894:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5895:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5896:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5897:                 return 1 unless ($tend && $tend < $now) 
 5898:                         or ($tstart && $tstart > $now);
 5899:             }
 5900:         }
 5901:     }
 5902:     return 0;
 5903: }
 5904: 
 5905: sub privileged_by_domain {
 5906:     my ($domains,$roles) = @_;
 5907:     my %privileged = ();
 5908:     my $cachetime = 60*60*24;
 5909:     my $now = time;
 5910:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5911:         return %privileged;
 5912:     }
 5913:     foreach my $dom (@{$domains}) {
 5914:         next if (ref($privileged{$dom}) eq 'HASH');
 5915:         my $needroles;
 5916:         foreach my $role (@{$roles}) {
 5917:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5918:             if (defined($cached)) {
 5919:                 if (ref($result) eq 'HASH') {
 5920:                     $privileged{$dom}{$role} = $result;
 5921:                 }
 5922:             } else {
 5923:                 $needroles = 1;
 5924:             }
 5925:         }
 5926:         if ($needroles) {
 5927:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5928:             $privileged{$dom} = {};
 5929:             foreach my $server (keys(%dompersonnel)) {
 5930:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5931:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5932:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5933:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5934:                         next if ($end && $end < $now);
 5935:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5936:                             $dompersonnel{$server}{$item};
 5937:                     }
 5938:                 }
 5939:             }
 5940:             if (ref($privileged{$dom}) eq 'HASH') {
 5941:                 foreach my $role (@{$roles}) {
 5942:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5943:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5944:                     } else {
 5945:                         my %hash = ();
 5946:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5947:                     }
 5948:                 }
 5949:             }
 5950:         }
 5951:     }
 5952:     return %privileged;
 5953: }
 5954: 
 5955: # -------------------------------------------------------- Get user privileges
 5956: 
 5957: sub rolesinit {
 5958:     my ($domain, $username) = @_;
 5959:     my %userroles = ('user.login.time' => time);
 5960:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5961: 
 5962:     # firstaccess and timerinterval are related to timed maps/resources. 
 5963:     # also, blocking can be triggered by an activating timer
 5964:     # it's saved in the user's %env.
 5965:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5966:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5967:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5968:         %timerintchk, %timerintenv);
 5969: 
 5970:     foreach my $key (keys(%firstaccess)) {
 5971:         my ($cid, $rest) = split(/\0/, $key);
 5972:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5973:     }
 5974: 
 5975:     foreach my $key (keys(%timerinterval)) {
 5976:         my ($cid,$rest) = split(/\0/,$key);
 5977:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5978:     }
 5979: 
 5980:     my %allroles=();
 5981:     my %allgroups=();
 5982: 
 5983:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5984:         my $role = $rolesdump{$area};
 5985:         $area =~ s/\_\w\w$//;
 5986: 
 5987:         my ($trole, $tend, $tstart, $group_privs);
 5988: 
 5989:         if ($role =~ /^cr/) {
 5990:         # Custom role, defined by a user 
 5991:         # e.g., user.role.cr/msu/smith/mynewrole
 5992:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5993:                 $trole = $1;
 5994:                 ($tend, $tstart) = split('_', $2);
 5995:             } else {
 5996:                 $trole = $role;
 5997:             }
 5998:         } elsif ($role =~ m|^gr/|) {
 5999:         # Role of member in a group, defined within a course/community
 6000:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6001:             ($trole, $tend, $tstart) = split(/_/, $role);
 6002:             next if $tstart eq '-1';
 6003:             ($trole, $group_privs) = split(/\//, $trole);
 6004:             $group_privs = &unescape($group_privs);
 6005:         } else {
 6006:         # Just a normal role, defined in roles.tab
 6007:             ($trole, $tend, $tstart) = split(/_/,$role);
 6008:         }
 6009: 
 6010:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6011:                  $username);
 6012:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6013: 
 6014:         # role expired or not available yet?
 6015:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6016:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6017: 
 6018:         next if $area eq '' or $trole eq '';
 6019: 
 6020:         my $spec = "$trole.$area";
 6021:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6022: 
 6023:         if ($trole =~ /^cr\//) {
 6024:         # Custom role, defined by a user
 6025:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6026:         } elsif ($trole eq 'gr') {
 6027:         # Role of a member in a group, defined within a course/community
 6028:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6029:             next;
 6030:         } else {
 6031:         # Normal role, defined in roles.tab
 6032:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6033:         }
 6034: 
 6035:         my $cid = $tdomain.'_'.$trest;
 6036:         unless ($firstaccchk{$cid}) {
 6037:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6038:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6039:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6040:                         $coursetimerstarts{$cid}{$item}; 
 6041:                 }
 6042:             }
 6043:             $firstaccchk{$cid} = 1;
 6044:         }
 6045:         unless ($timerintchk{$cid}) {
 6046:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6047:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6048:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6049:                        $coursetimerintervals{$cid}{$item};
 6050:                 }
 6051:             }
 6052:             $timerintchk{$cid} = 1;
 6053:         }
 6054:     }
 6055: 
 6056:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6057:                                                           \%allroles, \%allgroups);
 6058:     $env{'user.adv'} = $userroles{'user.adv'};
 6059:     $env{'user.rar'} = $userroles{'user.rar'};
 6060: 
 6061:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6062: }
 6063: 
 6064: sub set_arearole {
 6065:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6066:     unless ($nolog) {
 6067: # log the associated role with the area
 6068:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6069:     }
 6070:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6071: }
 6072: 
 6073: sub custom_roleprivs {
 6074:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6075:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6076:     my $homsvr = &homeserver($rauthor,$rdomain);
 6077:     if (&hostname($homsvr) ne '') {
 6078:         my ($rdummy,$roledef)=
 6079:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6080:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6081:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6082:             if (defined($syspriv)) {
 6083:                 if ($trest =~ /^$match_community$/) {
 6084:                     $syspriv =~ s/bre\&S//; 
 6085:                 }
 6086:                 $$allroles{'cm./'}.=':'.$syspriv;
 6087:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6088:             }
 6089:             if ($tdomain ne '') {
 6090:                 if (defined($dompriv)) {
 6091:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6092:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6093:                 }
 6094:                 if (($trest ne '') && (defined($coursepriv))) {
 6095:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6096:                         my $rolename = $1;
 6097:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6098:                     }
 6099:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6100:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6101:                 }
 6102:             }
 6103:         }
 6104:     }
 6105: }
 6106: 
 6107: sub course_adhocrole_privs {
 6108:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6109:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6110:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6111:         my (%currprivs,%storeprivs);
 6112:         foreach my $item (split(/:/,$coursepriv)) {
 6113:             my ($priv,$restrict) = split(/\&/,$item);
 6114:             $currprivs{$priv} = $restrict;
 6115:         }
 6116:         my (%possadd,%possremove,%full);
 6117:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6118:             my ($priv,$restrict)=split(/\&/,$item);
 6119:             $full{$priv} = $restrict;
 6120:         }
 6121:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6122:              next if ($item eq '');
 6123:              my ($rule,$rest) = split(/=/,$item);
 6124:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6125:              foreach my $priv (split(/:/,$rest)) {
 6126:                  if ($priv ne '') {
 6127:                      if ($rule eq 'off') {
 6128:                          $possremove{$priv} = 1;
 6129:                      } else {
 6130:                          $possadd{$priv} = 1;
 6131:                      }
 6132:                  }
 6133:              }
 6134:          }
 6135:          foreach my $priv (sort(keys(%full))) {
 6136:              if (exists($currprivs{$priv})) {
 6137:                  unless (exists($possremove{$priv})) {
 6138:                      $storeprivs{$priv} = $currprivs{$priv};
 6139:                  }
 6140:              } elsif (exists($possadd{$priv})) {
 6141:                  $storeprivs{$priv} = $full{$priv};
 6142:              }
 6143:          }
 6144:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6145:      }
 6146:      return $coursepriv;
 6147: }
 6148: 
 6149: sub group_roleprivs {
 6150:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6151:     my $access = 1;
 6152:     my $now = time;
 6153:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6154:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6155:     if ($access) {
 6156:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6157:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6158:     }
 6159: }
 6160: 
 6161: sub standard_roleprivs {
 6162:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6163:     if (defined($pr{$trole.':s'})) {
 6164:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6165:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6166:     }
 6167:     if ($tdomain ne '') {
 6168:         if (defined($pr{$trole.':d'})) {
 6169:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6170:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6171:         }
 6172:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6173:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6174:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6175:         }
 6176:     }
 6177: }
 6178: 
 6179: sub set_userprivs {
 6180:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6181:     my $author=0;
 6182:     my $adv=0;
 6183:     my $rar=0;
 6184:     my %grouproles = ();
 6185:     if (keys(%{$allgroups}) > 0) {
 6186:         my @groupkeys; 
 6187:         foreach my $role (keys(%{$allroles})) {
 6188:             push(@groupkeys,$role);
 6189:         }
 6190:         if (ref($groups_roles) eq 'HASH') {
 6191:             foreach my $key (keys(%{$groups_roles})) {
 6192:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6193:                     push(@groupkeys,$key);
 6194:                 }
 6195:             }
 6196:         }
 6197:         if (@groupkeys > 0) {
 6198:             foreach my $role (@groupkeys) {
 6199:                 my ($trole,$area,$sec,$extendedarea);
 6200:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6201:                     $trole = $1;
 6202:                     $area = $2;
 6203:                     $sec = $3;
 6204:                     $extendedarea = $area.$sec;
 6205:                     if (exists($$allgroups{$area})) {
 6206:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6207:                             my $spec = $trole.'.'.$extendedarea;
 6208:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6209:                                                 $$allgroups{$area}{$group};
 6210:                         }
 6211:                     }
 6212:                 }
 6213:             }
 6214:         }
 6215:     }
 6216:     foreach my $group (keys(%grouproles)) {
 6217:         $$allroles{$group} = $grouproles{$group};
 6218:     }
 6219:     foreach my $role (keys(%{$allroles})) {
 6220:         my %thesepriv;
 6221:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6222:         foreach my $item (split(/:/,$$allroles{$role})) {
 6223:             if ($item ne '') {
 6224:                 my ($privilege,$restrictions)=split(/&/,$item);
 6225:                 if ($restrictions eq '') {
 6226:                     $thesepriv{$privilege}='F';
 6227:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6228:                     $thesepriv{$privilege}.=$restrictions;
 6229:                 }
 6230:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6231:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6232:             }
 6233:         }
 6234:         my $thesestr='';
 6235:         foreach my $priv (sort(keys(%thesepriv))) {
 6236: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6237: 	}
 6238:         $userroles->{'user.priv.'.$role} = $thesestr;
 6239:     }
 6240:     return ($author,$adv,$rar);
 6241: }
 6242: 
 6243: sub role_status {
 6244:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6245:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6246:         my ($one,$two) = split(m{\./},$rolekey,2);
 6247:         (undef,undef,$$role) = split(/\./,$one,3);
 6248:         unless (!defined($$role) || $$role eq '') {
 6249:             $$where = '/'.$two;
 6250:             $$trolecode=$$role.'.'.$$where;
 6251:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6252:             $$tstatus='is';
 6253:             if ($$tstart && $$tstart>$update) {
 6254:                 $$tstatus='future';
 6255:                 if ($$tstart<$now) {
 6256:                     if ($$tstart && $$tstart>$refresh) {
 6257:                         if (($$where ne '') && ($$role ne '')) {
 6258:                             my (%allroles,%allgroups,$group_privs,
 6259:                                 %groups_roles,@rolecodes);
 6260:                             my %userroles = (
 6261:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6262:                             );
 6263:                             @rolecodes = ('cm'); 
 6264:                             my $spec=$$role.'.'.$$where;
 6265:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6266:                             if ($$role =~ /^cr\//) {
 6267:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6268:                                 push(@rolecodes,'cr');
 6269:                             } elsif ($$role eq 'gr') {
 6270:                                 push(@rolecodes,$$role);
 6271:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6272:                                                     $env{'user.name'});
 6273:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6274:                                 (undef,my $group_privs) = split(/\//,$trole);
 6275:                                 $group_privs = &unescape($group_privs);
 6276:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6277:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6278:                                 &get_groups_roles($tdomain,$trest,
 6279:                                                   \%course_roles,\@rolecodes,
 6280:                                                   \%groups_roles);
 6281:                             } else {
 6282:                                 push(@rolecodes,$$role);
 6283:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6284:                             }
 6285:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6286:                                                                    \%groups_roles);
 6287:                             &appenv(\%userroles,\@rolecodes);
 6288:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6289:                         }
 6290:                     }
 6291:                     $$tstatus = 'is';
 6292:                 }
 6293:             }
 6294:             if ($$tend) {
 6295:                 if ($$tend<$update) {
 6296:                     $$tstatus='expired';
 6297:                 } elsif ($$tend<$now) {
 6298:                     $$tstatus='will_not';
 6299:                 }
 6300:             }
 6301:         }
 6302:     }
 6303: }
 6304: 
 6305: sub get_groups_roles {
 6306:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6307:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6308:                   (ref($rolecodes) eq 'ARRAY') && 
 6309:                   (ref($groups_roles) eq 'HASH')); 
 6310:     if (keys(%{$cdom_courseroles}) > 0) {
 6311:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6312:         if ($cdom ne '' && $cnum ne '') {
 6313:             foreach my $key (keys(%{$cdom_courseroles})) {
 6314:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6315:                     my $crsrole = $1;
 6316:                     my $crssec = $2;
 6317:                     if ($crsrole =~ /^cr/) {
 6318:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6319:                             push(@{$rolecodes},'cr');
 6320:                         }
 6321:                     } else {
 6322:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6323:                             push(@{$rolecodes},$crsrole);
 6324:                         }
 6325:                     }
 6326:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6327:                     if ($crssec ne '') {
 6328:                         $rolekey .= "/$crssec";
 6329:                     }
 6330:                     $rolekey .= './';
 6331:                     $groups_roles->{$rolekey} = $rolecodes;
 6332:                 }
 6333:             }
 6334:         }
 6335:     }
 6336:     return;
 6337: }
 6338: 
 6339: sub delete_env_groupprivs {
 6340:     my ($where,$courseroles,$possroles) = @_;
 6341:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6342:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6343:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6344:         %{$courseroles->{$udom}} =
 6345:             &get_my_roles('','','userroles',['active'],
 6346:                           $possroles,[$udom],1);
 6347:     }
 6348:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6349:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6350:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6351:             my $area = '/'.$cdom.'/'.$cnum;
 6352:             my $privkey = "user.priv.$crsrole.$area";
 6353:             if ($crssec ne '') {
 6354:                 $privkey .= '/'.$crssec;
 6355:             }
 6356:             $privkey .= ".$area/$group";
 6357:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6358:         }
 6359:     }
 6360:     return;
 6361: }
 6362: 
 6363: sub check_adhoc_privs {
 6364:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6365:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6366:     if ($sec) {
 6367:         $cckey .= '/'.$sec;
 6368:     } 
 6369:     my $setprivs;
 6370:     if ($env{$cckey}) {
 6371:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6372:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6373:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6374:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6375:             $setprivs = 1;
 6376:         }
 6377:     } else {
 6378:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6379:         $setprivs = 1;
 6380:     }
 6381:     return $setprivs;
 6382: }
 6383: 
 6384: sub set_adhoc_privileges {
 6385: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6386:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6387:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6388:     if ($sec ne '') {
 6389:         $area .= '/'.$sec;
 6390:     }
 6391:     my $spec = $role.'.'.$area;
 6392:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6393:                                   $env{'user.name'},1);
 6394:     my %rolehash = ();
 6395:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6396:         my $rolename = $1;
 6397:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6398:         my %domdef = &get_domain_defaults($dcdom);
 6399:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6400:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6401:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6402:             }
 6403:         }
 6404:     } else {
 6405:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6406:     }
 6407:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6408:     &appenv(\%userroles,[$role,'cm']);
 6409:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6410:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6411:         &appenv( {'request.role'        => $spec,
 6412:                   'request.role.domain' => $dcdom,
 6413:                   'request.course.sec'  => $sec,
 6414:                  }
 6415:                );
 6416:         my $tadv=0;
 6417:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6418:         &appenv({'request.role.adv'    => $tadv});
 6419:     }
 6420: }
 6421: 
 6422: # --------------------------------------------------------------- get interface
 6423: 
 6424: sub get {
 6425:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6426:    my $items='';
 6427:    foreach my $item (@$storearr) {
 6428:        $items.=&escape($item).'&';
 6429:    }
 6430:    $items=~s/\&$//;
 6431:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6432:    if (!$uname) { $uname=$env{'user.name'}; }
 6433:    my $uhome=&homeserver($uname,$udomain);
 6434: 
 6435:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6436:    my @pairs=split(/\&/,$rep);
 6437:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6438:      return @pairs;
 6439:    }
 6440:    my %returnhash=();
 6441:    my $i=0;
 6442:    foreach my $item (@$storearr) {
 6443:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6444:       $i++;
 6445:    }
 6446:    return %returnhash;
 6447: }
 6448: 
 6449: # --------------------------------------------------------------- del interface
 6450: 
 6451: sub del {
 6452:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6453:    my $items='';
 6454:    foreach my $item (@$storearr) {
 6455:        $items.=&escape($item).'&';
 6456:    }
 6457: 
 6458:    $items=~s/\&$//;
 6459:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6460:    if (!$uname) { $uname=$env{'user.name'}; }
 6461:    my $uhome=&homeserver($uname,$udomain);
 6462:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6463: }
 6464: 
 6465: # -------------------------------------------------------------- dump interface
 6466: 
 6467: sub unserialize {
 6468:     my ($rep, $escapedkeys) = @_;
 6469: 
 6470:     return {} if $rep =~ /^error/;
 6471: 
 6472:     my %returnhash=();
 6473: 	foreach my $item (split(/\&/,$rep)) {
 6474: 	    my ($key, $value) = split(/=/, $item, 2);
 6475: 	    $key = unescape($key) unless $escapedkeys;
 6476: 	    next if $key =~ /^error: 2 /;
 6477: 	    $returnhash{$key} = &thaw_unescape($value);
 6478: 	}
 6479:     #return %returnhash;
 6480:     return \%returnhash;
 6481: }        
 6482: 
 6483: # see Lond::dump_with_regexp
 6484: # if $escapedkeys hash keys won't get unescaped.
 6485: sub dump {
 6486:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6487:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6488:     if (!$uname) { $uname=$env{'user.name'}; }
 6489:     my $uhome=&homeserver($uname,$udomain);
 6490: 
 6491:     if ($regexp) {
 6492:         $regexp=&escape($regexp);
 6493:     } else {
 6494:         $regexp='.';
 6495:     }
 6496:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6497:         # user is hosted on this machine
 6498:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6499:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6500:         return %{unserialize($reply, $escapedkeys)};
 6501:     }
 6502:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6503:     my @pairs=split(/\&/,$rep);
 6504:     my %returnhash=();
 6505:     if (!($rep =~ /^error/ )) {
 6506: 	foreach my $item (@pairs) {
 6507: 	    my ($key,$value)=split(/=/,$item,2);
 6508:         $key = unescape($key) unless $escapedkeys;
 6509:         #$key = &unescape($key);
 6510: 	    next if ($key =~ /^error: 2 /);
 6511: 	    $returnhash{$key}=&thaw_unescape($value);
 6512: 	}
 6513:     }
 6514:     return %returnhash;
 6515: }
 6516: 
 6517: 
 6518: # --------------------------------------------------------- dumpstore interface
 6519: 
 6520: sub dumpstore {
 6521:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6522:    # same as dump but keys must be escaped. They may contain colon separated
 6523:    # lists of values that may themself contain colons (e.g. symbs).
 6524:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6525: }
 6526: 
 6527: # -------------------------------------------------------------- keys interface
 6528: 
 6529: sub getkeys {
 6530:    my ($namespace,$udomain,$uname)=@_;
 6531:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6532:    if (!$uname) { $uname=$env{'user.name'}; }
 6533:    my $uhome=&homeserver($uname,$udomain);
 6534:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6535:    my @keyarray=();
 6536:    foreach my $key (split(/\&/,$rep)) {
 6537:       next if ($key =~ /^error: 2 /);
 6538:       push(@keyarray,&unescape($key));
 6539:    }
 6540:    return @keyarray;
 6541: }
 6542: 
 6543: # --------------------------------------------------------------- currentdump
 6544: sub currentdump {
 6545:    my ($courseid,$sdom,$sname)=@_;
 6546:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6547:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6548:    $sname    = $env{'user.name'}         if (! defined($sname));
 6549:    my $uhome = &homeserver($sname,$sdom);
 6550:    my $rep;
 6551: 
 6552:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6553:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6554:                    $courseid)));
 6555:    } else {
 6556:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6557:    }
 6558: 
 6559:    return if ($rep =~ /^(error:|no_such_host)/);
 6560:    #
 6561:    my %returnhash=();
 6562:    #
 6563:    if ($rep eq 'unknown_cmd') {
 6564:        # an old lond will not know currentdump
 6565:        # Do a dump and make it look like a currentdump
 6566:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6567:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6568:        my %hash = @tmp;
 6569:        @tmp=();
 6570:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6571:    } else {
 6572:        my @pairs=split(/\&/,$rep);
 6573:        foreach my $pair (@pairs) {
 6574:            my ($key,$value)=split(/=/,$pair,2);
 6575:            my ($symb,$param) = split(/:/,$key);
 6576:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6577:                                                         &thaw_unescape($value);
 6578:        }
 6579:    }
 6580:    return %returnhash;
 6581: }
 6582: 
 6583: sub convert_dump_to_currentdump{
 6584:     my %hash = %{shift()};
 6585:     my %returnhash;
 6586:     # Code ripped from lond, essentially.  The only difference
 6587:     # here is the unescaping done by lonnet::dump().  Conceivably
 6588:     # we might run in to problems with parameter names =~ /^v\./
 6589:     while (my ($key,$value) = each(%hash)) {
 6590:         my ($v,$symb,$param) = split(/:/,$key);
 6591: 	$symb  = &unescape($symb);
 6592: 	$param = &unescape($param);
 6593:         next if ($v eq 'version' || $symb eq 'keys');
 6594:         next if (exists($returnhash{$symb}) &&
 6595:                  exists($returnhash{$symb}->{$param}) &&
 6596:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6597:         $returnhash{$symb}->{$param}=$value;
 6598:         $returnhash{$symb}->{'v.'.$param}=$v;
 6599:     }
 6600:     #
 6601:     # Remove all of the keys in the hashes which keep track of
 6602:     # the version of the parameter.
 6603:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6604:         # use a foreach because we are going to delete from the hash.
 6605:         foreach my $key (keys(%$param_hash)) {
 6606:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6607:         }
 6608:     }
 6609:     return \%returnhash;
 6610: }
 6611: 
 6612: # ------------------------------------------------------ critical inc interface
 6613: 
 6614: sub cinc {
 6615:     return &inc(@_,'critical');
 6616: }
 6617: 
 6618: # --------------------------------------------------------------- inc interface
 6619: 
 6620: sub inc {
 6621:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6622:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6623:     if (!$uname) { $uname=$env{'user.name'}; }
 6624:     my $uhome=&homeserver($uname,$udomain);
 6625:     my $items='';
 6626:     if (! ref($store)) {
 6627:         # got a single value, so use that instead
 6628:         $items = &escape($store).'=&';
 6629:     } elsif (ref($store) eq 'SCALAR') {
 6630:         $items = &escape($$store).'=&';        
 6631:     } elsif (ref($store) eq 'ARRAY') {
 6632:         $items = join('=&',map {&escape($_);} @{$store});
 6633:     } elsif (ref($store) eq 'HASH') {
 6634:         while (my($key,$value) = each(%{$store})) {
 6635:             $items.= &escape($key).'='.&escape($value).'&';
 6636:         }
 6637:     }
 6638:     $items=~s/\&$//;
 6639:     if ($critical) {
 6640: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6641:     } else {
 6642: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6643:     }
 6644: }
 6645: 
 6646: # --------------------------------------------------------------- put interface
 6647: 
 6648: sub put {
 6649:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6650:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6651:    if (!$uname) { $uname=$env{'user.name'}; }
 6652:    my $uhome=&homeserver($uname,$udomain);
 6653:    my $items='';
 6654:    foreach my $item (keys(%$storehash)) {
 6655:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6656:    }
 6657:    $items=~s/\&$//;
 6658:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6659: }
 6660: 
 6661: # ------------------------------------------------------------ newput interface
 6662: 
 6663: sub newput {
 6664:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6665:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6666:    if (!$uname) { $uname=$env{'user.name'}; }
 6667:    my $uhome=&homeserver($uname,$udomain);
 6668:    my $items='';
 6669:    foreach my $key (keys(%$storehash)) {
 6670:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6671:    }
 6672:    $items=~s/\&$//;
 6673:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6674: }
 6675: 
 6676: # ---------------------------------------------------------  putstore interface
 6677: 
 6678: sub putstore {
 6679:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6680:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6681:    if (!$uname) { $uname=$env{'user.name'}; }
 6682:    my $uhome=&homeserver($uname,$udomain);
 6683:    my $items='';
 6684:    foreach my $key (keys(%$storehash)) {
 6685:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6686:    }
 6687:    $items=~s/\&$//;
 6688:    my $esc_symb=&escape($symb);
 6689:    my $esc_v=&escape($version);
 6690:    my $reply =
 6691:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6692: 	      $uhome);
 6693:    if (($tolog) && ($reply eq 'ok')) {
 6694:        my $namevalue='';
 6695:        foreach my $key (keys(%{$storehash})) {
 6696:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6697:        }
 6698:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6699:                      '&host='.&escape($perlvar{'lonHostID'}).
 6700:                      '&version='.$esc_v.
 6701:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6702:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6703:    }
 6704:    if ($reply eq 'unknown_cmd') {
 6705:        # gfall back to way things use to be done
 6706:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6707: 			    $uname);
 6708:    }
 6709:    return $reply;
 6710: }
 6711: 
 6712: sub old_putstore {
 6713:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6714:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6715:     if (!$uname) { $uname=$env{'user.name'}; }
 6716:     my $uhome=&homeserver($uname,$udomain);
 6717:     my %newstorehash;
 6718:     foreach my $item (keys(%$storehash)) {
 6719: 	my $key = $version.':'.&escape($symb).':'.$item;
 6720: 	$newstorehash{$key} = $storehash->{$item};
 6721:     }
 6722:     my $items='';
 6723:     my %allitems = ();
 6724:     foreach my $item (keys(%newstorehash)) {
 6725: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6726: 	    my $key = $1.':keys:'.$2;
 6727: 	    $allitems{$key} .= $3.':';
 6728: 	}
 6729: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6730:     }
 6731:     foreach my $item (keys(%allitems)) {
 6732: 	$allitems{$item} =~ s/\:$//;
 6733: 	$items.= $item.'='.$allitems{$item}.'&';
 6734:     }
 6735:     $items=~s/\&$//;
 6736:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6737: }
 6738: 
 6739: # ------------------------------------------------------ critical put interface
 6740: 
 6741: sub cput {
 6742:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6743:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6744:    if (!$uname) { $uname=$env{'user.name'}; }
 6745:    my $uhome=&homeserver($uname,$udomain);
 6746:    my $items='';
 6747:    foreach my $item (keys(%$storehash)) {
 6748:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6749:    }
 6750:    $items=~s/\&$//;
 6751:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6752: }
 6753: 
 6754: # -------------------------------------------------------------- eget interface
 6755: 
 6756: sub eget {
 6757:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6758:    my $items='';
 6759:    foreach my $item (@$storearr) {
 6760:        $items.=&escape($item).'&';
 6761:    }
 6762:    $items=~s/\&$//;
 6763:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6764:    if (!$uname) { $uname=$env{'user.name'}; }
 6765:    my $uhome=&homeserver($uname,$udomain);
 6766:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6767:    my @pairs=split(/\&/,$rep);
 6768:    my %returnhash=();
 6769:    my $i=0;
 6770:    foreach my $item (@$storearr) {
 6771:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6772:       $i++;
 6773:    }
 6774:    return %returnhash;
 6775: }
 6776: 
 6777: # ------------------------------------------------------------ tmpput interface
 6778: sub tmpput {
 6779:     my ($storehash,$server,$context)=@_;
 6780:     my $items='';
 6781:     foreach my $item (keys(%$storehash)) {
 6782: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6783:     }
 6784:     $items=~s/\&$//;
 6785:     if (defined($context)) {
 6786:         $items .= ':'.&escape($context);
 6787:     }
 6788:     return &reply("tmpput:$items",$server);
 6789: }
 6790: 
 6791: # ------------------------------------------------------------ tmpget interface
 6792: sub tmpget {
 6793:     my ($token,$server)=@_;
 6794:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6795:     my $rep=&reply("tmpget:$token",$server);
 6796:     my %returnhash;
 6797:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6798:         return %returnhash;
 6799:     }
 6800:     foreach my $item (split(/\&/,$rep)) {
 6801: 	my ($key,$value)=split(/=/,$item);
 6802: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6803:     }
 6804:     return %returnhash;
 6805: }
 6806: 
 6807: # ------------------------------------------------------------ tmpdel interface
 6808: sub tmpdel {
 6809:     my ($token,$server)=@_;
 6810:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6811:     return &reply("tmpdel:$token",$server);
 6812: }
 6813: 
 6814: # ------------------------------------------------------------ get_timebased_id 
 6815: 
 6816: sub get_timebased_id {
 6817:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6818:         $maxtries) = @_;
 6819:     my ($newid,$error,$dellock);
 6820:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6821:         return ('','ok','invalid call to get suffix');
 6822:     }
 6823: 
 6824: # set defaults for any optional args for which values were not supplied
 6825:     if ($who eq '') {
 6826:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6827:     }
 6828:     if (!$locktries) {
 6829:         $locktries = 3;
 6830:     }
 6831:     if (!$maxtries) {
 6832:         $maxtries = 10;
 6833:     }
 6834:     
 6835:     if (($cdom eq '') || ($cnum eq '')) {
 6836:         if ($env{'request.course.id'}) {
 6837:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6838:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6839:         }
 6840:         if (($cdom eq '') || ($cnum eq '')) {
 6841:             return ('','ok','call to get suffix not in course context');
 6842:         }
 6843:     }
 6844: 
 6845: # construct locking item
 6846:     my $lockhash = {
 6847:                       $prefix."\0".'locked_'.$keyid => $who,
 6848:                    };
 6849:     my $tries = 0;
 6850: 
 6851: # attempt to get lock on nohist_$namespace file
 6852:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6853:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6854:         $tries ++;
 6855:         sleep 1;
 6856:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6857:     }
 6858: 
 6859: # attempt to get unique identifier, based on current timestamp
 6860:     if ($gotlock eq 'ok') {
 6861:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6862:         my $id = time;
 6863:         $newid = $id;
 6864:         if ($idtype eq 'addcode') {
 6865:             $newid .= &sixnum_code();
 6866:         }
 6867:         my $idtries = 0;
 6868:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6869:             if ($idtype eq 'concat') {
 6870:                 $newid = $id.$idtries;
 6871:             } elsif ($idtype eq 'addcode') {
 6872:                 $newid = $newid.&sixnum_code();
 6873:             } else {
 6874:                 $newid ++;
 6875:             }
 6876:             $idtries ++;
 6877:         }
 6878:         if (!exists($inuse{$prefix."\0".$newid})) {
 6879:             my %new_item =  (
 6880:                               $prefix."\0".$newid => $who,
 6881:                             );
 6882:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6883:                                                  $cdom,$cnum);
 6884:             if ($putresult ne 'ok') {
 6885:                 undef($newid);
 6886:                 $error = 'error saving new item: '.$putresult;
 6887:             }
 6888:         } else {
 6889:              undef($newid);
 6890:              $error = ('error: no unique suffix available for the new item ');
 6891:         }
 6892: #  remove lock
 6893:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6894:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6895:     } else {
 6896:         $error = "error: could not obtain lockfile\n";
 6897:         $dellock = 'ok';
 6898:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6899:             $dellock = 'nolock';
 6900:         }
 6901:     }
 6902:     return ($newid,$dellock,$error);
 6903: }
 6904: 
 6905: sub sixnum_code {
 6906:     my $code;
 6907:     for (0..6) {
 6908:         $code .= int( rand(9) );
 6909:     }
 6910:     return $code;
 6911: }
 6912: 
 6913: # -------------------------------------------------- portfolio access checking
 6914: 
 6915: sub portfolio_access {
 6916:     my ($requrl,$clientip) = @_;
 6917:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6918:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6919:     if ($result) {
 6920:         my %setters;
 6921:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6922:             my ($startblock,$endblock) =
 6923:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6924:             if ($startblock && $endblock) {
 6925:                 return 'B';
 6926:             }
 6927:         } else {
 6928:             my ($startblock,$endblock) =
 6929:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6930:             if ($startblock && $endblock) {
 6931:                 return 'B';
 6932:             }
 6933:         }
 6934:     }
 6935:     if ($result eq 'ok') {
 6936:        return 'F';
 6937:     } elsif ($result =~ /^[^:]+:guest_/) {
 6938:        return 'A';
 6939:     }
 6940:     return '';
 6941: }
 6942: 
 6943: sub get_portfolio_access {
 6944:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6945: 
 6946:     if (!ref($access_hash)) {
 6947: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6948: 	my %access_controls = &get_access_controls($current_perms,$group,
 6949: 						   $file_name);
 6950: 	$access_hash = $access_controls{$file_name};
 6951:     }
 6952: 
 6953:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6954:     my $now = time;
 6955:     if (ref($access_hash) eq 'HASH') {
 6956:         foreach my $key (keys(%{$access_hash})) {
 6957:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6958:             if ($start > $now) {
 6959:                 next;
 6960:             }
 6961:             if ($end && $end<$now) {
 6962:                 next;
 6963:             }
 6964:             if ($scope eq 'public') {
 6965:                 $public = $key;
 6966:                 last;
 6967:             } elsif ($scope eq 'guest') {
 6968:                 $guest = $key;
 6969:             } elsif ($scope eq 'domains') {
 6970:                 push(@domains,$key);
 6971:             } elsif ($scope eq 'users') {
 6972:                 push(@users,$key);
 6973:             } elsif ($scope eq 'course') {
 6974:                 push(@courses,$key);
 6975:             } elsif ($scope eq 'group') {
 6976:                 push(@groups,$key);
 6977:             } elsif ($scope eq 'ip') {
 6978:                 push(@ips,$key);
 6979:             }
 6980:         }
 6981:         if ($public) {
 6982:             return 'ok';
 6983:         } elsif (@ips > 0) {
 6984:             my $allowed;
 6985:             foreach my $ipkey (@ips) {
 6986:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6987:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6988:                         $allowed = 1;
 6989:                         last; 
 6990:                     }
 6991:                 }
 6992:             }
 6993:             if ($allowed) {
 6994:                 return 'ok';
 6995:             }
 6996:         }
 6997:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6998:             if ($guest) {
 6999:                 return $guest;
 7000:             }
 7001:         } else {
 7002:             if (@domains > 0) {
 7003:                 foreach my $domkey (@domains) {
 7004:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7005:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7006:                             return 'ok';
 7007:                         }
 7008:                     }
 7009:                 }
 7010:             }
 7011:             if (@users > 0) {
 7012:                 foreach my $userkey (@users) {
 7013:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7014:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7015:                             if (ref($item) eq 'HASH') {
 7016:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7017:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7018:                                     return 'ok';
 7019:                                 }
 7020:                             }
 7021:                         }
 7022:                     } 
 7023:                 }
 7024:             }
 7025:             my %roleshash;
 7026:             my @courses_and_groups = @courses;
 7027:             push(@courses_and_groups,@groups); 
 7028:             if (@courses_and_groups > 0) {
 7029:                 my (%allgroups,%allroles); 
 7030:                 my ($start,$end,$role,$sec,$group);
 7031:                 foreach my $envkey (%env) {
 7032:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7033:                         my $cid = $2.'_'.$3; 
 7034:                         if ($1 eq 'gr') {
 7035:                             $group = $4;
 7036:                             $allgroups{$cid}{$group} = $env{$envkey};
 7037:                         } else {
 7038:                             if ($4 eq '') {
 7039:                                 $sec = 'none';
 7040:                             } else {
 7041:                                 $sec = $4;
 7042:                             }
 7043:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7044:                         }
 7045:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7046:                         my $cid = $2.'_'.$3;
 7047:                         if ($4 eq '') {
 7048:                             $sec = 'none';
 7049:                         } else {
 7050:                             $sec = $4;
 7051:                         }
 7052:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7053:                     }
 7054:                 }
 7055:                 if (keys(%allroles) == 0) {
 7056:                     return;
 7057:                 }
 7058:                 foreach my $key (@courses_and_groups) {
 7059:                     my %content = %{$$access_hash{$key}};
 7060:                     my $cnum = $content{'number'};
 7061:                     my $cdom = $content{'domain'};
 7062:                     my $cid = $cdom.'_'.$cnum;
 7063:                     if (!exists($allroles{$cid})) {
 7064:                         next;
 7065:                     }    
 7066:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7067:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7068:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7069:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7070:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7071:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7072:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7073:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7074:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7075:                                         if (grep/^all$/,@sections) {
 7076:                                             return 'ok';
 7077:                                         } else {
 7078:                                             if (grep/^$sec$/,@sections) {
 7079:                                                 return 'ok';
 7080:                                             }
 7081:                                         }
 7082:                                     }
 7083:                                 }
 7084:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7085:                                     if (grep/^none$/,@groups) {
 7086:                                         return 'ok';
 7087:                                     }
 7088:                                 } else {
 7089:                                     if (grep/^all$/,@groups) {
 7090:                                         return 'ok';
 7091:                                     } 
 7092:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7093:                                         if (grep/^$group$/,@groups) {
 7094:                                             return 'ok';
 7095:                                         }
 7096:                                     }
 7097:                                 } 
 7098:                             }
 7099:                         }
 7100:                     }
 7101:                 }
 7102:             }
 7103:             if ($guest) {
 7104:                 return $guest;
 7105:             }
 7106:         }
 7107:     }
 7108:     return;
 7109: }
 7110: 
 7111: sub course_group_datechecker {
 7112:     my ($dates,$now,$status) = @_;
 7113:     my ($start,$end) = split(/\./,$dates);
 7114:     if (!$start && !$end) {
 7115:         return 'ok';
 7116:     }
 7117:     if (grep/^active$/,@{$status}) {
 7118:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7119:             return 'ok';
 7120:         }
 7121:     }
 7122:     if (grep/^previous$/,@{$status}) {
 7123:         if ($end > $now ) {
 7124:             return 'ok';
 7125:         }
 7126:     }
 7127:     if (grep/^future$/,@{$status}) {
 7128:         if ($start > $now) {
 7129:             return 'ok';
 7130:         }
 7131:     }
 7132:     return; 
 7133: }
 7134: 
 7135: sub parse_portfolio_url {
 7136:     my ($url) = @_;
 7137: 
 7138:     my ($type,$udom,$unum,$group,$file_name);
 7139:     
 7140:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7141: 	$type = 1;
 7142:         $udom = $1;
 7143:         $unum = $2;
 7144:         $file_name = $3;
 7145:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7146: 	$type = 2;
 7147:         $udom = $1;
 7148:         $unum = $2;
 7149:         $group = $3;
 7150:         $file_name = $3.'/'.$4;
 7151:     }
 7152:     if (wantarray) {
 7153: 	return ($type,$udom,$unum,$file_name,$group);
 7154:     }
 7155:     return $type;
 7156: }
 7157: 
 7158: sub is_portfolio_url {
 7159:     my ($url) = @_;
 7160:     return scalar(&parse_portfolio_url($url));
 7161: }
 7162: 
 7163: sub is_portfolio_file {
 7164:     my ($file) = @_;
 7165:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7166:         return 1;
 7167:     }
 7168:     return;
 7169: }
 7170: 
 7171: sub usertools_access {
 7172:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7173:     my ($access,%tools);
 7174:     if ($context eq '') {
 7175:         $context = 'tools';
 7176:     }
 7177:     if ($context eq 'requestcourses') {
 7178:         %tools = (
 7179:                       official   => 1,
 7180:                       unofficial => 1,
 7181:                       community  => 1,
 7182:                       textbook   => 1,
 7183:                       placement  => 1,
 7184:                       lti        => 1,
 7185:                  );
 7186:     } elsif ($context eq 'requestauthor') {
 7187:         %tools = (
 7188:                       requestauthor => 1,
 7189:                  );
 7190:     } else {
 7191:         %tools = (
 7192:                       aboutme   => 1,
 7193:                       blog      => 1,
 7194:                       webdav    => 1,
 7195:                       portfolio => 1,
 7196:                  );
 7197:     }
 7198:     return if (!defined($tools{$tool}));
 7199: 
 7200:     if (($udom eq '') || ($uname eq '')) {
 7201:         $udom = $env{'user.domain'};
 7202:         $uname = $env{'user.name'};
 7203:     }
 7204: 
 7205:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7206:         if ($action ne 'reload') {
 7207:             if ($context eq 'requestcourses') {
 7208:                 return $env{'environment.canrequest.'.$tool};
 7209:             } elsif ($context eq 'requestauthor') {
 7210:                 return $env{'environment.canrequest.author'};
 7211:             } else {
 7212:                 return $env{'environment.availabletools.'.$tool};
 7213:             }
 7214:         }
 7215:     }
 7216: 
 7217:     my ($toolstatus,$inststatus,$envkey);
 7218:     if ($context eq 'requestauthor') {
 7219:         $envkey = $context; 
 7220:     } else {
 7221:         $envkey = $context.'.'.$tool;
 7222:     }
 7223: 
 7224:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7225:          ($action ne 'reload')) {
 7226:         $toolstatus = $env{'environment.'.$envkey};
 7227:         $inststatus = $env{'environment.inststatus'};
 7228:     } else {
 7229:         if (ref($userenvref) eq 'HASH') {
 7230:             $toolstatus = $userenvref->{$envkey};
 7231:             $inststatus = $userenvref->{'inststatus'};
 7232:         } else {
 7233:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7234:             $toolstatus = $userenv{$envkey};
 7235:             $inststatus = $userenv{'inststatus'};
 7236:         }
 7237:     }
 7238: 
 7239:     if ($toolstatus ne '') {
 7240:         if ($toolstatus) {
 7241:             $access = 1;
 7242:         } else {
 7243:             $access = 0;
 7244:         }
 7245:         return $access;
 7246:     }
 7247: 
 7248:     my ($is_adv,%domdef);
 7249:     if (ref($is_advref) eq 'HASH') {
 7250:         $is_adv = $is_advref->{'is_adv'};
 7251:     } else {
 7252:         $is_adv = &is_advanced_user($udom,$uname);
 7253:     }
 7254:     if (ref($domdefref) eq 'HASH') {
 7255:         %domdef = %{$domdefref};
 7256:     } else {
 7257:         %domdef = &get_domain_defaults($udom);
 7258:     }
 7259:     if (ref($domdef{$tool}) eq 'HASH') {
 7260:         if ($is_adv) {
 7261:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7262:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7263:                     $access = 1;
 7264:                 } else {
 7265:                     $access = 0;
 7266:                 }
 7267:                 return $access;
 7268:             }
 7269:         }
 7270:         if ($inststatus ne '') {
 7271:             my ($hasaccess,$hasnoaccess);
 7272:             foreach my $affiliation (split(/:/,$inststatus)) {
 7273:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7274:                     if ($domdef{$tool}{$affiliation}) {
 7275:                         $hasaccess = 1;
 7276:                     } else {
 7277:                         $hasnoaccess = 1;
 7278:                     }
 7279:                 }
 7280:             }
 7281:             if ($hasaccess || $hasnoaccess) {
 7282:                 if ($hasaccess) {
 7283:                     $access = 1;
 7284:                 } elsif ($hasnoaccess) {
 7285:                     $access = 0; 
 7286:                 }
 7287:                 return $access;
 7288:             }
 7289:         } else {
 7290:             if ($domdef{$tool}{'default'} ne '') {
 7291:                 if ($domdef{$tool}{'default'}) {
 7292:                     $access = 1;
 7293:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7294:                     $access = 0;
 7295:                 }
 7296:                 return $access;
 7297:             }
 7298:         }
 7299:     } else {
 7300:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7301:             $access = 1;
 7302:         } else {
 7303:             $access = 0;
 7304:         }
 7305:         return $access;
 7306:     }
 7307: }
 7308: 
 7309: sub is_course_owner {
 7310:     my ($cdom,$cnum,$udom,$uname) = @_;
 7311:     if (($udom eq '') || ($uname eq '')) {
 7312:         $udom = $env{'user.domain'};
 7313:         $uname = $env{'user.name'};
 7314:     }
 7315:     unless (($udom eq '') || ($uname eq '')) {
 7316:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7317:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7318:                 return 1;
 7319:             } else {
 7320:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7321:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7322:                     return 1;
 7323:                 }
 7324:             }
 7325:         }
 7326:     }
 7327:     return;
 7328: }
 7329: 
 7330: sub is_advanced_user {
 7331:     my ($udom,$uname) = @_;
 7332:     if ($udom ne '' && $uname ne '') {
 7333:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7334:             if (wantarray) {
 7335:                 return ($env{'user.adv'},$env{'user.author'});
 7336:             } else {
 7337:                 return $env{'user.adv'};
 7338:             }
 7339:         }
 7340:     }
 7341:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7342:     my %allroles;
 7343:     my ($is_adv,$is_author);
 7344:     foreach my $role (keys(%roleshash)) {
 7345:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7346:         my $area = '/'.$tdomain.'/'.$trest;
 7347:         if ($sec ne '') {
 7348:             $area .= '/'.$sec;
 7349:         }
 7350:         if (($area ne '') && ($trole ne '')) {
 7351:             my $spec=$trole.'.'.$area;
 7352:             if ($trole =~ /^cr\//) {
 7353:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7354:             } elsif ($trole ne 'gr') {
 7355:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7356:             }
 7357:             if ($trole eq 'au') {
 7358:                 $is_author = 1;
 7359:             }
 7360:         }
 7361:     }
 7362:     foreach my $role (keys(%allroles)) {
 7363:         last if ($is_adv);
 7364:         foreach my $item (split(/:/,$allroles{$role})) {
 7365:             if ($item ne '') {
 7366:                 my ($privilege,$restrictions)=split(/&/,$item);
 7367:                 if ($privilege eq 'adv') {
 7368:                     $is_adv = 1;
 7369:                     last;
 7370:                 }
 7371:             }
 7372:         }
 7373:     }
 7374:     if (wantarray) {
 7375:         return ($is_adv,$is_author);
 7376:     }
 7377:     return $is_adv;
 7378: }
 7379: 
 7380: sub check_can_request {
 7381:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7382:     my $canreq = 0;
 7383:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7384:         $uname = $env{'user.name'};
 7385:         $udom = $env{'user.domain'};
 7386:     }
 7387:     my ($types,$typename) = &Apache::loncommon::course_types();
 7388:     my @options = ('approval','validate','autolimit');
 7389:     my $optregex = join('|',@options);
 7390:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7391:         foreach my $type (@{$types}) {
 7392:             if (&usertools_access($uname,$udom,$type,undef,
 7393:                                   'requestcourses')) {
 7394:                 $canreq ++;
 7395:                 if (ref($request_domains) eq 'HASH') {
 7396:                     push(@{$request_domains->{$type}},$udom);
 7397:                 }
 7398:                 if ($dom eq $udom) {
 7399:                     $can_request->{$type} = 1;
 7400:                 }
 7401:             }
 7402:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7403:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7404:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7405:                 if (@curr > 0) {
 7406:                     foreach my $item (@curr) {
 7407:                         if (ref($request_domains) eq 'HASH') {
 7408:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7409:                             if ($otherdom ne '') {
 7410:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7411:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7412:                                         push(@{$request_domains->{$type}},$otherdom);
 7413:                                     }
 7414:                                 } else {
 7415:                                     push(@{$request_domains->{$type}},$otherdom);
 7416:                                 }
 7417:                             }
 7418:                         }
 7419:                     }
 7420:                     unless ($dom eq $env{'user.domain'}) {
 7421:                         $canreq ++;
 7422:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7423:                             $can_request->{$type} = 1;
 7424:                         }
 7425:                     }
 7426:                 }
 7427:             }
 7428:         }
 7429:     }
 7430:     return $canreq;
 7431: }
 7432: 
 7433: # ---------------------------------------------- Custom access rule evaluation
 7434: 
 7435: sub customaccess {
 7436:     my ($priv,$uri)=@_;
 7437:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7438:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7439:     $udom = &LONCAPA::clean_domain($udom);
 7440:     $ucrs = &LONCAPA::clean_username($ucrs);
 7441:     my $access=0;
 7442:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7443: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7444: 	if ($type eq 'user') {
 7445: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7446: 		my ($tdom,$tuname)=split(m{/},$scope);
 7447: 		if ($tdom) {
 7448: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7449: 		}
 7450: 		if ($tuname) {
 7451: 		    if ($tuname ne $env{'user.name'}) { next; }
 7452: 		}
 7453: 		$access=($effect eq 'allow');
 7454: 		last;
 7455: 	    }
 7456: 	} else {
 7457: 	    if ($role) {
 7458: 		if ($role ne $urole) { next; }
 7459: 	    }
 7460: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7461: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7462: 		if ($tdom) {
 7463: 		    if ($tdom ne $udom) { next; }
 7464: 		}
 7465: 		if ($tcrs) {
 7466: 		    if ($tcrs ne $ucrs) { next; }
 7467: 		}
 7468: 		if ($tsec) {
 7469: 		    if ($tsec ne $usec) { next; }
 7470: 		}
 7471: 		$access=($effect eq 'allow');
 7472: 		last;
 7473: 	    }
 7474: 	    if ($realm eq '' && $role eq '') {
 7475: 		$access=($effect eq 'allow');
 7476: 	    }
 7477: 	}
 7478:     }
 7479:     return $access;
 7480: }
 7481: 
 7482: # ------------------------------------------------- Check for a user privilege
 7483: 
 7484: sub allowed {
 7485:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7486:     my $ver_orguri=$uri;
 7487:     $uri=&deversion($uri);
 7488:     my $orguri=$uri;
 7489:     $uri=&declutter($uri);
 7490: 
 7491:     if ($priv eq 'evb') {
 7492: # Evade communication block restrictions for specified role in a course
 7493:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7494:             return $1;
 7495:         } else {
 7496:             return;
 7497:         }
 7498:     }
 7499: 
 7500:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7501: # Free bre access to adm and meta resources
 7502:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7503: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7504: 	&& ($priv eq 'bre')) {
 7505: 	return 'F';
 7506:     }
 7507: 
 7508: # Free bre access to user's own portfolio contents
 7509:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7510:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7511: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7512:         my %setters;
 7513:         my ($startblock,$endblock) = 
 7514:             &Apache::loncommon::blockcheck(\%setters,'port');
 7515:         if ($startblock && $endblock) {
 7516:             return 'B';
 7517:         } else {
 7518:             return 'F';
 7519:         }
 7520:     }
 7521: 
 7522: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7523:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7524:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7525:         if (exists($env{'request.course.id'})) {
 7526:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7527:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7528:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7529:                 my $courseprivid=$env{'request.course.id'};
 7530:                 $courseprivid=~s/\_/\//;
 7531:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7532:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7533:                     return $1; 
 7534:                 } else {
 7535:                     if ($env{'request.course.sec'}) {
 7536:                         $courseprivid.='/'.$env{'request.course.sec'};
 7537:                     }
 7538:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7539:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7540:                         return $2;
 7541:                     }
 7542:                 }
 7543:             }
 7544:         }
 7545:     }
 7546: 
 7547: # Free bre to public access
 7548: 
 7549:     if ($priv eq 'bre') {
 7550:         my $copyright;
 7551:         unless ($uri =~ /ext\.tool/) {
 7552:             $copyright=&metadata($uri,'copyright');
 7553:         }
 7554: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7555:            return 'F'; 
 7556:         }
 7557:         if ($copyright eq 'priv') {
 7558:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7559: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7560: 		return '';
 7561:             }
 7562:         }
 7563:         if ($copyright eq 'domain') {
 7564:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7565: 	    unless (($env{'user.domain'} eq $1) ||
 7566:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7567: 		return '';
 7568:             }
 7569:         }
 7570:         if ($env{'request.role'}=~ /li\.\//) {
 7571:             # Library role, so allow browsing of resources in this domain.
 7572:             return 'F';
 7573:         }
 7574:         if ($copyright eq 'custom') {
 7575: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7576:         }
 7577:     }
 7578:     # Domain coordinator is trying to create a course
 7579:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7580:         # uri is the requested domain in this case.
 7581:         # comparison to 'request.role.domain' shows if the user has selected
 7582:         # a role of dc for the domain in question.
 7583:         return 'F' if ($uri eq $env{'request.role.domain'});
 7584:     }
 7585: 
 7586:     my $thisallowed='';
 7587:     my $statecond=0;
 7588:     my $courseprivid='';
 7589: 
 7590:     my $ownaccess;
 7591:     # Community Coordinator or Assistant Co-author browsing resource space.
 7592:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7593:         if ($uri eq '') {
 7594:             $ownaccess = 1;
 7595:         } else {
 7596:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7597:                 my $udom = $env{'user.domain'};
 7598:                 my $uname = $env{'user.name'};
 7599:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7600:                     $ownaccess = 1;
 7601:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7602:                     unless ($uri =~ m{\.\./}) {
 7603:                         $ownaccess = 1;
 7604:                     }
 7605:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7606:                     my $now = time;
 7607:                     if ($uri =~ m{^([^/]+)/?$}) {
 7608:                         my $adom = $1;
 7609:                         foreach my $key (keys(%env)) {
 7610:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7611:                                 my ($start,$end) = split('.',$env{$key});
 7612:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7613:                                     $ownaccess = 1;
 7614:                                     last;
 7615:                                 }
 7616:                             }
 7617:                         }
 7618:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7619:                         my $adom = $1;
 7620:                         my $aname = $2;
 7621:                         foreach my $role ('ca','aa') { 
 7622:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7623:                                 my ($start,$end) =
 7624:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7625:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7626:                                     $ownaccess = 1;
 7627:                                     last;
 7628:                                 }
 7629:                             }
 7630:                         }
 7631:                     }
 7632:                 }
 7633:             }
 7634:         }
 7635:     }
 7636: 
 7637: # Course
 7638: 
 7639:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7640:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7641:             $thisallowed.=$1;
 7642:         }
 7643:     }
 7644: 
 7645: # Domain
 7646: 
 7647:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7648:        =~/\Q$priv\E\&([^\:]*)/) {
 7649:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7650:             $thisallowed.=$1;
 7651:         }
 7652:     }
 7653: 
 7654: # User who is not author or co-author might still be able to edit
 7655: # resource of an author in the domain (e.g., if Domain Coordinator).
 7656:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7657:         (&allowed('mdc',$env{'request.course.id'}))) {
 7658:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7659:             $thisallowed.=$1;
 7660:         }
 7661:     }
 7662: 
 7663: # Course: uri itself is a course
 7664:     my $courseuri=$uri;
 7665:     $courseuri=~s/\_(\d)/\/$1/;
 7666:     $courseuri=~s/^([^\/])/\/$1/;
 7667: 
 7668:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7669:        =~/\Q$priv\E\&([^\:]*)/) {
 7670:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7671:             $thisallowed.=$1;
 7672:         }
 7673:     }
 7674: 
 7675: # URI is an uploaded document for this course, default permissions don't matter
 7676: # not allowing 'edit' access (editupload) to uploaded course docs
 7677:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7678: 	$thisallowed='';
 7679:         my ($match)=&is_on_map($uri);
 7680:         if ($match) {
 7681:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7682:                   =~/\Q$priv\E\&([^\:]*)/) {
 7683:                 my $value = $1;
 7684:                 if ($noblockcheck) {
 7685:                     $thisallowed.=$value;
 7686:                 } else {
 7687:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7688:                     if (@blockers > 0) {
 7689:                         $thisallowed = 'B';
 7690:                     } else {
 7691:                         $thisallowed.=$value;
 7692:                     }
 7693:                 }
 7694:             }
 7695:         } else {
 7696:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7697:             if ($refuri) {
 7698:                 if ($refuri =~ m|^/adm/|) {
 7699:                     $thisallowed='F';
 7700:                 } else {
 7701:                     $refuri=&declutter($refuri);
 7702:                     my ($match) = &is_on_map($refuri);
 7703:                     if ($match) {
 7704:                         if ($noblockcheck) {
 7705:                             $thisallowed='F';
 7706:                         } else {
 7707:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7708:                             if (@blockers > 0) {
 7709:                                 $thisallowed = 'B';
 7710:                             } else {
 7711:                                 $thisallowed='F';
 7712:                             }
 7713:                         }
 7714:                     }
 7715:                 }
 7716:             }
 7717:         }
 7718:     }
 7719: 
 7720:     if ($priv eq 'bre'
 7721: 	&& $thisallowed ne 'F' 
 7722: 	&& $thisallowed ne '2'
 7723: 	&& &is_portfolio_url($uri)) {
 7724: 	$thisallowed = &portfolio_access($uri,$clientip);
 7725:     }
 7726: 
 7727: # Full access at system, domain or course-wide level? Exit.
 7728:     if ($thisallowed=~/F/) {
 7729: 	return 'F';
 7730:     }
 7731: 
 7732: # If this is generating or modifying users, exit with special codes
 7733: 
 7734:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7735: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7736: 	    my ($audom,$auname)=split('/',$uri);
 7737: # no author name given, so this just checks on the general right to make a co-author in this domain
 7738: 	    unless ($auname) { return $thisallowed; }
 7739: # an author name is given, so we are about to actually make a co-author for a certain account
 7740: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7741: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7742: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7743: 	}
 7744: 	return $thisallowed;
 7745:     }
 7746: #
 7747: # Gathered so far: system, domain and course wide privileges
 7748: #
 7749: # Course: See if uri or referer is an individual resource that is part of 
 7750: # the course
 7751: 
 7752:     if ($env{'request.course.id'}) {
 7753: 
 7754:        $courseprivid=$env{'request.course.id'};
 7755:        if ($env{'request.course.sec'}) {
 7756:           $courseprivid.='/'.$env{'request.course.sec'};
 7757:        }
 7758:        $courseprivid=~s/\_/\//;
 7759:        my $checkreferer=1;
 7760:        my ($match,$cond)=&is_on_map($uri);
 7761:        if ($match) {
 7762:            $statecond=$cond;
 7763:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7764:                =~/\Q$priv\E\&([^\:]*)/) {
 7765:                my $value = $1;
 7766:                if ($priv eq 'bre') {
 7767:                    if ($noblockcheck) {
 7768:                        $thisallowed.=$value;
 7769:                    } else {
 7770:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7771:                        if (@blockers > 0) {
 7772:                            $thisallowed = 'B';
 7773:                        } else {
 7774:                            $thisallowed.=$value;
 7775:                        }
 7776:                    }
 7777:                } else {
 7778:                    $thisallowed.=$value;
 7779:                }
 7780:                $checkreferer=0;
 7781:            }
 7782:        }
 7783:        
 7784:        if ($checkreferer) {
 7785: 	  my $refuri=$env{'httpref.'.$orguri};
 7786:             unless ($refuri) {
 7787:                 foreach my $key (keys(%env)) {
 7788: 		    if ($key=~/^httpref\..*\*/) {
 7789: 			my $pattern=$key;
 7790:                         $pattern=~s/^httpref\.\/res\///;
 7791:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7792:                         $pattern=~s/\//\\\//g;
 7793:                         if ($orguri=~/$pattern/) {
 7794: 			    $refuri=$env{$key};
 7795:                         }
 7796:                     }
 7797:                 }
 7798:             }
 7799: 
 7800:          if ($refuri) { 
 7801: 	  $refuri=&declutter($refuri);
 7802:           my ($match,$cond)=&is_on_map($refuri);
 7803:             if ($match) {
 7804:               my $refstatecond=$cond;
 7805:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7806:                   =~/\Q$priv\E\&([^\:]*)/) {
 7807:                   my $value = $1;
 7808:                   if ($priv eq 'bre') {
 7809:                       if ($noblockcheck) {
 7810:                           $thisallowed.=$value;
 7811:                       } else {
 7812:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7813:                           if (@blockers > 0) {
 7814:                               $thisallowed = 'B';
 7815:                           } else {
 7816:                               $thisallowed.=$value;
 7817:                           }
 7818:                       }
 7819:                   } else {
 7820:                       $thisallowed.=$value;
 7821:                   }
 7822:                   $uri=$refuri;
 7823:                   $statecond=$refstatecond;
 7824:               }
 7825:           }
 7826:         }
 7827:        }
 7828:    }
 7829: 
 7830: #
 7831: # Gathered now: all privileges that could apply, and condition number
 7832: # 
 7833: #
 7834: # Full or no access?
 7835: #
 7836: 
 7837:     if ($thisallowed=~/F/) {
 7838: 	return 'F';
 7839:     }
 7840: 
 7841:     unless ($thisallowed) {
 7842:         return '';
 7843:     }
 7844: 
 7845: # Restrictions exist, deal with them
 7846: #
 7847: #   C:according to course preferences
 7848: #   R:according to resource settings
 7849: #   L:unless locked
 7850: #   X:according to user session state
 7851: #
 7852: 
 7853: # Possibly locked functionality, check all courses
 7854: # Locks might take effect only after 10 minutes cache expiration for other
 7855: # courses, and 2 minutes for current course
 7856: 
 7857:     my $envkey;
 7858:     if ($thisallowed=~/L/) {
 7859:         foreach $envkey (keys(%env)) {
 7860:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7861:                my $courseid=$2;
 7862:                my $roleid=$1.'.'.$2;
 7863:                $courseid=~s/^\///;
 7864:                my $expiretime=600;
 7865:                if ($env{'request.role'} eq $roleid) {
 7866: 		  $expiretime=120;
 7867:                }
 7868: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7869:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7870:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7871: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7872:                }
 7873:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7874:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7875: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7876:                        &log($env{'user.domain'},$env{'user.name'},
 7877:                             $env{'user.home'},
 7878:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7879:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7880:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7881: 		       return '';
 7882:                    }
 7883:                }
 7884:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7885:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7886: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7887:                        &log($env{'user.domain'},$env{'user.name'},
 7888:                             $env{'user.home'},
 7889:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7890:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7891:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7892: 		       return '';
 7893:                    }
 7894:                }
 7895: 	   }
 7896:        }
 7897:     }
 7898:    
 7899: #
 7900: # Rest of the restrictions depend on selected course
 7901: #
 7902: 
 7903:     unless ($env{'request.course.id'}) {
 7904: 	if ($thisallowed eq 'A') {
 7905: 	    return 'A';
 7906:         } elsif ($thisallowed eq 'B') {
 7907:             return 'B';
 7908: 	} else {
 7909: 	    return '1';
 7910: 	}
 7911:     }
 7912: 
 7913: #
 7914: # Now user is definitely in a course
 7915: #
 7916: 
 7917: 
 7918: # Course preferences
 7919: 
 7920:    if ($thisallowed=~/C/) {
 7921:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7922:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7923:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7924: 	   =~/\Q$rolecode\E/) {
 7925: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7926: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7927: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7928: 			$env{'request.course.id'});
 7929: 	   }
 7930:            return '';
 7931:        }
 7932: 
 7933:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7934: 	   =~/\Q$unamedom\E/) {
 7935: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7936: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7937: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7938: 			$env{'request.course.id'});
 7939: 	   }
 7940:            return '';
 7941:        }
 7942:    }
 7943: 
 7944: # Resource preferences
 7945: 
 7946:    if ($thisallowed=~/R/) {
 7947:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7948:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7949: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7950: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7951: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7952: 	   }
 7953: 	   return '';
 7954:        }
 7955:    }
 7956: 
 7957: # Restricted by state or randomout?
 7958: 
 7959:    if ($thisallowed=~/X/) {
 7960:       if ($env{'acc.randomout'}) {
 7961: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7962:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7963:             return ''; 
 7964:          }
 7965:       }
 7966:       if (&condval($statecond)) {
 7967: 	 return '2';
 7968:       } else {
 7969:          return '';
 7970:       }
 7971:    }
 7972: 
 7973:     if ($thisallowed eq 'A') {
 7974: 	return 'A';
 7975:     } elsif ($thisallowed eq 'B') {
 7976:         return 'B';
 7977:     }
 7978:    return 'F';
 7979: }
 7980: 
 7981: # ------------------------------------------- Check construction space access
 7982: 
 7983: sub constructaccess {
 7984:     my ($url,$setpriv)=@_;
 7985: 
 7986: # We do not allow editing of previous versions of files
 7987:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7988: 
 7989: # Get username and domain from URL
 7990:     my ($ownername,$ownerdomain,$ownerhome);
 7991: 
 7992:     ($ownerdomain,$ownername) =
 7993:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 7994: 
 7995: # The URL does not really point to any authorspace, forget it
 7996:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7997: 
 7998: # Now we need to see if the user has access to the authorspace of
 7999: # $ownername at $ownerdomain
 8000: 
 8001:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8002: # Real author for this?
 8003:        $ownerhome = $env{'user.home'};
 8004:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8005:           return ($ownername,$ownerdomain,$ownerhome);
 8006:        }
 8007:     } else {
 8008: # Co-author for this?
 8009:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8010:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8011:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8012:             return ($ownername,$ownerdomain,$ownerhome);
 8013:         }
 8014:         if ($env{'request.course.id'}) {
 8015:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8016:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8017:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8018:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8019:                     return ($ownername,$ownerdomain,$ownerhome);
 8020:                 }
 8021:             }
 8022:         }
 8023:     }
 8024: 
 8025: # We don't have any access right now. If we are not possibly going to do anything about this,
 8026: # we might as well leave
 8027:    unless ($setpriv) { return ''; }
 8028: 
 8029: # Backdoor access?
 8030:     my $allowed=&allowed('eco',$ownerdomain);
 8031: # Nope
 8032:     unless ($allowed) { return ''; }
 8033: # Looks like we may have access, but could be locked by the owner of the construction space
 8034:     if ($allowed eq 'U') {
 8035:         my %blocked=&get('environment',['domcoord.author'],
 8036:                          $ownerdomain,$ownername);
 8037: # Is blocked by owner
 8038:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8039:     }
 8040:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8041: # Grant temporary access
 8042:         my $then=$env{'user.login.time'};
 8043:         my $update=$env{'user.update.time'};
 8044:         if (!$update) { $update = $then; }
 8045:         my $refresh=$env{'user.refresh.time'};
 8046:         if (!$refresh) { $refresh = $update; }
 8047:         my $now = time;
 8048:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8049:                            $now,'ca','constructaccess');
 8050:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8051:         return($ownername,$ownerdomain,$ownerhome);
 8052:     }
 8053: # No business here
 8054:     return '';
 8055: }
 8056: 
 8057: # ----------------------------------------------------------- Content Blocking
 8058: 
 8059: {
 8060: # Caches for faster Course Contents display where content blocking
 8061: # is in operation (i.e., interval param set) for timed quiz.
 8062: #
 8063: # User for whom data are being temporarily cached.
 8064: my $cacheduser='';
 8065: # Cached blockers for this user (a hash of blocking items). 
 8066: my %cachedblockers=();
 8067: # When the data were last cached.
 8068: my $cachedlast='';
 8069: 
 8070: sub load_all_blockers {
 8071:     my ($uname,$udom,$blocks)=@_;
 8072:     if (($uname ne '') && ($udom ne '')) { 
 8073:         if (($cacheduser eq $uname.':'.$udom) &&
 8074:             (abs($cachedlast-time)<5)) {
 8075:             return;
 8076:         }
 8077:     }
 8078:     $cachedlast=time;
 8079:     $cacheduser=$uname.':'.$udom;
 8080:     %cachedblockers = &get_commblock_resources($blocks);
 8081: }
 8082: 
 8083: sub get_comm_blocks {
 8084:     my ($cdom,$cnum) = @_;
 8085:     if ($cdom eq '' || $cnum eq '') {
 8086:         return unless ($env{'request.course.id'});
 8087:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8088:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8089:     }
 8090:     my %commblocks;
 8091:     my $hashid=$cdom.'_'.$cnum;
 8092:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8093:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8094:         %commblocks = %{$blocksref};
 8095:     } else {
 8096:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8097:         my $cachetime = 600;
 8098:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8099:     }
 8100:     return %commblocks;
 8101: }
 8102: 
 8103: sub get_commblock_resources {
 8104:     my ($blocks) = @_;
 8105:     my %blockers = ();
 8106:     return %blockers unless ($env{'request.course.id'});
 8107:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8108:     my %commblocks;
 8109:     if (ref($blocks) eq 'HASH') {
 8110:         %commblocks = %{$blocks};
 8111:     } else {
 8112:         %commblocks = &get_comm_blocks();
 8113:     }
 8114:     return %blockers unless (keys(%commblocks) > 0); 
 8115:     my $navmap = Apache::lonnavmaps::navmap->new();
 8116:     return %blockers unless (ref($navmap));
 8117:     my $now = time;
 8118:     foreach my $block (keys(%commblocks)) {
 8119:         if ($block =~ /^(\d+)____(\d+)$/) {
 8120:             my ($start,$end) = ($1,$2);
 8121:             if ($start <= $now && $end >= $now) {
 8122:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8123:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8124:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8125:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8126:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8127:                             }
 8128:                         }
 8129:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8130:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8131:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8132:                             }
 8133:                         }
 8134:                     }
 8135:                 }
 8136:             }
 8137:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8138:             my $item = $1;
 8139:             my @to_test;
 8140:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8141:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8142:                     my @interval;
 8143:                     my $type = 'map';
 8144:                     if ($item eq 'course') {
 8145:                         $type = 'course';
 8146:                         @interval=&EXT("resource.0.interval");
 8147:                     } else {
 8148:                         if ($item =~ /___\d+___/) {
 8149:                             $type = 'resource';
 8150:                             @interval=&EXT("resource.0.interval",$item);
 8151:                             if (ref($navmap)) {                        
 8152:                                 my $res = $navmap->getBySymb($item); 
 8153:                                 push(@to_test,$res);
 8154:                             }
 8155:                         } else {
 8156:                             my $mapsymb = &symbread($item,1);
 8157:                             if ($mapsymb) {
 8158:                                 if (ref($navmap)) {
 8159:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8160:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8161:                                     foreach my $res (@to_test) {
 8162:                                         my $symb = $res->symb();
 8163:                                         next if ($symb eq $mapsymb);
 8164:                                         if ($symb ne '') {
 8165:                                             @interval=&EXT("resource.0.interval",$symb);
 8166:                                             if ($interval[1] eq 'map') {
 8167:                                                 last;
 8168:                                             }
 8169:                                         }
 8170:                                     }
 8171:                                 }
 8172:                             }
 8173:                         }
 8174:                     }
 8175:                     if ($interval[0] =~ /^(\d+)/) {
 8176:                         my $timelimit = $1; 
 8177:                         my $first_access;
 8178:                         if ($type eq 'resource') {
 8179:                             $first_access=&get_first_access($interval[1],$item);
 8180:                         } elsif ($type eq 'map') {
 8181:                             $first_access=&get_first_access($interval[1],undef,$item);
 8182:                         } else {
 8183:                             $first_access=&get_first_access($interval[1]);
 8184:                         }
 8185:                         if ($first_access) {
 8186:                             my $timesup = $first_access+$timelimit;
 8187:                             if ($timesup > $now) {
 8188:                                 my $activeblock;
 8189:                                 foreach my $res (@to_test) {
 8190:                                     if ($res->answerable()) {
 8191:                                         $activeblock = 1;
 8192:                                         last;
 8193:                                     }
 8194:                                 }
 8195:                                 if ($activeblock) {
 8196:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8197:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8198:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8199:                                          }
 8200:                                     }
 8201:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8202:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8203:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8204:                                         }
 8205:                                     }
 8206:                                 }
 8207:                             }
 8208:                         }
 8209:                     }
 8210:                 }
 8211:             }
 8212:         }
 8213:     }
 8214:     return %blockers;
 8215: }
 8216: 
 8217: sub has_comm_blocking {
 8218:     my ($priv,$symb,$uri,$blocks) = @_;
 8219:     my @blockers;
 8220:     return unless ($env{'request.course.id'});
 8221:     return unless ($priv eq 'bre');
 8222:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8223:     return if ($env{'request.state'} eq 'construct');
 8224:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8225:     return unless (keys(%cachedblockers) > 0);
 8226:     my (%possibles,@symbs);
 8227:     if (!$symb) {
 8228:         $symb = &symbread($uri,1,1,1,\%possibles);
 8229:     }
 8230:     if ($symb) {
 8231:         @symbs = ($symb);
 8232:     } elsif (keys(%possibles)) { 
 8233:         @symbs = keys(%possibles);
 8234:     }
 8235:     my $noblock;
 8236:     foreach my $symb (@symbs) {
 8237:         last if ($noblock);
 8238:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8239:         foreach my $block (keys(%cachedblockers)) {
 8240:             if ($block =~ /^firstaccess____(.+)$/) {
 8241:                 my $item = $1;
 8242:                 if (($item eq $map) || ($item eq $symb)) {
 8243:                     $noblock = 1;
 8244:                     last;
 8245:                 }
 8246:             }
 8247:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8248:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8249:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8250:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8251:                             push(@blockers,$block);
 8252:                         }
 8253:                     }
 8254:                 }
 8255:             }
 8256:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8257:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8258:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8259:                         push(@blockers,$block);
 8260:                     }
 8261:                 }
 8262:             }
 8263:         }
 8264:     }
 8265:     return if ($noblock);
 8266:     return @blockers;
 8267: }
 8268: }
 8269: 
 8270: # -------------------------------- Deversion and split uri into path an filename   
 8271: 
 8272: #
 8273: #   Removes the version from a URI and
 8274: #   splits it in to its filename and path to the filename.
 8275: #   Seems like File::Basename could have done this more clearly.
 8276: #   Parameters:
 8277: #      $uri   - input URI
 8278: #   Returns:
 8279: #     Two element list consisting of 
 8280: #     $pathname  - the URI up to and excluding the trailing /
 8281: #     $filename  - The part of the URI following the last /
 8282: #  NOTE:
 8283: #    Another realization of this is simply:
 8284: #    use File::Basename;
 8285: #    ...
 8286: #    $uri = shift;
 8287: #    $filename = basename($uri);
 8288: #    $path     = dirname($uri);
 8289: #    return ($filename, $path);
 8290: #
 8291: #     The implementation below is probably faster however.
 8292: #
 8293: sub split_uri_for_cond {
 8294:     my $uri=&deversion(&declutter(shift));
 8295:     my @uriparts=split(/\//,$uri);
 8296:     my $filename=pop(@uriparts);
 8297:     my $pathname=join('/',@uriparts);
 8298:     return ($pathname,$filename);
 8299: }
 8300: # --------------------------------------------------- Is a resource on the map?
 8301: 
 8302: sub is_on_map {
 8303:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8304:     #Trying to find the conditional for the file
 8305:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8306: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8307:     if ($match) {
 8308: 	return (1,$1);
 8309:     } else {
 8310: 	return (0,0);
 8311:     }
 8312: }
 8313: 
 8314: # --------------------------------------------------------- Get symb from alias
 8315: 
 8316: sub get_symb_from_alias {
 8317:     my $symb=shift;
 8318:     my ($map,$resid,$url)=&decode_symb($symb);
 8319: # Already is a symb
 8320:     if ($url) { return $symb; }
 8321: # Must be an alias
 8322:     my $aliassymb='';
 8323:     my %bighash;
 8324:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8325:                             &GDBM_READER(),0640)) {
 8326:         my $rid=$bighash{'mapalias_'.$symb};
 8327: 	if ($rid) {
 8328: 	    my ($mapid,$resid)=split(/\./,$rid);
 8329: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8330: 				    $resid,$bighash{'src_'.$rid});
 8331: 	}
 8332:         untie %bighash;
 8333:     }
 8334:     return $aliassymb;
 8335: }
 8336: 
 8337: # ----------------------------------------------------------------- Define Role
 8338: 
 8339: sub definerole {
 8340:   if (allowed('mcr','/')) {
 8341:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8342:     foreach my $role (split(':',$sysrole)) {
 8343: 	my ($crole,$cqual)=split(/\&/,$role);
 8344:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8345:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8346: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8347:                return "refused:s:$crole&$cqual"; 
 8348:             }
 8349:         }
 8350:     }
 8351:     foreach my $role (split(':',$domrole)) {
 8352: 	my ($crole,$cqual)=split(/\&/,$role);
 8353:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8354:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8355: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8356:                return "refused:d:$crole&$cqual"; 
 8357:             }
 8358:         }
 8359:     }
 8360:     foreach my $role (split(':',$courole)) {
 8361: 	my ($crole,$cqual)=split(/\&/,$role);
 8362:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8363:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8364: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8365:                return "refused:c:$crole&$cqual"; 
 8366:             }
 8367:         }
 8368:     }
 8369:     my $uhome;
 8370:     if (($uname ne '') && ($udom ne '')) {
 8371:         $uhome = &homeserver($uname,$udom);
 8372:         return $uhome if ($uhome eq 'no_host');
 8373:     } else {
 8374:         $uname = $env{'user.name'};
 8375:         $udom = $env{'user.domain'};
 8376:         $uhome = $env{'user.home'};
 8377:     }
 8378:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8379:                 "$udom:$uname:rolesdef_$rolename=".
 8380:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8381:     return reply($command,$uhome);
 8382:   } else {
 8383:     return 'refused';
 8384:   }
 8385: }
 8386: 
 8387: # ---------------- Make a metadata query against the network of library servers
 8388: 
 8389: sub metadata_query {
 8390:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8391:     my %rhash;
 8392:     my %libserv = &all_library();
 8393:     my @server_list = (defined($server_array) ? @$server_array
 8394:                                               : keys(%libserv) );
 8395:     for my $server (@server_list) {
 8396:         my $domains = ''; 
 8397:         if (ref($domains_hash) eq 'HASH') {
 8398:             $domains = $domains_hash->{$server}; 
 8399:         }
 8400: 	unless ($custom or $customshow) {
 8401: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8402: 	    $rhash{$server}=$reply;
 8403: 	}
 8404: 	else {
 8405: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8406: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8407: 			     $server);
 8408: 	    $rhash{$server}=$reply;
 8409: 	}
 8410:     }
 8411:     return \%rhash;
 8412: }
 8413: 
 8414: # ----------------------------------------- Send log queries and wait for reply
 8415: 
 8416: sub log_query {
 8417:     my ($uname,$udom,$query,%filters)=@_;
 8418:     my $uhome=&homeserver($uname,$udom);
 8419:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8420:     my $uhost=&hostname($uhome);
 8421:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8422:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8423:                        $uhome);
 8424:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8425:     return get_query_reply($queryid);
 8426: }
 8427: 
 8428: # -------------------------- Update MySQL table for portfolio file
 8429: 
 8430: sub update_portfolio_table {
 8431:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8432:     if ($group ne '') {
 8433:         $file_name =~s /^\Q$group\E//;
 8434:     }
 8435:     my $homeserver = &homeserver($uname,$udom);
 8436:     my $queryid=
 8437:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8438:                ':'.&escape($file_name).':'.$action,$homeserver);
 8439:     my $reply = &get_query_reply($queryid);
 8440:     return $reply;
 8441: }
 8442: 
 8443: # -------------------------- Update MySQL allusers table
 8444: 
 8445: sub update_allusers_table {
 8446:     my ($uname,$udom,$names) = @_;
 8447:     my $homeserver = &homeserver($uname,$udom);
 8448:     my $queryid=
 8449:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8450:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8451:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8452:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8453:                'generation='.&escape($names->{'generation'}).'%%'.
 8454:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8455:                'id='.&escape($names->{'id'}),$homeserver);
 8456:     return;
 8457: }
 8458: 
 8459: # ------- Request retrieval of institutional classlists for course(s)
 8460: 
 8461: sub fetch_enrollment_query {
 8462:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8463:     my ($homeserver,$sleep,$loopmax);
 8464:     my $maxtries = 1;
 8465:     if ($context eq 'automated') {
 8466:         $homeserver = $perlvar{'lonHostID'};
 8467:         $sleep = 2;
 8468:         $loopmax = 100;
 8469:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8470:     } else {
 8471:         $homeserver = &homeserver($cnum,$dom);
 8472:     }
 8473:     my $host=&hostname($homeserver);
 8474:     my $cmd = '';
 8475:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8476:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8477:     }
 8478:     $cmd =~ s/%%$//;
 8479:     $cmd = &escape($cmd);
 8480:     my $query = 'fetchenrollment';
 8481:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8482:     unless ($queryid=~/^\Q$host\E\_/) { 
 8483:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8484:         return 'error: '.$queryid;
 8485:     }
 8486:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8487:     my $tries = 1;
 8488:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8489:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8490:         $tries ++;
 8491:     }
 8492:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8493:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8494:     } else {
 8495:         my @responses = split(/:/,$reply);
 8496:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8497:             foreach my $line (@responses) {
 8498:                 my ($key,$value) = split(/=/,$line,2);
 8499:                 $$replyref{$key} = $value;
 8500:             }
 8501:         } else {
 8502:             my $pathname = LONCAPA::tempdir();
 8503:             foreach my $line (@responses) {
 8504:                 my ($key,$value) = split(/=/,$line);
 8505:                 $$replyref{$key} = $value;
 8506:                 if ($value > 0) {
 8507:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8508:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8509:                         my $destname = $pathname.'/'.$filename;
 8510:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8511:                         if ($xml_classlist =~ /^error/) {
 8512:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8513:                         } else {
 8514:                             if ( open(FILE,">",$destname) ) {
 8515:                                 print FILE &unescape($xml_classlist);
 8516:                                 close(FILE);
 8517:                             } else {
 8518:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8519:                             }
 8520:                         }
 8521:                     }
 8522:                 }
 8523:             }
 8524:         }
 8525:         return 'ok';
 8526:     }
 8527:     return 'error';
 8528: }
 8529: 
 8530: sub get_query_reply {
 8531:     my ($queryid,$sleep,$loopmax) = @_;;
 8532:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8533:         $sleep = 0.2;
 8534:     }
 8535:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8536:         $loopmax = 100;
 8537:     }
 8538:     my $replyfile=LONCAPA::tempdir().$queryid;
 8539:     my $reply='';
 8540:     for (1..$loopmax) {
 8541: 	sleep($sleep);
 8542:         if (-e $replyfile.'.end') {
 8543: 	    if (open(my $fh,"<",$replyfile)) {
 8544: 		$reply = join('',<$fh>);
 8545: 		close($fh);
 8546: 	   } else { return 'error: reply_file_error'; }
 8547:            return &unescape($reply);
 8548: 	}
 8549:     }
 8550:     return 'timeout:'.$queryid;
 8551: }
 8552: 
 8553: sub courselog_query {
 8554: #
 8555: # possible filters:
 8556: # url: url or symb
 8557: # username
 8558: # domain
 8559: # action: view, submit, grade
 8560: # start: timestamp
 8561: # end: timestamp
 8562: #
 8563:     my (%filters)=@_;
 8564:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8565:     if ($filters{'url'}) {
 8566: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8567:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8568:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8569:     }
 8570:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8571:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8572:     return &log_query($cname,$cdom,'courselog',%filters);
 8573: }
 8574: 
 8575: sub userlog_query {
 8576: #
 8577: # possible filters:
 8578: # action: log check role
 8579: # start: timestamp
 8580: # end: timestamp
 8581: #
 8582:     my ($uname,$udom,%filters)=@_;
 8583:     return &log_query($uname,$udom,'userlog',%filters);
 8584: }
 8585: 
 8586: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8587: 
 8588: sub auto_run {
 8589:     my ($cnum,$cdom) = @_;
 8590:     my $response = 0;
 8591:     my $settings;
 8592:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8593:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8594:         $settings = $domconfig{'autoenroll'};
 8595:         if ($settings->{'run'} eq '1') {
 8596:             $response = 1;
 8597:         }
 8598:     } else {
 8599:         my $homeserver;
 8600:         if (&is_course($cdom,$cnum)) {
 8601:             $homeserver = &homeserver($cnum,$cdom);
 8602:         } else {
 8603:             $homeserver = &domain($cdom,'primary');
 8604:         }
 8605:         if ($homeserver ne 'no_host') {
 8606:             $response = &reply('autorun:'.$cdom,$homeserver);
 8607:         }
 8608:     }
 8609:     return $response;
 8610: }
 8611: 
 8612: sub auto_get_sections {
 8613:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8614:     my $homeserver;
 8615:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8616:         $homeserver = &homeserver($cnum,$cdom);
 8617:     }
 8618:     if (!defined($homeserver)) { 
 8619:         if ($cdom =~ /^$match_domain$/) {
 8620:             $homeserver = &domain($cdom,'primary');
 8621:         }
 8622:     }
 8623:     my @secs;
 8624:     if (defined($homeserver)) {
 8625:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8626:         unless ($response eq 'refused') {
 8627:             @secs = split(/:/,$response);
 8628:         }
 8629:     }
 8630:     return @secs;
 8631: }
 8632: 
 8633: sub auto_new_course {
 8634:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8635:     my $homeserver = &homeserver($cnum,$cdom);
 8636:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8637:     return $response;
 8638: }
 8639: 
 8640: sub auto_validate_courseID {
 8641:     my ($cnum,$cdom,$inst_course_id) = @_;
 8642:     my $homeserver = &homeserver($cnum,$cdom);
 8643:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8644:     return $response;
 8645: }
 8646: 
 8647: sub auto_validate_instcode {
 8648:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8649:     my ($homeserver,$response);
 8650:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8651:         $homeserver = &homeserver($cnum,$cdom);
 8652:     }
 8653:     if (!defined($homeserver)) {
 8654:         if ($cdom =~ /^$match_domain$/) {
 8655:             $homeserver = &domain($cdom,'primary');
 8656:         }
 8657:     }
 8658:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8659:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8660:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8661:     return ($outcome,$description,$defaultcredits);
 8662: }
 8663: 
 8664: sub auto_create_password {
 8665:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8666:     my ($homeserver,$response);
 8667:     my $create_passwd = 0;
 8668:     my $authchk = '';
 8669:     if ($udom =~ /^$match_domain$/) {
 8670:         $homeserver = &domain($udom,'primary');
 8671:     }
 8672:     if ($homeserver eq '') {
 8673:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8674:             $homeserver = &homeserver($cnum,$cdom);
 8675:         }
 8676:     }
 8677:     if ($homeserver eq '') {
 8678:         $authchk = 'nodomain';
 8679:     } else {
 8680:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8681:         if ($response eq 'refused') {
 8682:             $authchk = 'refused';
 8683:         } else {
 8684:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8685:         }
 8686:     }
 8687:     return ($authparam,$create_passwd,$authchk);
 8688: }
 8689: 
 8690: sub auto_photo_permission {
 8691:     my ($cnum,$cdom,$students) = @_;
 8692:     my $homeserver = &homeserver($cnum,$cdom);
 8693:     my ($outcome,$perm_reqd,$conditions) = 
 8694: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8695:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8696: 	return (undef,undef);
 8697:     }
 8698:     return ($outcome,$perm_reqd,$conditions);
 8699: }
 8700: 
 8701: sub auto_checkphotos {
 8702:     my ($uname,$udom,$pid) = @_;
 8703:     my $homeserver = &homeserver($uname,$udom);
 8704:     my ($result,$resulttype);
 8705:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8706: 				   &escape($uname).':'.&escape($pid),
 8707: 				   $homeserver));
 8708:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8709: 	return (undef,undef);
 8710:     }
 8711:     if ($outcome) {
 8712:         ($result,$resulttype) = split(/:/,$outcome);
 8713:     } 
 8714:     return ($result,$resulttype);
 8715: }
 8716: 
 8717: sub auto_photochoice {
 8718:     my ($cnum,$cdom) = @_;
 8719:     my $homeserver = &homeserver($cnum,$cdom);
 8720:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8721: 						       &escape($cdom),
 8722: 						       $homeserver)));
 8723:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8724: 	return (undef,undef);
 8725:     }
 8726:     return ($update,$comment);
 8727: }
 8728: 
 8729: sub auto_photoupdate {
 8730:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8731:     my $homeserver = &homeserver($cnum,$dom);
 8732:     my $host=&hostname($homeserver);
 8733:     my $cmd = '';
 8734:     my $maxtries = 1;
 8735:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8736:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8737:     }
 8738:     $cmd =~ s/%%$//;
 8739:     $cmd = &escape($cmd);
 8740:     my $query = 'institutionalphotos';
 8741:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8742:     unless ($queryid=~/^\Q$host\E\_/) {
 8743:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8744:         return 'error: '.$queryid;
 8745:     }
 8746:     my $reply = &get_query_reply($queryid);
 8747:     my $tries = 1;
 8748:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8749:         $reply = &get_query_reply($queryid);
 8750:         $tries ++;
 8751:     }
 8752:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8753:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8754:     } else {
 8755:         my @responses = split(/:/,$reply);
 8756:         my $outcome = shift(@responses); 
 8757:         foreach my $item (@responses) {
 8758:             my ($key,$value) = split(/=/,$item);
 8759:             $$photo{$key} = $value;
 8760:         }
 8761:         return $outcome;
 8762:     }
 8763:     return 'error';
 8764: }
 8765: 
 8766: sub auto_instcode_format {
 8767:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8768: 	$cat_order) = @_;
 8769:     my $courses = '';
 8770:     my @homeservers;
 8771:     if ($caller eq 'global') {
 8772: 	my %servers = &get_servers($codedom,'library');
 8773: 	foreach my $tryserver (keys(%servers)) {
 8774: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8775: 		push(@homeservers,$tryserver);
 8776: 	    }
 8777:         }
 8778:     } elsif ($caller eq 'requests') {
 8779:         if ($codedom =~ /^$match_domain$/) {
 8780:             my $chome = &domain($codedom,'primary');
 8781:             unless ($chome eq 'no_host') {
 8782:                 push(@homeservers,$chome);
 8783:             }
 8784:         }
 8785:     } else {
 8786:         push(@homeservers,&homeserver($caller,$codedom));
 8787:     }
 8788:     foreach my $code (keys(%{$instcodes})) {
 8789:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8790:     }
 8791:     chop($courses);
 8792:     my $ok_response = 0;
 8793:     my $response;
 8794:     while (@homeservers > 0 && $ok_response == 0) {
 8795:         my $server = shift(@homeservers); 
 8796:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8797:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8798:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8799: 		split(/:/,$response);
 8800:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8801:             push(@{$codetitles},&str2array($codetitles_str));
 8802:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8803:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8804:             $ok_response = 1;
 8805:         }
 8806:     }
 8807:     if ($ok_response) {
 8808:         return 'ok';
 8809:     } else {
 8810:         return $response;
 8811:     }
 8812: }
 8813: 
 8814: sub auto_instcode_defaults {
 8815:     my ($domain,$returnhash,$code_order) = @_;
 8816:     my @homeservers;
 8817: 
 8818:     my %servers = &get_servers($domain,'library');
 8819:     foreach my $tryserver (keys(%servers)) {
 8820: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8821: 	    push(@homeservers,$tryserver);
 8822: 	}
 8823:     }
 8824: 
 8825:     my $response;
 8826:     foreach my $server (@homeservers) {
 8827:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8828:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8829: 	
 8830: 	foreach my $pair (split(/\&/,$response)) {
 8831: 	    my ($name,$value)=split(/\=/,$pair);
 8832: 	    if ($name eq 'code_order') {
 8833: 		@{$code_order} = split(/\&/,&unescape($value));
 8834: 	    } else {
 8835: 		$returnhash->{&unescape($name)}=&unescape($value);
 8836: 	    }
 8837: 	}
 8838: 	return 'ok';
 8839:     }
 8840: 
 8841:     return $response;
 8842: }
 8843: 
 8844: sub auto_possible_instcodes {
 8845:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8846:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8847:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8848:         return;
 8849:     }
 8850:     my (@homeservers,$uhome);
 8851:     if (defined(&domain($domain,'primary'))) {
 8852:         $uhome=&domain($domain,'primary');
 8853:         push(@homeservers,&domain($domain,'primary'));
 8854:     } else {
 8855:         my %servers = &get_servers($domain,'library');
 8856:         foreach my $tryserver (keys(%servers)) {
 8857:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8858:                 push(@homeservers,$tryserver);
 8859:             }
 8860:         }
 8861:     }
 8862:     my $response;
 8863:     foreach my $server (@homeservers) {
 8864:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8865:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8866:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8867:             split(':',$response);
 8868:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8869:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8870:         foreach my $item (split('&',$cat_title)) {   
 8871:             my ($name,$value)=split('=',$item);
 8872:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8873:         }
 8874:         foreach my $item (split('&',$cat_order)) {
 8875:             my ($name,$value)=split('=',$item);
 8876:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8877:         }
 8878:         return 'ok';
 8879:     }
 8880:     return $response;
 8881: }
 8882: 
 8883: sub auto_courserequest_checks {
 8884:     my ($dom) = @_;
 8885:     my ($homeserver,%validations);
 8886:     if ($dom =~ /^$match_domain$/) {
 8887:         $homeserver = &domain($dom,'primary');
 8888:     }
 8889:     unless ($homeserver eq 'no_host') {
 8890:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8891:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8892:             my @items = split(/&/,$response);
 8893:             foreach my $item (@items) {
 8894:                 my ($key,$value) = split('=',$item);
 8895:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8896:             }
 8897:         }
 8898:     }
 8899:     return %validations; 
 8900: }
 8901: 
 8902: sub auto_courserequest_validation {
 8903:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8904:     my ($homeserver,$response);
 8905:     if ($dom =~ /^$match_domain$/) {
 8906:         $homeserver = &domain($dom,'primary');
 8907:     }
 8908:     unless ($homeserver eq 'no_host') {
 8909:         my $customdata;
 8910:         if (ref($custominfo) eq 'HASH') {
 8911:             $customdata = &freeze_escape($custominfo);
 8912:         }
 8913:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8914:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8915:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8916:                                     $customdata,$homeserver));
 8917:     }
 8918:     return $response;
 8919: }
 8920: 
 8921: sub auto_validate_class_sec {
 8922:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8923:     my $homeserver = &homeserver($cnum,$cdom);
 8924:     my $ownerlist;
 8925:     if (ref($owners) eq 'ARRAY') {
 8926:         $ownerlist = join(',',@{$owners});
 8927:     } else {
 8928:         $ownerlist = $owners;
 8929:     }
 8930:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8931:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8932:     return $response;
 8933: }
 8934: 
 8935: sub auto_validate_instclasses {
 8936:     my ($cdom,$cnum,$owners,$classesref) = @_;
 8937:     my ($homeserver,%validations);
 8938:     $homeserver = &homeserver($cnum,$cdom);
 8939:     unless ($homeserver eq 'no_host') {
 8940:         my $ownerlist;
 8941:         if (ref($owners) eq 'ARRAY') {
 8942:             $ownerlist = join(',',@{$owners});
 8943:         } else {
 8944:             $ownerlist = $owners;
 8945:         }
 8946:         if (ref($classesref) eq 'HASH') {
 8947:             my $classes = &freeze_escape($classesref);
 8948:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 8949:                                 ':'.$cdom.':'.$classes,$homeserver);
 8950:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8951:                 my @items = split(/&/,$response);
 8952:                 foreach my $item (@items) {
 8953:                     my ($key,$value) = split('=',$item);
 8954:                     $validations{&unescape($key)} = &thaw_unescape($value);
 8955:                 }
 8956:             }
 8957:         }
 8958:     }
 8959:     return %validations;
 8960: }
 8961: 
 8962: sub auto_crsreq_update {
 8963:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8964:         $code,$accessstart,$accessend,$inbound) = @_;
 8965:     my ($homeserver,%crsreqresponse);
 8966:     if ($cdom =~ /^$match_domain$/) {
 8967:         $homeserver = &domain($cdom,'primary');
 8968:     }
 8969:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8970:         my $info;
 8971:         if (ref($inbound) eq 'HASH') {
 8972:             $info = &freeze_escape($inbound);
 8973:         }
 8974:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8975:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8976:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8977:                             &escape($title).':'.&escape($code).':'.
 8978:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8979:                             $homeserver);
 8980:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8981:             my @items = split(/&/,$response);
 8982:             foreach my $item (@items) {
 8983:                 my ($key,$value) = split('=',$item);
 8984:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8985:             }
 8986:         }
 8987:     }
 8988:     return \%crsreqresponse;
 8989: }
 8990: 
 8991: sub auto_export_grades {
 8992:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8993:     my ($homeserver,%exportresponse);
 8994:     if ($cdom =~ /^$match_domain$/) {
 8995:         $homeserver = &domain($cdom,'primary');
 8996:     }
 8997:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8998:         my $info;
 8999:         if (ref($inforef) eq 'HASH') {
 9000:             $info = &freeze_escape($inforef);
 9001:         }
 9002:         if (ref($gradesref) eq 'HASH') {
 9003:             my $grades = &freeze_escape($gradesref);
 9004:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9005:                                 $info.':'.$grades,$homeserver);
 9006:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9007:                 my @items = split(/&/,$response);
 9008:                 foreach my $item (@items) {
 9009:                     my ($key,$value) = split('=',$item);
 9010:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9011:                 }
 9012:             }
 9013:         }
 9014:     }
 9015:     return \%exportresponse;
 9016: }
 9017: 
 9018: sub check_instcode_cloning {
 9019:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9020:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9021:         return;
 9022:     }
 9023:     my $canclone;
 9024:     if (@{$code_order} > 0) {
 9025:         my $instcoderegexp ='^';
 9026:         my @clonecodes = split(/\&/,$cloner);
 9027:         foreach my $item (@{$code_order}) {
 9028:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9029:                 foreach my $pair (@clonecodes) {
 9030:                     my ($key,$val) = split(/\=/,$pair,2);
 9031:                     $val = &unescape($val);
 9032:                     if ($key eq $item) {
 9033:                         $instcoderegexp .= '('.$val.')';
 9034:                         last;
 9035:                     }
 9036:                 }
 9037:             } else {
 9038:                 $instcoderegexp .= $codedefaults->{$item};
 9039:             }
 9040:         }
 9041:         $instcoderegexp .= '$';
 9042:         my (@from,@to);
 9043:         eval {
 9044:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9045:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9046:         };
 9047:         if ((@from > 0) && (@to > 0)) {
 9048:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9049:             if (!@diffs) {
 9050:                 $canclone = 1;
 9051:             }
 9052:         }
 9053:     }
 9054:     return $canclone;
 9055: }
 9056: 
 9057: sub default_instcode_cloning {
 9058:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9059:     my (%codedefaults,@code_order,$canclone);
 9060:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9061:         %codedefaults = %{$codedefaultsref};
 9062:         @code_order = @{$codeorderref};
 9063:     } elsif ($clonedom) {
 9064:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9065:     }
 9066:     if (($domdefclone) && (@code_order)) {
 9067:         my @clonecodes = split(/\+/,$domdefclone);
 9068:         my $instcoderegexp ='^';
 9069:         foreach my $item (@code_order) {
 9070:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9071:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9072:             } else {
 9073:                 $instcoderegexp .= $codedefaults{$item};
 9074:             }
 9075:         }
 9076:         $instcoderegexp .= '$';
 9077:         my (@from,@to);
 9078:         eval {
 9079:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9080:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9081:         };
 9082:         if ((@from > 0) && (@to > 0)) {
 9083:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9084:             if (!@diffs) {
 9085:                 $canclone = 1;
 9086:             }
 9087:         }
 9088:     }
 9089:     return $canclone;
 9090: }
 9091: 
 9092: # ------------------------------------------------------- Course Group routines
 9093: 
 9094: sub get_coursegroups {
 9095:     my ($cdom,$cnum,$group,$namespace) = @_;
 9096:     return(&dump($namespace,$cdom,$cnum,$group));
 9097: }
 9098: 
 9099: sub modify_coursegroup {
 9100:     my ($cdom,$cnum,$groupsettings) = @_;
 9101:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9102: }
 9103: 
 9104: sub toggle_coursegroup_status {
 9105:     my ($cdom,$cnum,$group,$action) = @_;
 9106:     my ($from_namespace,$to_namespace);
 9107:     if ($action eq 'delete') {
 9108:         $from_namespace = 'coursegroups';
 9109:         $to_namespace = 'deleted_groups';
 9110:     } else {
 9111:         $from_namespace = 'deleted_groups';
 9112:         $to_namespace = 'coursegroups';
 9113:     }
 9114:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9115:     if (my $tmp = &error(%curr_group)) {
 9116:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9117:         return ('read error',$tmp);
 9118:     } else {
 9119:         my %savedsettings = %curr_group; 
 9120:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9121:         my $deloutcome;
 9122:         if ($result eq 'ok') {
 9123:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9124:         } else {
 9125:             return ('write error',$result);
 9126:         }
 9127:         if ($deloutcome eq 'ok') {
 9128:             return 'ok';
 9129:         } else {
 9130:             return ('delete error',$deloutcome);
 9131:         }
 9132:     }
 9133: }
 9134: 
 9135: sub modify_group_roles {
 9136:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9137:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9138:     my $role = 'gr/'.&escape($userprivs);
 9139:     my ($uname,$udom) = split(/:/,$user);
 9140:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9141:     if ($result eq 'ok') {
 9142:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9143:     }
 9144:     return $result;
 9145: }
 9146: 
 9147: sub modify_coursegroup_membership {
 9148:     my ($cdom,$cnum,$membership) = @_;
 9149:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9150:     return $result;
 9151: }
 9152: 
 9153: sub get_active_groups {
 9154:     my ($udom,$uname,$cdom,$cnum) = @_;
 9155:     my $now = time;
 9156:     my %groups = ();
 9157:     foreach my $key (keys(%env)) {
 9158:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9159:             my ($start,$end) = split(/\./,$env{$key});
 9160:             if (($end!=0) && ($end<$now)) { next; }
 9161:             if (($start!=0) && ($start>$now)) { next; }
 9162:             if ($1 eq $cdom && $2 eq $cnum) {
 9163:                 $groups{$3} = $env{$key} ;
 9164:             }
 9165:         }
 9166:     }
 9167:     return %groups;
 9168: }
 9169: 
 9170: sub get_group_membership {
 9171:     my ($cdom,$cnum,$group) = @_;
 9172:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9173: }
 9174: 
 9175: sub get_users_groups {
 9176:     my ($udom,$uname,$courseid) = @_;
 9177:     my @usersgroups;
 9178:     my $cachetime=1800;
 9179: 
 9180:     my $hashid="$udom:$uname:$courseid";
 9181:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9182:     if (defined($cached)) {
 9183:         @usersgroups = split(/:/,$grouplist);
 9184:     } else {  
 9185:         $grouplist = '';
 9186:         my $courseurl = &courseid_to_courseurl($courseid);
 9187:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9188:         my $access_end = $env{'course.'.$courseid.
 9189:                               '.default_enrollment_end_date'};
 9190:         my $now = time;
 9191:         foreach my $key (keys(%roleshash)) {
 9192:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9193:                 my $group = $1;
 9194:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9195:                     my $start = $2;
 9196:                     my $end = $1;
 9197:                     if ($start == -1) { next; } # deleted from group
 9198:                     if (($start!=0) && ($start>$now)) { next; }
 9199:                     if (($end!=0) && ($end<$now)) {
 9200:                         if ($access_end && $access_end < $now) {
 9201:                             if ($access_end - $end < 86400) {
 9202:                                 push(@usersgroups,$group);
 9203:                             }
 9204:                         }
 9205:                         next;
 9206:                     }
 9207:                     push(@usersgroups,$group);
 9208:                 }
 9209:             }
 9210:         }
 9211:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9212:         $grouplist = join(':',@usersgroups);
 9213:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9214:     }
 9215:     return @usersgroups;
 9216: }
 9217: 
 9218: sub devalidate_getgroups_cache {
 9219:     my ($udom,$uname,$cdom,$cnum)=@_;
 9220:     my $courseid = $cdom.'_'.$cnum;
 9221: 
 9222:     my $hashid="$udom:$uname:$courseid";
 9223:     &devalidate_cache_new('getgroups',$hashid);
 9224: }
 9225: 
 9226: # ------------------------------------------------------------------ Plain Text
 9227: 
 9228: sub plaintext {
 9229:     my ($short,$type,$cid,$forcedefault) = @_;
 9230:     if ($short =~ m{^cr/}) {
 9231: 	return (split('/',$short))[-1];
 9232:     }
 9233:     if (!defined($cid)) {
 9234:         $cid = $env{'request.course.id'};
 9235:     }
 9236:     my %rolenames = (
 9237:                       Course    => 'std',
 9238:                       Community => 'alt1',
 9239:                       Placement => 'std',
 9240:                     );
 9241:     if ($cid ne '') {
 9242:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9243:             unless ($forcedefault) {
 9244:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9245:                 &Apache::lonlocal::mt_escape(\$roletext);
 9246:                 return &Apache::lonlocal::mt($roletext);
 9247:             }
 9248:         }
 9249:     }
 9250:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9251:         (defined($rolenames{$type})) && 
 9252:         (defined($prp{$short}{$rolenames{$type}}))) {
 9253:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9254:     } elsif ($cid ne '') {
 9255:         my $crstype = $env{'course.'.$cid.'.type'};
 9256:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9257:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9258:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9259:         }
 9260:     }
 9261:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9262: }
 9263: 
 9264: # ----------------------------------------------------------------- Assign Role
 9265: 
 9266: sub assignrole {
 9267:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9268:         $context)=@_;
 9269:     my $mrole;
 9270:     if ($role =~ /^cr\//) {
 9271:         my $cwosec=$url;
 9272:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9273: 	unless (&allowed('ccr',$cwosec)) {
 9274:            my $refused = 1;
 9275:            if ($context eq 'requestcourses') {
 9276:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9277:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9278:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9279:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9280:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9281:                            if ($crsenv{'internal.courseowner'} eq
 9282:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9283:                                $refused = '';
 9284:                            }
 9285:                        }
 9286:                    }
 9287:                }
 9288:            }
 9289:            if ($refused) {
 9290:                &logthis('Refused custom assignrole: '.
 9291:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9292:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9293:                return 'refused';
 9294:            }
 9295:         }
 9296:         $mrole='cr';
 9297:     } elsif ($role =~ /^gr\//) {
 9298:         my $cwogrp=$url;
 9299:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9300:         unless (&allowed('mdg',$cwogrp)) {
 9301:             &logthis('Refused group assignrole: '.
 9302:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9303:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9304:             return 'refused';
 9305:         }
 9306:         $mrole='gr';
 9307:     } else {
 9308:         my $cwosec=$url;
 9309:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9310:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9311:             my $refused;
 9312:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9313:                 if (!(&allowed('c'.$role,$url))) {
 9314:                     $refused = 1;
 9315:                 }
 9316:             } else {
 9317:                 $refused = 1;
 9318:             }
 9319:             if ($refused) {
 9320:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9321:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9322:                     my %crsenv;
 9323:                     if ($role eq 'cc' || $role eq 'co') {
 9324:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9325:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9326:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9327:                                 if ($crsenv{'internal.courseowner'} eq 
 9328:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9329:                                     $refused = '';
 9330:                                 }
 9331:                             }
 9332:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9333:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9334:                                 if ($crsenv{'internal.courseowner'} eq 
 9335:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9336:                                     $refused = '';
 9337:                                 }
 9338:                             }
 9339:                         }
 9340:                     }
 9341:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9342:                     if ($role eq 'st') {
 9343:                         $refused = '';
 9344:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9345:                         $refused = '';
 9346:                     }
 9347:                 } elsif ($context eq 'requestcourses') {
 9348:                     my @possroles = ('st','ta','ep','in','cc','co');
 9349:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9350:                         my $wrongcc;
 9351:                         if ($cnum =~ /^$match_community$/) {
 9352:                             $wrongcc = 1 if ($role eq 'cc');
 9353:                         } else {
 9354:                             $wrongcc = 1 if ($role eq 'co');
 9355:                         }
 9356:                         unless ($wrongcc) {
 9357:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9358:                             if ($crsenv{'internal.courseowner'} eq 
 9359:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9360:                                 $refused = '';
 9361:                             }
 9362:                         }
 9363:                     }
 9364:                 } elsif ($context eq 'requestauthor') {
 9365:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9366:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9367:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9368:                             $refused = '';
 9369:                         } else {
 9370:                             my %domdefaults = &get_domain_defaults($udom);
 9371:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9372:                                 my $checkbystatus;
 9373:                                 if ($env{'user.adv'}) { 
 9374:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9375:                                     if ($disposition eq 'automatic') {
 9376:                                         $refused = '';
 9377:                                     } elsif ($disposition eq '') {
 9378:                                         $checkbystatus = 1;
 9379:                                     } 
 9380:                                 } else {
 9381:                                     $checkbystatus = 1;
 9382:                                 }
 9383:                                 if ($checkbystatus) {
 9384:                                     if ($env{'environment.inststatus'}) {
 9385:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9386:                                         foreach my $type (@inststatuses) {
 9387:                                             if (($type ne '') &&
 9388:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9389:                                                 $refused = '';
 9390:                                             }
 9391:                                         }
 9392:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9393:                                         $refused = '';
 9394:                                     }
 9395:                                 }
 9396:                             }
 9397:                         }
 9398:                     }
 9399:                 }
 9400:                 if ($refused) {
 9401:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9402:                              ' '.$role.' '.$end.' '.$start.' by '.
 9403: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9404:                     return 'refused';
 9405:                 }
 9406:             }
 9407:         } elsif ($role eq 'au') {
 9408:             if ($url ne '/'.$udom.'/') {
 9409:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9410:                          ' to assign author role for '.$uname.':'.$udom.
 9411:                          ' in domain: '.$url.' refused (wrong domain).');
 9412:                 return 'refused';
 9413:             }
 9414:         }
 9415:         $mrole=$role;
 9416:     }
 9417:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9418:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9419:     if ($end) { $command.='_'.$end; }
 9420:     if ($start) {
 9421: 	if ($end) { 
 9422:            $command.='_'.$start; 
 9423:         } else {
 9424:            $command.='_0_'.$start;
 9425:         }
 9426:     }
 9427:     my $origstart = $start;
 9428:     my $origend = $end;
 9429:     my $delflag;
 9430: # actually delete
 9431:     if ($deleteflag) {
 9432: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9433: # modify command to delete the role
 9434:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9435:                 "$udom:$uname:$url".'_'."$mrole";
 9436: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9437: # set start and finish to negative values for userrolelog
 9438:            $start=-1;
 9439:            $end=-1;
 9440:            $delflag = 1;
 9441:         }
 9442:     }
 9443: # send command
 9444:     my $answer=&reply($command,&homeserver($uname,$udom));
 9445: # log new user role if status is ok
 9446:     if ($answer eq 'ok') {
 9447: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9448:         if (($role eq 'cc') || ($role eq 'in') ||
 9449:             ($role eq 'ep') || ($role eq 'ad') ||
 9450:             ($role eq 'ta') || ($role eq 'st') ||
 9451:             ($role=~/^cr/) || ($role eq 'gr') ||
 9452:             ($role eq 'co')) {
 9453: # for course roles, perform group memberships changes triggered by role change.
 9454:             unless ($role =~ /^gr/) {
 9455:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9456:                                                  $origstart,$selfenroll,$context);
 9457:             }
 9458:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9459:                            $selfenroll,$context);
 9460:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9461:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9462:                  ($role eq 'da')) {
 9463:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9464:                            $context);
 9465:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9466:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9467:                              $context); 
 9468:         }
 9469:         if ($role eq 'cc') {
 9470:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9471:         }
 9472:     }
 9473:     return $answer;
 9474: }
 9475: 
 9476: sub autoupdate_coowners {
 9477:     my ($url,$end,$start,$uname,$udom) = @_;
 9478:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9479:     if (($cdom ne '') && ($cnum ne '')) {
 9480:         my $now = time;
 9481:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9482:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9483:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9484:             my $instcode = $coursehash{'internal.coursecode'};
 9485:             if ($instcode ne '') {
 9486:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9487:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9488:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9489:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9490:                         if ($result eq 'valid') {
 9491:                             if ($coursehash{'internal.co-owners'}) {
 9492:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9493:                                     push(@newcoowners,$coowner);
 9494:                                 }
 9495:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9496:                                     push(@newcoowners,$uname.':'.$udom);
 9497:                                 }
 9498:                                 @newcoowners = sort(@newcoowners);
 9499:                             } else {
 9500:                                 push(@newcoowners,$uname.':'.$udom);
 9501:                             }
 9502:                         } else {
 9503:                             if ($coursehash{'internal.co-owners'}) {
 9504:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9505:                                     unless ($coowner eq $uname.':'.$udom) {
 9506:                                         push(@newcoowners,$coowner);
 9507:                                     }
 9508:                                 }
 9509:                                 unless (@newcoowners > 0) {
 9510:                                     $delcoowners = 1;
 9511:                                     $coowners = '';
 9512:                                 }
 9513:                             }
 9514:                         }
 9515:                         if (@newcoowners || $delcoowners) {
 9516:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9517:                                             $delcoowners,@newcoowners);
 9518:                         }
 9519:                     }
 9520:                 }
 9521:             }
 9522:         }
 9523:     }
 9524: }
 9525: 
 9526: sub store_coowners {
 9527:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9528:     my $cid = $cdom.'_'.$cnum;
 9529:     my ($coowners,$delresult,$putresult);
 9530:     if (@newcoowners) {
 9531:         $coowners = join(',',@newcoowners);
 9532:         my %coownershash = (
 9533:                             'internal.co-owners' => $coowners,
 9534:                            );
 9535:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9536:         if ($putresult eq 'ok') {
 9537:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9538:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9539:             }
 9540:         }
 9541:     }
 9542:     if ($delcoowners) {
 9543:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9544:         if ($delresult eq 'ok') {
 9545:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9546:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9547:             }
 9548:         }
 9549:     }
 9550:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9551:         my %crsinfo =
 9552:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9553:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9554:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9555:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9556:         }
 9557:     }
 9558: }
 9559: 
 9560: # -------------------------------------------------- Modify user authentication
 9561: # Overrides without validation
 9562: 
 9563: sub modifyuserauth {
 9564:     my ($udom,$uname,$umode,$upass)=@_;
 9565:     my $uhome=&homeserver($uname,$udom);
 9566:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9567:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9568:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9569:              ' in domain '.$env{'request.role.domain'});  
 9570:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9571: 		     &escape($upass),$uhome);
 9572:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9573:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9574:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9575:     &log($udom,,$uname,$uhome,
 9576:         'Authentication changed by '.$env{'user.domain'}.', '.
 9577:                                      $env{'user.name'}.', '.$umode.
 9578:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9579:     unless ($reply eq 'ok') {
 9580:         &logthis('Authentication mode error: '.$reply);
 9581: 	return 'error: '.$reply;
 9582:     }   
 9583:     return 'ok';
 9584: }
 9585: 
 9586: # --------------------------------------------------------------- Modify a user
 9587: 
 9588: sub modifyuser {
 9589:     my ($udom,    $uname, $uid,
 9590:         $umode,   $upass, $first,
 9591:         $middle,  $last,  $gene,
 9592:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9593:     $udom= &LONCAPA::clean_domain($udom);
 9594:     $uname=&LONCAPA::clean_username($uname);
 9595:     my $showcandelete = 'none';
 9596:     if (ref($candelete) eq 'ARRAY') {
 9597:         if (@{$candelete} > 0) {
 9598:             $showcandelete = join(', ',@{$candelete});
 9599:         }
 9600:     }
 9601:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9602:              $umode.', '.$first.', '.$middle.', '.
 9603: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9604:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9605:                                      ' desiredhome not specified'). 
 9606:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9607:              ' in domain '.$env{'request.role.domain'});
 9608:     my $uhome=&homeserver($uname,$udom,'true');
 9609:     my $newuser;
 9610:     if ($uhome eq 'no_host') {
 9611:         $newuser = 1;
 9612:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9613:                 ($umode eq 'lti')) {
 9614:             return 'error: more information needed to create new user';
 9615:         }
 9616:     }
 9617: # ----------------------------------------------------------------- Create User
 9618:     if (($uhome eq 'no_host') && 
 9619: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9620:         my $unhome='';
 9621:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9622:             $unhome = $desiredhome;
 9623: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9624: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9625:         } else { # load balancing routine for determining $unhome
 9626:             my $loadm=10000000;
 9627: 	    my %servers = &get_servers($udom,'library');
 9628: 	    foreach my $tryserver (keys(%servers)) {
 9629: 		my $answer=reply('load',$tryserver);
 9630: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9631: 		    $loadm=$answer;
 9632: 		    $unhome=$tryserver;
 9633: 		}
 9634: 	    }
 9635:         }
 9636:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9637: 	    return 'error: unable to find a home server for '.$uname.
 9638:                    ' in domain '.$udom;
 9639:         }
 9640:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9641:                          &escape($upass),$unhome);
 9642: 	unless ($reply eq 'ok') {
 9643:             return 'error: '.$reply;
 9644:         }   
 9645:         $uhome=&homeserver($uname,$udom,'true');
 9646:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9647: 	    return 'error: unable verify users home machine.';
 9648:         }
 9649:     }   # End of creation of new user
 9650: # ---------------------------------------------------------------------- Add ID
 9651:     if ($uid) {
 9652:        $uid=~tr/A-Z/a-z/;
 9653:        my %uidhash=&idrget($udom,$uname);
 9654:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9655:          && (!$forceid)) {
 9656: 	  unless ($uid eq $uidhash{$uname}) {
 9657: 	      return 'error: user id "'.$uid.'" does not match '.
 9658:                   'current user id "'.$uidhash{$uname}.'".';
 9659:           }
 9660:        } else {
 9661: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9662:        }
 9663:     }
 9664: # -------------------------------------------------------------- Add names, etc
 9665:     my @tmp=&get('environment',
 9666: 		   ['firstname','middlename','lastname','generation','id',
 9667:                     'permanentemail','inststatus'],
 9668: 		   $udom,$uname);
 9669:     my (%names,%oldnames);
 9670:     if ($tmp[0] =~ m/^error:.*/) { 
 9671:         %names=(); 
 9672:     } else {
 9673:         %names = @tmp;
 9674:         %oldnames = %names;
 9675:     }
 9676: #
 9677: # If name, email and/or uid are blank (e.g., because an uploaded file
 9678: # of users did not contain them), do not overwrite existing values
 9679: # unless field is in $candelete array ref.  
 9680: #
 9681: 
 9682:     my @fields = ('firstname','middlename','lastname','generation',
 9683:                   'permanentemail','id');
 9684:     my %newvalues;
 9685:     if (ref($candelete) eq 'ARRAY') {
 9686:         foreach my $field (@fields) {
 9687:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9688:                 if ($field eq 'firstname') {
 9689:                     $names{$field} = $first;
 9690:                 } elsif ($field eq 'middlename') {
 9691:                     $names{$field} = $middle;
 9692:                 } elsif ($field eq 'lastname') {
 9693:                     $names{$field} = $last;
 9694:                 } elsif ($field eq 'generation') { 
 9695:                     $names{$field} = $gene;
 9696:                 } elsif ($field eq 'permanentemail') {
 9697:                     $names{$field} = $email;
 9698:                 } elsif ($field eq 'id') {
 9699:                     $names{$field}  = $uid;
 9700:                 }
 9701:             }
 9702:         }
 9703:     }
 9704:     if ($first)  { $names{'firstname'}  = $first; }
 9705:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9706:     if ($last)   { $names{'lastname'}   = $last; }
 9707:     if (defined($gene))   { $names{'generation'} = $gene; }
 9708:     if ($email) {
 9709:        $email=~s/[^\w\@\.\-\,]//gs;
 9710:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9711:     }
 9712:     if ($uid) { $names{'id'}  = $uid; }
 9713:     if (defined($inststatus)) {
 9714:         $names{'inststatus'} = '';
 9715:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9716:         if (ref($usertypes) eq 'HASH') {
 9717:             my @okstatuses; 
 9718:             foreach my $item (split(/:/,$inststatus)) {
 9719:                 if (defined($usertypes->{$item})) {
 9720:                     push(@okstatuses,$item);  
 9721:                 }
 9722:             }
 9723:             if (@okstatuses) {
 9724:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9725:             }
 9726:         }
 9727:     }
 9728:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9729:                  $umode.', '.$first.', '.$middle.', '.
 9730:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9731:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9732:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9733:     } else {
 9734:         $logmsg .= ' during self creation';
 9735:     }
 9736:     my $changed;
 9737:     if ($newuser) {
 9738:         $changed = 1;
 9739:     } else {
 9740:         foreach my $field (@fields) {
 9741:             if ($names{$field} ne $oldnames{$field}) {
 9742:                 $changed = 1;
 9743:                 last;
 9744:             }
 9745:         }
 9746:     }
 9747:     unless ($changed) {
 9748:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9749:         &logthis($logmsg);
 9750:         return 'ok';
 9751:     }
 9752:     my $reply = &put('environment', \%names, $udom,$uname);
 9753:     if ($reply ne 'ok') { 
 9754:         return 'error: '.$reply;
 9755:     }
 9756:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9757:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9758:     }
 9759:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9760:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9761:     $logmsg = 'Success modifying user '.$logmsg;
 9762:     &logthis($logmsg);
 9763:     return 'ok';
 9764: }
 9765: 
 9766: # -------------------------------------------------------------- Modify student
 9767: 
 9768: sub modifystudent {
 9769:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9770:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9771:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9772:     if (!$cid) {
 9773: 	unless ($cid=$env{'request.course.id'}) {
 9774: 	    return 'not_in_class';
 9775: 	}
 9776:     }
 9777: # --------------------------------------------------------------- Make the user
 9778:     my $reply=&modifyuser
 9779: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9780:          $desiredhome,$email,$inststatus);
 9781:     unless ($reply eq 'ok') { return $reply; }
 9782:     # This will cause &modify_student_enrollment to get the uid from the
 9783:     # student's environment
 9784:     $uid = undef if (!$forceid);
 9785:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9786:                                         $gene,$usec,$end,$start,$type,$locktype,
 9787:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9788:     return $reply;
 9789: }
 9790: 
 9791: sub modify_student_enrollment {
 9792:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9793:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9794:     my ($cdom,$cnum,$chome);
 9795:     if (!$cid) {
 9796: 	unless ($cid=$env{'request.course.id'}) {
 9797: 	    return 'not_in_class';
 9798: 	}
 9799: 	$cdom=$env{'course.'.$cid.'.domain'};
 9800: 	$cnum=$env{'course.'.$cid.'.num'};
 9801:     } else {
 9802: 	($cdom,$cnum)=split(/_/,$cid);
 9803:     }
 9804:     $chome=$env{'course.'.$cid.'.home'};
 9805:     if (!$chome) {
 9806: 	$chome=&homeserver($cnum,$cdom);
 9807:     }
 9808:     if (!$chome) { return 'unknown_course'; }
 9809:     # Make sure the user exists
 9810:     my $uhome=&homeserver($uname,$udom);
 9811:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9812: 	return 'error: no such user';
 9813:     }
 9814:     # Get student data if we were not given enough information
 9815:     if (!defined($first)  || $first  eq '' || 
 9816:         !defined($last)   || $last   eq '' || 
 9817:         !defined($uid)    || $uid    eq '' || 
 9818:         !defined($middle) || $middle eq '' || 
 9819:         !defined($gene)   || $gene   eq '') {
 9820:         # They did not supply us with enough data to enroll the student, so
 9821:         # we need to pick up more information.
 9822:         my %tmp = &get('environment',
 9823:                        ['firstname','middlename','lastname', 'generation','id']
 9824:                        ,$udom,$uname);
 9825: 
 9826:         #foreach my $key (keys(%tmp)) {
 9827:         #    &logthis("key $key = ".$tmp{$key});
 9828:         #}
 9829:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9830:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9831:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9832:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9833:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9834:     }
 9835:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9836:     my $user = "$uname:$udom";
 9837:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9838:     my $reply=cput('classlist',
 9839: 		   {$user => 
 9840: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9841: 		   $cdom,$cnum);
 9842:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9843:         &devalidate_getsection_cache($udom,$uname,$cid);
 9844:     } else { 
 9845: 	return 'error: '.$reply;
 9846:     }
 9847:     # Add student role to user
 9848:     my $uurl='/'.$cid;
 9849:     $uurl=~s/\_/\//g;
 9850:     if ($usec) {
 9851: 	$uurl.='/'.$usec;
 9852:     }
 9853:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9854:                              $selfenroll,$context);
 9855:     if ($result ne 'ok') {
 9856:         if ($old_entry{$user} ne '') {
 9857:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9858:         } else {
 9859:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9860:         }
 9861:     }
 9862:     return $result; 
 9863: }
 9864: 
 9865: sub format_name {
 9866:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9867:     my $name;
 9868:     if ($first ne 'lastname') {
 9869: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9870:     } else {
 9871: 	if ($lastname=~/\S/) {
 9872: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9873: 	    $name=~s/\s+,/,/;
 9874: 	} else {
 9875: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9876: 	}
 9877:     }
 9878:     $name=~s/^\s+//;
 9879:     $name=~s/\s+$//;
 9880:     $name=~s/\s+/ /g;
 9881:     return $name;
 9882: }
 9883: 
 9884: # ------------------------------------------------- Write to course preferences
 9885: 
 9886: sub writecoursepref {
 9887:     my ($courseid,%prefs)=@_;
 9888:     $courseid=~s/^\///;
 9889:     $courseid=~s/\_/\//g;
 9890:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9891:     my $chome=homeserver($cnum,$cdomain);
 9892:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9893: 	return 'error: no such course';
 9894:     }
 9895:     my $cstring='';
 9896:     foreach my $pref (keys(%prefs)) {
 9897: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9898:     }
 9899:     $cstring=~s/\&$//;
 9900:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9901: }
 9902: 
 9903: # ---------------------------------------------------------- Make/modify course
 9904: 
 9905: sub createcourse {
 9906:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9907:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9908:     $url=&declutter($url);
 9909:     my $cid='';
 9910:     if ($context eq 'requestcourses') {
 9911:         my $can_create = 0;
 9912:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9913:         if ($udom eq $ownerdom) {
 9914:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9915:                                   $context)) {
 9916:                 $can_create = 1;
 9917:             }
 9918:         } else {
 9919:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9920:                                            $category);
 9921:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9922:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9923:                 if (@curr > 0) {
 9924:                     my @options = qw(approval validate autolimit);
 9925:                     my $optregex = join('|',@options);
 9926:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9927:                         $can_create = 1;
 9928:                     }
 9929:                 }
 9930:             }
 9931:         }
 9932:         if ($can_create) {
 9933:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9934:                 unless (&allowed('ccc',$udom)) {
 9935:                     return 'refused'; 
 9936:                 }
 9937:             }
 9938:         } else {
 9939:             return 'refused';
 9940:         }
 9941:     } elsif (!&allowed('ccc',$udom)) {
 9942:         return 'refused';
 9943:     }
 9944: # --------------------------------------------------------------- Get Unique ID
 9945:     my $uname;
 9946:     if ($cnum =~ /^$match_courseid$/) {
 9947:         my $chome=&homeserver($cnum,$udom,'true');
 9948:         if (($chome eq '') || ($chome eq 'no_host')) {
 9949:             $uname = $cnum;
 9950:         } else {
 9951:             $uname = &generate_coursenum($udom,$crstype);
 9952:         }
 9953:     } else {
 9954:         $uname = &generate_coursenum($udom,$crstype);
 9955:     }
 9956:     return $uname if ($uname =~ /^error/);
 9957: # -------------------------------------------------- Check supplied server name
 9958:     if (!defined($course_server)) {
 9959:         if (defined(&domain($udom,'primary'))) {
 9960:             $course_server = &domain($udom,'primary');
 9961:         } else {
 9962:             $course_server = $env{'user.home'}; 
 9963:         }
 9964:     }
 9965:     my %host_servers =
 9966:         &Apache::lonnet::get_servers($udom,'library');
 9967:     unless ($host_servers{$course_server}) {
 9968:         return 'error: invalid home server for course: '.$course_server;
 9969:     }
 9970: # ------------------------------------------------------------- Make the course
 9971:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9972:                       $course_server);
 9973:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9974:     my $uhome=&homeserver($uname,$udom,'true');
 9975:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9976: 	return 'error: no such course';
 9977:     }
 9978: # ----------------------------------------------------------------- Course made
 9979: # log existence
 9980:     my $now = time;
 9981:     my $newcourse = {
 9982:                     $udom.'_'.$uname => {
 9983:                                      description => $description,
 9984:                                      inst_code   => $inst_code,
 9985:                                      owner       => $course_owner,
 9986:                                      type        => $crstype,
 9987:                                      creator     => $env{'user.name'}.':'.
 9988:                                                     $env{'user.domain'},
 9989:                                      created     => $now,
 9990:                                      context     => $context,
 9991:                                                 },
 9992:                     };
 9993:     &courseidput($udom,$newcourse,$uhome,'notime');
 9994: # set toplevel url
 9995:     my $topurl=$url;
 9996:     unless ($nonstandard) {
 9997: # ------------------------------------------ For standard courses, make top url
 9998:         my $mapurl=&clutter($url);
 9999:         if ($mapurl eq '/res/') { $mapurl=''; }
10000:         $env{'form.initmap'}=(<<ENDINITMAP);
10001: <map>
10002: <resource id="1" type="start"></resource>
10003: <resource id="2" src="$mapurl"></resource>
10004: <resource id="3" type="finish"></resource>
10005: <link index="1" from="1" to="2"></link>
10006: <link index="2" from="2" to="3"></link>
10007: </map>
10008: ENDINITMAP
10009:         $topurl=&declutter(
10010:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10011:                           );
10012:     }
10013: # ----------------------------------------------------------- Write preferences
10014:     &writecoursepref($udom.'_'.$uname,
10015:                      ('description'              => $description,
10016:                       'url'                      => $topurl,
10017:                       'internal.creator'         => $env{'user.name'}.':'.
10018:                                                     $env{'user.domain'},
10019:                       'internal.created'         => $now,
10020:                       'internal.creationcontext' => $context)
10021:                     );
10022:     return '/'.$udom.'/'.$uname;
10023: }
10024: 
10025: # ------------------------------------------------------------------- Create ID
10026: sub generate_coursenum {
10027:     my ($udom,$crstype) = @_;
10028:     my $domdesc = &domain($udom);
10029:     return 'error: invalid domain' if ($domdesc eq '');
10030:     my $first;
10031:     if ($crstype eq 'Community') {
10032:         $first = '0';
10033:     } else {
10034:         $first = int(1+rand(9)); 
10035:     } 
10036:     my $uname=$first.
10037:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10038:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10039:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10040: # ----------------------------------------------- Make sure that does not exist
10041:     my $uhome=&homeserver($uname,$udom,'true');
10042:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10043:         if ($crstype eq 'Community') {
10044:             $first = '0';
10045:         } else {
10046:             $first = int(1+rand(9));
10047:         }
10048:         $uname=$first.
10049:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10050:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10051:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10052:         $uhome=&homeserver($uname,$udom,'true');
10053:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10054:             return 'error: unable to generate unique course-ID';
10055:         }
10056:     }
10057:     return $uname;
10058: }
10059: 
10060: sub is_course {
10061:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10062:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10063: 
10064:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10065:     my $uhome=&homeserver($cnum,$cdom);
10066:     my $iscourse;
10067:     if (grep { $_ eq $uhome } current_machine_ids()) {
10068:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10069:     } else {
10070:         my $hashid = $cdom.':'.$cnum;
10071:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10072:         unless (defined($cached)) {
10073:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10074:                                         $cnum,undef,undef,'.');
10075:             $iscourse = 0;
10076:             if (exists($courses{$cdom.'_'.$cnum})) {
10077:                 $iscourse = 1;
10078:             }
10079:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10080:         }
10081:     }
10082:     return unless ($iscourse);
10083:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10084: }
10085: 
10086: sub store_userdata {
10087:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10088:     my $result;
10089:     if ($datakey ne '') {
10090:         if (ref($storehash) eq 'HASH') {
10091:             if ($udom eq '' || $uname eq '') {
10092:                 $udom = $env{'user.domain'};
10093:                 $uname = $env{'user.name'};
10094:             }
10095:             my $uhome=&homeserver($uname,$udom);
10096:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10097:                 $result = 'error: no_host';
10098:             } else {
10099:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10100:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10101: 
10102:                 my $namevalue='';
10103:                 foreach my $key (keys(%{$storehash})) {
10104:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10105:                 }
10106:                 $namevalue=~s/\&$//;
10107:                 unless ($namespace eq 'courserequests') {
10108:                     $datakey = &escape($datakey);
10109:                 }
10110:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10111:                                   $namevalue,$uhome);
10112:             }
10113:         } else {
10114:             $result = 'error: data to store was not a hash reference'; 
10115:         }
10116:     } else {
10117:         $result= 'error: invalid requestkey'; 
10118:     }
10119:     return $result;
10120: }
10121: 
10122: # ---------------------------------------------------------- Assign Custom Role
10123: 
10124: sub assigncustomrole {
10125:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10126:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10127:                        $end,$start,$deleteflag,$selfenroll,$context);
10128: }
10129: 
10130: # ----------------------------------------------------------------- Revoke Role
10131: 
10132: sub revokerole {
10133:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10134:     my $now=time;
10135:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10136: }
10137: 
10138: # ---------------------------------------------------------- Revoke Custom Role
10139: 
10140: sub revokecustomrole {
10141:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10142:     my $now=time;
10143:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10144:            $deleteflag,$selfenroll,$context);
10145: }
10146: 
10147: # ------------------------------------------------------------ Disk usage
10148: sub diskusage {
10149:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10150:     $directorypath =~ s/\/$//;
10151:     my $listing=&reply('du2:'.&escape($directorypath).':'
10152:                        .&escape($getpropath).':'.&escape($uname).':'
10153:                        .&escape($udom),homeserver($uname,$udom));
10154:     if ($listing eq 'unknown_cmd') {
10155:         if ($getpropath) {
10156:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10157:         }
10158:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10159:     }
10160:     return $listing;
10161: }
10162: 
10163: sub is_locked {
10164:     my ($file_name, $domain, $user, $which) = @_;
10165:     my @check;
10166:     my $is_locked;
10167:     push (@check,$file_name);
10168:     my %locked = &get('file_permissions',\@check,
10169: 		      $env{'user.domain'},$env{'user.name'});
10170:     my ($tmp)=keys(%locked);
10171:     if ($tmp=~/^error:/) { undef(%locked); }
10172:     
10173:     if (ref($locked{$file_name}) eq 'ARRAY') {
10174:         $is_locked = 'false';
10175:         foreach my $entry (@{$locked{$file_name}}) {
10176:            if (ref($entry) eq 'ARRAY') {
10177:                $is_locked = 'true';
10178:                if (ref($which) eq 'ARRAY') {
10179:                    push(@{$which},$entry);
10180:                } else {
10181:                    last;
10182:                }
10183:            }
10184:        }
10185:     } else {
10186:         $is_locked = 'false';
10187:     }
10188:     return $is_locked;
10189: }
10190: 
10191: sub declutter_portfile {
10192:     my ($file) = @_;
10193:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10194:     return $file;
10195: }
10196: 
10197: # ------------------------------------------------------------- Mark as Read Only
10198: 
10199: sub mark_as_readonly {
10200:     my ($domain,$user,$files,$what) = @_;
10201:     my %current_permissions = &dump('file_permissions',$domain,$user);
10202:     my ($tmp)=keys(%current_permissions);
10203:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10204:     foreach my $file (@{$files}) {
10205: 	$file = &declutter_portfile($file);
10206:         push(@{$current_permissions{$file}},$what);
10207:     }
10208:     &put('file_permissions',\%current_permissions,$domain,$user);
10209:     return;
10210: }
10211: 
10212: # ------------------------------------------------------------Save Selected Files
10213: 
10214: sub save_selected_files {
10215:     my ($user, $path, @files) = @_;
10216:     my $filename = $user."savedfiles";
10217:     my @other_files = &files_not_in_path($user, $path);
10218:     open (OUT,'>',LONCAPA::tempdir().$filename);
10219:     foreach my $file (@files) {
10220:         print (OUT $env{'form.currentpath'}.$file."\n");
10221:     }
10222:     foreach my $file (@other_files) {
10223:         print (OUT $file."\n");
10224:     }
10225:     close (OUT);
10226:     return 'ok';
10227: }
10228: 
10229: sub clear_selected_files {
10230:     my ($user) = @_;
10231:     my $filename = $user."savedfiles";
10232:     open (OUT,'>',LONCAPA::tempdir().$filename);
10233:     print (OUT undef);
10234:     close (OUT);
10235:     return ("ok");    
10236: }
10237: 
10238: sub files_in_path {
10239:     my ($user, $path) = @_;
10240:     my $filename = $user."savedfiles";
10241:     my %return_files;
10242:     open (IN,'<',LONCAPA::tempdir().$filename);
10243:     while (my $line_in = <IN>) {
10244:         chomp ($line_in);
10245:         my @paths_and_file = split (m!/!, $line_in);
10246:         my $file_part = pop (@paths_and_file);
10247:         my $path_part = join ('/', @paths_and_file);
10248:         $path_part.='/';
10249:         my $path_and_file = $path_part.$file_part;
10250:         if ($path_part eq $path) {
10251:             $return_files{$file_part}= 'selected';
10252:         }
10253:     }
10254:     close (IN);
10255:     return (\%return_files);
10256: }
10257: 
10258: # called in portfolio select mode, to show files selected NOT in current directory
10259: sub files_not_in_path {
10260:     my ($user, $path) = @_;
10261:     my $filename = $user."savedfiles";
10262:     my @return_files;
10263:     my $path_part;
10264:     open(IN, '<',LONCAPA::tempdir().$filename);
10265:     while (my $line = <IN>) {
10266:         #ok, I know it's clunky, but I want it to work
10267:         my @paths_and_file = split(m|/|, $line);
10268:         my $file_part = pop(@paths_and_file);
10269:         chomp($file_part);
10270:         my $path_part = join('/', @paths_and_file);
10271:         $path_part .= '/';
10272:         my $path_and_file = $path_part.$file_part;
10273:         if ($path_part ne $path) {
10274:             push(@return_files, ($path_and_file));
10275:         }
10276:     }
10277:     close(OUT);
10278:     return (@return_files);
10279: }
10280: 
10281: #------------------------------Submitted/Handedback Portfolio Files Versioning
10282:  
10283: sub portfiles_versioning {
10284:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10285:     my $portfolio_root = '/userfiles/portfolio';
10286:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10287:     foreach my $file (@{$portfiles}) {
10288:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10289:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10290:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10291:         my $getpropath = 1;
10292:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10293:                                              $stu_name,$getpropath);
10294:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10295:         my $new_answer = 
10296:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10297:         if ($new_answer ne 'problem getting file') {
10298:             push(@{$versioned_portfiles}, $directory.$new_answer);
10299:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10300:                               [$symb,$env{'request.course.id'},'graded']);
10301:         }
10302:     }
10303: }
10304: 
10305: sub get_next_version {
10306:     my ($answer_name, $answer_ext, $dir_list) = @_;
10307:     my $version;
10308:     if (ref($dir_list) eq 'ARRAY') {
10309:         foreach my $row (@{$dir_list}) {
10310:             my ($file) = split(/\&/,$row,2);
10311:             my ($file_name,$file_version,$file_ext) =
10312:                 &file_name_version_ext($file);
10313:             if (($file_name eq $answer_name) &&
10314:                 ($file_ext eq $answer_ext)) {
10315:                      # gets here if filename and extension match,
10316:                      # regardless of version
10317:                 if ($file_version ne '') {
10318:                     # a versioned file is found  so save it for later
10319:                     if ($file_version > $version) {
10320:                         $version = $file_version;
10321:                     }
10322:                 }
10323:             }
10324:         }
10325:     }
10326:     $version ++;
10327:     return($version);
10328: }
10329: 
10330: sub version_selected_portfile {
10331:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10332:     my ($answer_name,$answer_ver,$answer_ext) =
10333:         &file_name_version_ext($file_name);
10334:     my $new_answer;
10335:     $env{'form.copy'} =
10336:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10337:     if($env{'form.copy'} eq '-1') {
10338:         $new_answer = 'problem getting file';
10339:     } else {
10340:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10341:         my $copy_result = 
10342:             &finishuserfileupload($stu_name,$domain,'copy',
10343:                                   '/portfolio'.$directory.$new_answer);
10344:     }
10345:     undef($env{'form.copy'});
10346:     return ($new_answer);
10347: }
10348: 
10349: sub file_name_version_ext {
10350:     my ($file)=@_;
10351:     my @file_parts = split(/\./, $file);
10352:     my ($name,$version,$ext);
10353:     if (@file_parts > 1) {
10354:         $ext=pop(@file_parts);
10355:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10356:             $version=pop(@file_parts);
10357:         }
10358:         $name=join('.',@file_parts);
10359:     } else {
10360:         $name=join('.',@file_parts);
10361:     }
10362:     return($name,$version,$ext);
10363: }
10364: 
10365: #----------------------------------------------Get portfolio file permissions
10366: 
10367: sub get_portfile_permissions {
10368:     my ($domain,$user) = @_;
10369:     my %current_permissions = &dump('file_permissions',$domain,$user);
10370:     my ($tmp)=keys(%current_permissions);
10371:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10372:     return \%current_permissions;
10373: }
10374: 
10375: #---------------------------------------------Get portfolio file access controls
10376: 
10377: sub get_access_controls {
10378:     my ($current_permissions,$group,$file) = @_;
10379:     my %access;
10380:     my $real_file = $file;
10381:     $file =~ s/\.meta$//;
10382:     if (defined($file)) {
10383:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10384:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10385:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10386:             }
10387:         }
10388:     } else {
10389:         foreach my $key (keys(%{$current_permissions})) {
10390:             if ($key =~ /\0accesscontrol$/) {
10391:                 if (defined($group)) {
10392:                     if ($key !~ m-^\Q$group\E/-) {
10393:                         next;
10394:                     }
10395:                 }
10396:                 my ($fullpath) = split(/\0/,$key);
10397:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10398:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10399:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10400:                     }
10401:                 }
10402:             }
10403:         }
10404:     }
10405:     return %access;
10406: }
10407: 
10408: sub modify_access_controls {
10409:     my ($file_name,$changes,$domain,$user)=@_;
10410:     my ($outcome,$deloutcome);
10411:     my %store_permissions;
10412:     my %new_values;
10413:     my %new_control;
10414:     my %translation;
10415:     my @deletions = ();
10416:     my $now = time;
10417:     if (exists($$changes{'activate'})) {
10418:         if (ref($$changes{'activate'}) eq 'HASH') {
10419:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10420:             my $numnew = scalar(@newitems);
10421:             for (my $i=0; $i<$numnew; $i++) {
10422:                 my $newkey = $newitems[$i];
10423:                 my $newid = &Apache::loncommon::get_cgi_id();
10424:                 if ($newkey =~ /^\d+:/) { 
10425:                     $newkey =~ s/^(\d+)/$newid/;
10426:                     $translation{$1} = $newid;
10427:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10428:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10429:                     $translation{$1} = $newid;
10430:                 }
10431:                 $new_values{$file_name."\0".$newkey} = 
10432:                                           $$changes{'activate'}{$newitems[$i]};
10433:                 $new_control{$newkey} = $now;
10434:             }
10435:         }
10436:     }
10437:     my %todelete;
10438:     my %changed_items;
10439:     foreach my $action ('delete','update') {
10440:         if (exists($$changes{$action})) {
10441:             if (ref($$changes{$action}) eq 'HASH') {
10442:                 foreach my $key (keys(%{$$changes{$action}})) {
10443:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10444:                     if ($action eq 'delete') { 
10445:                         $todelete{$itemnum} = 1;
10446:                     } else {
10447:                         $changed_items{$itemnum} = $key;
10448:                     }
10449:                 }
10450:             }
10451:         }
10452:     }
10453:     # get lock on access controls for file.
10454:     my $lockhash = {
10455:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10456:                                                        ':'.$env{'user.domain'},
10457:                    }; 
10458:     my $tries = 0;
10459:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10460:    
10461:     while (($gotlock ne 'ok') && $tries < 10) {
10462:         $tries ++;
10463:         sleep(0.1);
10464:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10465:     }
10466:     if ($gotlock eq 'ok') {
10467:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10468:         my ($tmp)=keys(%curr_permissions);
10469:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10470:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10471:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10472:             if (ref($curr_controls) eq 'HASH') {
10473:                 foreach my $control_item (keys(%{$curr_controls})) {
10474:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10475:                     if (defined($todelete{$itemnum})) {
10476:                         push(@deletions,$file_name."\0".$control_item);
10477:                     } else {
10478:                         if (defined($changed_items{$itemnum})) {
10479:                             $new_control{$changed_items{$itemnum}} = $now;
10480:                             push(@deletions,$file_name."\0".$control_item);
10481:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10482:                         } else {
10483:                             $new_control{$control_item} = $$curr_controls{$control_item};
10484:                         }
10485:                     }
10486:                 }
10487:             }
10488:         }
10489:         my ($group);
10490:         if (&is_course($domain,$user)) {
10491:             ($group,my $file) = split(/\//,$file_name,2);
10492:         }
10493:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10494:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10495:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10496:         #  remove lock
10497:         my @del_lock = ($file_name."\0".'locked_access_records');
10498:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10499:         my $sqlresult =
10500:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10501:                                     $group);
10502:     } else {
10503:         $outcome = "error: could not obtain lockfile\n";  
10504:     }
10505:     return ($outcome,$deloutcome,\%new_values,\%translation);
10506: }
10507: 
10508: sub make_public_indefinitely {
10509:     my (@requrl) = @_;
10510:     return &automated_portfile_access('public',\@requrl);
10511: }
10512: 
10513: sub automated_portfile_access {
10514:     my ($accesstype,$addsref,$delsref,$info) = @_;
10515:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10516:         return 'invalid';
10517:     }
10518:     my %urls;
10519:     if (ref($addsref) eq 'ARRAY') {
10520:         foreach my $requrl (@{$addsref}) {
10521:             if (&is_portfolio_url($requrl)) {
10522:                 unless (exists($urls{$requrl})) {
10523:                     $urls{$requrl} = 'add';
10524:                 }
10525:             }
10526:         }
10527:     }
10528:     if (ref($delsref) eq 'ARRAY') {
10529:         foreach my $requrl (@{$delsref}) { 
10530:             if (&is_portfolio_url($requrl)) {
10531:                 unless (exists($urls{$requrl})) {
10532:                     $urls{$requrl} = 'delete'; 
10533:                 }
10534:             }
10535:         }
10536:     }
10537:     unless (keys(%urls)) {
10538:         return 'invalid';
10539:     }
10540:     my $ip;
10541:     if ($accesstype eq 'ip') {
10542:         if (ref($info) eq 'HASH') {
10543:             if ($info->{'ip'} ne '') {
10544:                 $ip = $info->{'ip'};
10545:             }
10546:         }
10547:         if ($ip eq '') {
10548:             return 'invalid';
10549:         }
10550:     }
10551:     my $errors;
10552:     my $now = time;
10553:     my %current_perms;
10554:     foreach my $requrl (sort(keys(%urls))) {
10555:         my $action;
10556:         if ($urls{$requrl} eq 'add') {
10557:             $action = 'activate';
10558:         } else {
10559:             $action = 'none';
10560:         }
10561:         my $aclnum = 0;
10562:         my (undef,$udom,$unum,$file_name,$group) =
10563:             &parse_portfolio_url($requrl);
10564:         unless (exists($current_perms{$unum.':'.$udom})) {
10565:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10566:         }
10567:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10568:                                                    $group,$file_name);
10569:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10570:             my ($num,$scope,$end,$start) = 
10571:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10572:             if ($scope eq $accesstype) {
10573:                 if (($start <= $now) && ($end == 0)) {
10574:                     if ($accesstype eq 'ip') {
10575:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10576:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10577:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10578:                                     if ($urls{$requrl} eq 'add') {
10579:                                         $action = 'none';
10580:                                         last;
10581:                                     } else {
10582:                                         $action = 'delete';
10583:                                         $aclnum = $num;
10584:                                         last;
10585:                                     }
10586:                                 }
10587:                             }
10588:                         }
10589:                     } elsif ($accesstype eq 'public') {
10590:                         if ($urls{$requrl} eq 'add') {
10591:                             $action = 'none';
10592:                             last;
10593:                         } else {
10594:                             $action = 'delete';
10595:                             $aclnum = $num;
10596:                             last;
10597:                         }
10598:                     }
10599:                 } elsif ($accesstype eq 'public') {
10600:                     $action = 'update';
10601:                     $aclnum = $num;
10602:                     last;
10603:                 }
10604:             }
10605:         }
10606:         if ($action eq 'none') {
10607:             next;
10608:         } else {
10609:             my %changes;
10610:             my $newend = 0;
10611:             my $newstart = $now;
10612:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10613:             $changes{$action}{$newkey} = {
10614:                 type => $accesstype,
10615:                 time => {
10616:                     start => $newstart,
10617:                     end   => $newend,
10618:                 },
10619:             };
10620:             if ($accesstype eq 'ip') {
10621:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10622:             }
10623:             my ($outcome,$deloutcome,$new_values,$translation) =
10624:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10625:             unless ($outcome eq 'ok') {
10626:                 $errors .= $outcome.' ';
10627:             }
10628:         }
10629:     }
10630:     if ($errors) {
10631:         $errors =~ s/\s$//;
10632:         return $errors;
10633:     } else {
10634:         return 'ok';
10635:     }
10636: }
10637: 
10638: #------------------------------------------------------Get Marked as Read Only
10639: 
10640: sub get_marked_as_readonly {
10641:     my ($domain,$user,$what,$group) = @_;
10642:     my $current_permissions = &get_portfile_permissions($domain,$user);
10643:     my @readonly_files;
10644:     my $cmp1=$what;
10645:     if (ref($what)) { $cmp1=join('',@{$what}) };
10646:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10647:         if (defined($group)) {
10648:             if ($file_name !~ m-^\Q$group\E/-) {
10649:                 next;
10650:             }
10651:         }
10652:         if (ref($value) eq "ARRAY"){
10653:             foreach my $stored_what (@{$value}) {
10654:                 my $cmp2=$stored_what;
10655:                 if (ref($stored_what) eq 'ARRAY') {
10656:                     $cmp2=join('',@{$stored_what});
10657:                 }
10658:                 if ($cmp1 eq $cmp2) {
10659:                     push(@readonly_files, $file_name);
10660:                     last;
10661:                 } elsif (!defined($what)) {
10662:                     push(@readonly_files, $file_name);
10663:                     last;
10664:                 }
10665:             }
10666:         }
10667:     }
10668:     return @readonly_files;
10669: }
10670: #-----------------------------------------------------------Get Marked as Read Only Hash
10671: 
10672: sub get_marked_as_readonly_hash {
10673:     my ($current_permissions,$group,$what) = @_;
10674:     my %readonly_files;
10675:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10676:         if (defined($group)) {
10677:             if ($file_name !~ m-^\Q$group\E/-) {
10678:                 next;
10679:             }
10680:         }
10681:         if (ref($value) eq "ARRAY"){
10682:             foreach my $stored_what (@{$value}) {
10683:                 if (ref($stored_what) eq 'ARRAY') {
10684:                     foreach my $lock_descriptor(@{$stored_what}) {
10685:                         if ($lock_descriptor eq 'graded') {
10686:                             $readonly_files{$file_name} = 'graded';
10687:                         } elsif ($lock_descriptor eq 'handback') {
10688:                             $readonly_files{$file_name} = 'handback';
10689:                         } else {
10690:                             if (!exists($readonly_files{$file_name})) {
10691:                                 $readonly_files{$file_name} = 'locked';
10692:                             }
10693:                         }
10694:                     }
10695:                 } 
10696:             }
10697:         } 
10698:     }
10699:     return %readonly_files;
10700: }
10701: # ------------------------------------------------------------ Unmark as Read Only
10702: 
10703: sub unmark_as_readonly {
10704:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10705:     # for portfolio submissions, $what contains [$symb,$crsid] 
10706:     my ($domain,$user,$what,$file_name,$group) = @_;
10707:     $file_name = &declutter_portfile($file_name);
10708:     my $symb_crs = $what;
10709:     if (ref($what)) { $symb_crs=join('',@$what); }
10710:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10711:     my ($tmp)=keys(%current_permissions);
10712:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10713:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10714:     foreach my $file (@readonly_files) {
10715: 	my $clean_file = &declutter_portfile($file);
10716: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10717: 	my $current_locks = $current_permissions{$file};
10718:         my @new_locks;
10719:         my @del_keys;
10720:         if (ref($current_locks) eq "ARRAY"){
10721:             foreach my $locker (@{$current_locks}) {
10722:                 my $compare=$locker;
10723:                 if (ref($locker) eq 'ARRAY') {
10724:                     $compare=join('',@{$locker});
10725:                     if ($compare ne $symb_crs) {
10726:                         push(@new_locks, $locker);
10727:                     }
10728:                 }
10729:             }
10730:             if (scalar(@new_locks) > 0) {
10731:                 $current_permissions{$file} = \@new_locks;
10732:             } else {
10733:                 push(@del_keys, $file);
10734:                 &del('file_permissions',\@del_keys, $domain, $user);
10735:                 delete($current_permissions{$file});
10736:             }
10737:         }
10738:     }
10739:     &put('file_permissions',\%current_permissions,$domain,$user);
10740:     return;
10741: }
10742: 
10743: # ------------------------------------------------------------ Directory lister
10744: 
10745: sub dirlist {
10746:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10747:     $uri=~s/^\///;
10748:     $uri=~s/\/$//;
10749:     my ($udom, $uname);
10750:     if ($getuserdir) {
10751:         $udom = $userdomain;
10752:         $uname = $username;
10753:     } else {
10754:         (undef,$udom,$uname)=split(/\//,$uri);
10755:         if(defined($userdomain)) {
10756:             $udom = $userdomain;
10757:         }
10758:         if(defined($username)) {
10759:             $uname = $username;
10760:         }
10761:     }
10762:     my ($dirRoot,$listing,@listing_results);
10763: 
10764:     $dirRoot = $perlvar{'lonDocRoot'};
10765:     if (defined($getpropath)) {
10766:         $dirRoot = &propath($udom,$uname);
10767:         $dirRoot =~ s/\/$//;
10768:     } elsif (defined($getuserdir)) {
10769:         my $subdir=$uname.'__';
10770:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10771:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10772:                    ."/$udom/$subdir/$uname";
10773:     } elsif (defined($alternateRoot)) {
10774:         $dirRoot = $alternateRoot;
10775:     }
10776: 
10777:     if($udom) {
10778:         if($uname) {
10779:             my $uhome = &homeserver($uname,$udom);
10780:             if ($uhome eq 'no_host') {
10781:                 return ([],'no_host');
10782:             }
10783:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10784:                               .$getuserdir.':'.&escape($dirRoot)
10785:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10786:             if ($listing eq 'unknown_cmd') {
10787:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10788:             } else {
10789:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10790:             }
10791:             if ($listing eq 'unknown_cmd') {
10792:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10793:                 @listing_results = split(/:/,$listing);
10794:             } else {
10795:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10796:             }
10797:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10798:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10799:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10800:                 return ([],$listing);
10801:             } else {
10802:                 return (\@listing_results);
10803:             }
10804:         } elsif(!$alternateRoot) {
10805:             my (%allusers,%listerror);
10806: 	    my %servers = &get_servers($udom,'library');
10807:  	    foreach my $tryserver (keys(%servers)) {
10808:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10809:                                   &escape($udom),$tryserver);
10810:                 if ($listing eq 'unknown_cmd') {
10811: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10812: 				      $udom, $tryserver);
10813:                 } else {
10814:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10815:                 }
10816: 		if ($listing eq 'unknown_cmd') {
10817: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10818: 				      $udom, $tryserver);
10819: 		    @listing_results = split(/:/,$listing);
10820: 		} else {
10821: 		    @listing_results =
10822: 			map { &unescape($_); } split(/:/,$listing);
10823: 		}
10824:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10825:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10826:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10827:                     $listerror{$tryserver} = $listing;
10828:                 } else {
10829: 		    foreach my $line (@listing_results) {
10830: 			my ($entry) = split(/&/,$line,2);
10831: 			$allusers{$entry} = 1;
10832: 		    }
10833: 		}
10834:             }
10835:             my @alluserslist=();
10836:             foreach my $user (sort(keys(%allusers))) {
10837:                 push(@alluserslist,$user.'&user');
10838:             }
10839: 
10840:             if (!%listerror) {
10841:                 # no errors
10842:                 return (\@alluserslist);
10843:             } elsif (scalar(keys(%servers)) == 1) {
10844:                 # one library server, one error 
10845:                 my ($key) = keys(%listerror);
10846:                 return (\@alluserslist, $listerror{$key});
10847:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10848:                 # con_lost indicates that we might miss data from at least one
10849:                 # library server
10850:                 return (\@alluserslist, 'con_lost');
10851:             } else {
10852:                 # multiple library servers and no con_lost -> data should be
10853:                 # complete. 
10854:                 return (\@alluserslist);
10855:             }
10856: 
10857:         } else {
10858:             return ([],'missing username');
10859:         }
10860:     } elsif(!defined($getpropath)) {
10861:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10862:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10863:         return (\@all_domains);
10864:     } else {
10865:         return ([],'missing domain');
10866:     }
10867: }
10868: 
10869: # --------------------------------------------- GetFileTimestamp
10870: # This function utilizes dirlist and returns the date stamp for
10871: # when it was last modified.  It will also return an error of -1
10872: # if an error occurs
10873: 
10874: sub GetFileTimestamp {
10875:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10876:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10877:     $studentName   = &LONCAPA::clean_username($studentName);
10878:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10879:                                     undef,$getuserdir);
10880:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10881:         return -1;
10882:     }
10883:     if (ref($fileref) eq 'ARRAY') {
10884:         my @stats = split('&',$fileref->[0]);
10885:         # @stats contains first the filename, then the stat output
10886:         return $stats[10]; # so this is 10 instead of 9.
10887:     } else {
10888:         return -1;
10889:     }
10890: }
10891: 
10892: sub stat_file {
10893:     my ($uri) = @_;
10894:     $uri = &clutter_with_no_wrapper($uri);
10895: 
10896:     my ($udom,$uname,$file);
10897:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10898: 	($udom,$uname,$file) =
10899: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10900: 	$file = 'userfiles/'.$file;
10901:     }
10902:     if ($uri =~ m-^/res/-) {
10903: 	($udom,$uname) = 
10904: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10905: 	$file = $uri;
10906:     }
10907: 
10908:     if (!$udom || !$uname || !$file) {
10909: 	# unable to handle the uri
10910: 	return ();
10911:     }
10912:     my $getpropath;
10913:     if ($file =~ /^userfiles\//) {
10914:         $getpropath = 1;
10915:     }
10916:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10917:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10918:         return ();
10919:     } else {
10920:         if (ref($listref) eq 'ARRAY') {
10921:             my @stats = split('&',$listref->[0]);
10922: 	    shift(@stats); #filename is first
10923: 	    return @stats;
10924:         }
10925:     }
10926:     return ();
10927: }
10928: 
10929: # --------------------------------------------------------- recursedirs
10930: # Recursive function to traverse either a specific user's Authoring Space
10931: # or corresponding Published Resource Space, and populate the hash ref:
10932: # $dirhashref with URLs of all directories, and if $filehashref hash
10933: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10934: # or .rights files in resource space, and .meta, .save, .log, and .bak
10935: # files in Authoring Space.
10936: #
10937: # Inputs:
10938: #
10939: # $is_home - true if current server is home server for user's space
10940: # $context - either: priv, or res respectively for Authoring or Resource Space.
10941: # $docroot - Document root (i.e., /home/httpd/html
10942: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10943: # $relpath - Current path (relative to top level).
10944: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10945: # $filehashref - reference to hash to populate with URLs of files (Optional)
10946: #
10947: # Returns: nothing
10948: #
10949: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10950: #
10951: # Currently used by interface/londocs.pm to create linked select boxes for
10952: # directory and filename to import a Course "Author" resource into a course, and
10953: # also to create linked select boxes for Authoring Space and Directory to choose
10954: # save location for creation of a new "standard" problem from the Course Editor.
10955: #
10956: 
10957: sub recursedirs {
10958:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10959:     return unless (ref($dirhashref) eq 'HASH');
10960:     my $currpath = $docroot.$toppath;
10961:     if ($relpath) {
10962:         $currpath .= "/$relpath";
10963:     }
10964:     my $savefile;
10965:     if (ref($filehashref)) {
10966:         $savefile = 1;
10967:     }
10968:     if ($is_home) {
10969:         if (opendir(my $dirh,$currpath)) {
10970:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10971:                 next if ($item eq '');
10972:                 if (-d "$currpath/$item") {
10973:                     my $newpath;
10974:                     if ($relpath) {
10975:                         $newpath = "$relpath/$item";
10976:                     } else {
10977:                         $newpath = $item;
10978:                     }
10979:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10980:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10981:                 } elsif ($savefile) {
10982:                     if ($context eq 'priv') {
10983:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10984:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10985:                         }
10986:                     } else {
10987:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10988:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10989:                         }
10990:                     }
10991:                 }
10992:             }
10993:             closedir($dirh);
10994:         }
10995:     } else {
10996:         my ($dirlistref,$listerror) =
10997:             &dirlist($toppath.$relpath);
10998:         my @dir_lines;
10999:         my $dirptr=16384;
11000:         if (ref($dirlistref) eq 'ARRAY') {
11001:             foreach my $dir_line (sort
11002:                               {
11003:                                   my ($afile)=split('&',$a,2);
11004:                                   my ($bfile)=split('&',$b,2);
11005:                                   return (lc($afile) cmp lc($bfile));
11006:                               } (@{$dirlistref})) {
11007:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11008:                     split(/\&/,$dir_line,16);
11009:                 $item =~ s/\s+$//;
11010:                 next if (($item =~ /^\.\.?$/) || ($obs));
11011:                 if ($dirptr&$testdir) {
11012:                     my $newpath;
11013:                     if ($relpath) {
11014:                         $newpath = "$relpath/$item";
11015:                     } else {
11016:                         $relpath = '/';
11017:                         $newpath = $item;
11018:                     }
11019:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11020:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11021:                 } elsif ($savefile) {
11022:                     if ($context eq 'priv') {
11023:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11024:                             $filehashref->{$relpath}{$item} = 1;
11025:                         }
11026:                     } else {
11027:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11028:                             $filehashref->{$relpath}{$item} = 1;
11029:                         }
11030:                     }
11031:                 }
11032:             }
11033:         }
11034:     }
11035:     return;
11036: }
11037: 
11038: # -------------------------------------------------------- Value of a Condition
11039: 
11040: # gets the value of a specific preevaluated condition
11041: #    stored in the string  $env{user.state.<cid>}
11042: # or looks up a condition reference in the bighash and if if hasn't
11043: # already been evaluated recurses into docondval to get the value of
11044: # the condition, then memoizing it to 
11045: #   $env{user.state.<cid>.<condition>}
11046: sub directcondval {
11047:     my $number=shift;
11048:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11049: 	&Apache::lonuserstate::evalstate();
11050:     }
11051:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11052: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11053:     } elsif ($number =~ /^_/) {
11054: 	my $sub_condition;
11055: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11056: 		&GDBM_READER(),0640)) {
11057: 	    $sub_condition=$bighash{'conditions'.$number};
11058: 	    untie(%bighash);
11059: 	}
11060: 	my $value = &docondval($sub_condition);
11061: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11062: 	return $value;
11063:     }
11064:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11065:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11066:     } else {
11067:        return 2;
11068:     }
11069: }
11070: 
11071: # get the collection of conditions for this resource
11072: sub condval {
11073:     my $condidx=shift;
11074:     my $allpathcond='';
11075:     foreach my $cond (split(/\|/,$condidx)) {
11076: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11077: 	    $allpathcond.=
11078: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11079: 	}
11080:     }
11081:     $allpathcond=~s/\|$//;
11082:     return &docondval($allpathcond);
11083: }
11084: 
11085: #evaluates an expression of conditions
11086: sub docondval {
11087:     my ($allpathcond) = @_;
11088:     my $result=0;
11089:     if ($env{'request.course.id'}
11090: 	&& defined($allpathcond)) {
11091: 	my $operand='|';
11092: 	my @stack;
11093: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11094: 	    if ($chunk eq '(') {
11095: 		push @stack,($operand,$result);
11096: 	    } elsif ($chunk eq ')') {
11097: 		my $before=pop @stack;
11098: 		if (pop @stack eq '&') {
11099: 		    $result=$result>$before?$before:$result;
11100: 		} else {
11101: 		    $result=$result>$before?$result:$before;
11102: 		}
11103: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11104: 		$operand=$chunk;
11105: 	    } else {
11106: 		my $new=directcondval($chunk);
11107: 		if ($operand eq '&') {
11108: 		    $result=$result>$new?$new:$result;
11109: 		} else {
11110: 		    $result=$result>$new?$result:$new;
11111: 		}
11112: 	    }
11113: 	}
11114:     }
11115:     return $result;
11116: }
11117: 
11118: # ---------------------------------------------------- Devalidate courseresdata
11119: 
11120: sub devalidatecourseresdata {
11121:     my ($coursenum,$coursedomain)=@_;
11122:     my $hashid=$coursenum.':'.$coursedomain;
11123:     &devalidate_cache_new('courseres',$hashid);
11124: }
11125: 
11126: 
11127: # --------------------------------------------------- Course Resourcedata Query
11128: #
11129: #  Parameters:
11130: #      $coursenum    - Number of the course.
11131: #      $coursedomain - Domain at which the course was created.
11132: #  Returns:
11133: #     A hash of the course parameters along (I think) with timestamps
11134: #     and version info.
11135: 
11136: sub get_courseresdata {
11137:     my ($coursenum,$coursedomain)=@_;
11138:     my $coursehom=&homeserver($coursenum,$coursedomain);
11139:     my $hashid=$coursenum.':'.$coursedomain;
11140:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11141:     my %dumpreply;
11142:     unless (defined($cached)) {
11143: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11144: 	$result=\%dumpreply;
11145: 	my ($tmp) = keys(%dumpreply);
11146: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11147: 	    &do_cache_new('courseres',$hashid,$result,600);
11148: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11149: 	    return $tmp;
11150: 	} elsif ($tmp =~ /^(error)/) {
11151: 	    $result=undef;
11152: 	    &do_cache_new('courseres',$hashid,$result,600);
11153: 	}
11154:     }
11155:     return $result;
11156: }
11157: 
11158: sub devalidateuserresdata {
11159:     my ($uname,$udom)=@_;
11160:     my $hashid="$udom:$uname";
11161:     &devalidate_cache_new('userres',$hashid);
11162: }
11163: 
11164: sub get_userresdata {
11165:     my ($uname,$udom)=@_;
11166:     #most student don\'t have any data set, check if there is some data
11167:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11168: 
11169:     my $hashid="$udom:$uname";
11170:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11171:     if (!defined($cached)) {
11172: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11173: 	$result=\%resourcedata;
11174: 	&do_cache_new('userres',$hashid,$result,600);
11175:     }
11176:     my ($tmp)=keys(%$result);
11177:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11178: 	return $result;
11179:     }
11180:     #error 2 occurs when the .db doesn't exist
11181:     if ($tmp!~/error: 2 /) {
11182:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11183: 	    &logthis("<font color=\"blue\">WARNING:".
11184: 		     " Trying to get resource data for ".
11185: 		     $uname." at ".$udom.": ".
11186: 		     $tmp."</font>");
11187:         }
11188:     } elsif ($tmp=~/error: 2 /) {
11189: 	#&EXT_cache_set($udom,$uname);
11190: 	&do_cache_new('userres',$hashid,undef,600);
11191: 	undef($tmp); # not really an error so don't send it back
11192:     }
11193:     return $tmp;
11194: }
11195: #----------------------------------------------- resdata - return resource data
11196: #  Purpose:
11197: #    Return resource data for either users or for a course.
11198: #  Parameters:
11199: #     $name      - Course/user name.
11200: #     $domain    - Name of the domain the user/course is registered on.
11201: #     $type      - Type of thing $name is (must be 'course' or 'user')
11202: #     $mapp      - decluttered URL of enclosing map  
11203: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11204: #     $recurseup - Ref to array of map URLs, starting with map containing
11205: #                  $mapp up through hierarchy of nested maps to top level map.  
11206: #     $courseid  - CourseID (first part of param identifier).
11207: #     $modifier  - Middle part of param identifier.
11208: #     $what      - Last part of param identifier.
11209: #     @which     - Array of names of resources desired.
11210: #  Returns:
11211: #     The value of the first reasource in @which that is found in the
11212: #     resource hash.
11213: #  Exceptional Conditions:
11214: #     If the $type passed in is not valid (not the string 'course' or 
11215: #     'user', an undefined  reference is returned.
11216: #     If none of the resources are found, an undef is returned
11217: sub resdata {
11218:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11219:         $modifier,$what,@which)=@_;
11220:     my $result;
11221:     if ($type eq 'course') {
11222: 	$result=&get_courseresdata($name,$domain);
11223:     } elsif ($type eq 'user') {
11224: 	$result=&get_userresdata($name,$domain);
11225:     }
11226:     if (!ref($result)) { return $result; }    
11227:     foreach my $item (@which) {
11228:         if ($item->[1] eq 'course') {
11229:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11230:                 unless ($$recursed) {
11231:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11232:                     $$recursed = 1;
11233:                 }
11234:                 foreach my $item (@${recurseup}) {
11235:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11236:                     last if (defined($result->{$norecursechk}));
11237:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11238:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11239:                 }
11240:             }
11241:         }
11242:         if (defined($result->{$item->[0]})) {
11243: 	    return [$result->{$item->[0]},$item->[1]];
11244: 	}
11245:     }
11246:     return undef;
11247: }
11248: 
11249: sub get_domain_lti {
11250:     my ($cdom,$context) = @_;
11251:     my ($name,%lti);
11252:     if ($context eq 'consumer') {
11253:         $name = 'ltitools';
11254:     } elsif ($context eq 'provider') {
11255:         $name = 'lti';
11256:     } else {
11257:         return %lti;
11258:     }
11259:     my ($result,$cached)=&is_cached_new($name,$cdom);
11260:     if (defined($cached)) {
11261:         if (ref($result) eq 'HASH') {
11262:             %lti = %{$result};
11263:         }
11264:     } else {
11265:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11266:         if (ref($domconfig{$name}) eq 'HASH') {
11267:             %lti = %{$domconfig{$name}};
11268:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11269:             if (ref($encdomconfig{$name}) eq 'HASH') {
11270:                 foreach my $id (keys(%lti)) {
11271:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11272:                         foreach my $item ('key','secret') {
11273:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11274:                         }
11275:                     }
11276:                 }
11277:             }
11278:         }
11279:         my $cachetime = 24*60*60;
11280:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11281:     }
11282:     return %lti;
11283: }
11284: 
11285: sub get_numsuppfiles {
11286:     my ($cnum,$cdom,$ignorecache)=@_;
11287:     my $hashid=$cnum.':'.$cdom;
11288:     my ($suppcount,$cached);
11289:     unless ($ignorecache) {
11290:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11291:     }
11292:     unless (defined($cached)) {
11293:         my $chome=&homeserver($cnum,$cdom);
11294:         unless ($chome eq 'no_host') {
11295:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11296:             my $suppmap = 'supplemental.sequence';
11297:             ($suppcount,$supptools,$errors) =
11298:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11299:                                                          $supptools,$errors);
11300:         }
11301:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11302:     }
11303:     return $suppcount;
11304: }
11305: 
11306: #
11307: # EXT resource caching routines
11308: #
11309: 
11310: {
11311: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11312: #
11313: # The course for which we cache
11314: my $cachedmapkey='';
11315: # The cached recursive maps for this course
11316: my %cachedmaps=();
11317: # When this was last done
11318: my $cachedmaptime='';
11319: 
11320: sub clear_EXT_cache_status {
11321:     &delenv('cache.EXT.');
11322: }
11323: 
11324: sub EXT_cache_status {
11325:     my ($target_domain,$target_user) = @_;
11326:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11327:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11328:         # We know already the user has no data
11329:         return 1;
11330:     } else {
11331:         return 0;
11332:     }
11333: }
11334: 
11335: sub EXT_cache_set {
11336:     my ($target_domain,$target_user) = @_;
11337:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11338:     #&appenv({$cachename => time});
11339: }
11340: 
11341: # --------------------------------------------------------- Value of a Variable
11342: sub EXT {
11343: 
11344:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11345:     unless ($varname) { return ''; }
11346:     #get real user name/domain, courseid and symb
11347:     my $courseid;
11348:     my $publicuser;
11349:     if ($symbparm) {
11350: 	$symbparm=&get_symb_from_alias($symbparm);
11351:     }
11352:     if (!($uname && $udom)) {
11353:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11354:       if (!$symbparm) {	$symbparm=$cursymb; }
11355:     } else {
11356: 	$courseid=$env{'request.course.id'};
11357:     }
11358:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11359:     my $rest;
11360:     if (defined($therest[0])) {
11361:        $rest=join('.',@therest);
11362:     } else {
11363:        $rest='';
11364:     }
11365: 
11366:     my $qualifierrest=$qualifier;
11367:     if ($rest) { $qualifierrest.='.'.$rest; }
11368:     my $spacequalifierrest=$space;
11369:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11370:     if ($realm eq 'user') {
11371: # --------------------------------------------------------------- user.resource
11372: 	if ($space eq 'resource') {
11373: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11374: 		  || defined($Apache::lonhomework::parsing_a_task))
11375: 		 &&
11376: 		 ($symbparm eq &symbread()) ) {	
11377: 		# if we are in the middle of processing the resource the
11378: 		# get the value we are planning on committing
11379:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11380:                     return $Apache::lonhomework::results{$qualifierrest};
11381:                 } else {
11382:                     return $Apache::lonhomework::history{$qualifierrest};
11383:                 }
11384: 	    } else {
11385: 		my %restored;
11386: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11387: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11388: 		} else {
11389: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11390: 		}
11391: 		return $restored{$qualifierrest};
11392: 	    }
11393: # ----------------------------------------------------------------- user.access
11394:         } elsif ($space eq 'access') {
11395: 	    # FIXME - not supporting calls for a specific user
11396:             return &allowed($qualifier,$rest);
11397: # ------------------------------------------ user.preferences, user.environment
11398:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11399: 	    if (($uname eq $env{'user.name'}) &&
11400: 		($udom eq $env{'user.domain'})) {
11401: 		return $env{join('.',('environment',$qualifierrest))};
11402: 	    } else {
11403: 		my %returnhash;
11404: 		if (!$publicuser) {
11405: 		    %returnhash=&userenvironment($udom,$uname,
11406: 						 $qualifierrest);
11407: 		}
11408: 		return $returnhash{$qualifierrest};
11409: 	    }
11410: # ----------------------------------------------------------------- user.course
11411:         } elsif ($space eq 'course') {
11412: 	    # FIXME - not supporting calls for a specific user
11413:             return $env{join('.',('request.course',$qualifier))};
11414: # ------------------------------------------------------------------- user.role
11415:         } elsif ($space eq 'role') {
11416: 	    # FIXME - not supporting calls for a specific user
11417:             my ($role,$where)=split(/\./,$env{'request.role'});
11418:             if ($qualifier eq 'value') {
11419: 		return $role;
11420:             } elsif ($qualifier eq 'extent') {
11421:                 return $where;
11422:             }
11423: # ----------------------------------------------------------------- user.domain
11424:         } elsif ($space eq 'domain') {
11425:             return $udom;
11426: # ------------------------------------------------------------------- user.name
11427:         } elsif ($space eq 'name') {
11428:             return $uname;
11429: # ---------------------------------------------------- Any other user namespace
11430:         } else {
11431: 	    my %reply;
11432: 	    if (!$publicuser) {
11433: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11434: 	    }
11435: 	    return $reply{$qualifierrest};
11436:         }
11437:     } elsif ($realm eq 'query') {
11438: # ---------------------------------------------- pull stuff out of query string
11439:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11440: 						[$spacequalifierrest]);
11441: 	return $env{'form.'.$spacequalifierrest}; 
11442:    } elsif ($realm eq 'request') {
11443: # ------------------------------------------------------------- request.browser
11444:         if ($space eq 'browser') {
11445:             return $env{'browser.'.$qualifier};
11446: # ------------------------------------------------------------ request.filename
11447:         } else {
11448:             return $env{'request.'.$spacequalifierrest};
11449:         }
11450:     } elsif ($realm eq 'course') {
11451: # ---------------------------------------------------------- course.description
11452:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11453:     } elsif ($realm eq 'resource') {
11454: 
11455: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11456: 	    if (!$symbparm) { $symbparm=&symbread(); }
11457: 	}
11458: 
11459:         if ($qualifier eq '') {
11460: 	    if ($space eq 'title') {
11461: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11462: 	        return &gettitle($symbparm);
11463: 	    }
11464: 	
11465: 	    if ($space eq 'map') {
11466: 	        my ($map) = &decode_symb($symbparm);
11467: 	        return &symbread($map);
11468: 	    }
11469:             if ($space eq 'maptitle') {
11470:                 my ($map) = &decode_symb($symbparm);
11471:                 return &gettitle($map);
11472:             }
11473: 	    if ($space eq 'filename') {
11474: 	        if ($symbparm) {
11475: 		    return &clutter((&decode_symb($symbparm))[2]);
11476: 	        }
11477: 	        return &hreflocation('',$env{'request.filename'});
11478: 	    }
11479: 
11480:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11481:                 if ($space eq 'visibleparts') {
11482:                     my $navmap = Apache::lonnavmaps::navmap->new();
11483:                     my $item;
11484:                     if (ref($navmap)) {
11485:                         my $res = $navmap->getBySymb($symbparm);
11486:                         my $parts = $res->parts();
11487:                         if (ref($parts) eq 'ARRAY') {
11488:                             $item = join(',',@{$parts});
11489:                         }
11490:                         undef($navmap);
11491:                     }
11492:                     return $item;
11493:                 }
11494:             }
11495:         }
11496: 
11497: 	my ($section, $group, @groups, @recurseup, $recursed);
11498: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11499:         if (($courseid eq '') && ($cid)) {
11500:             $courseid = $cid;
11501:         }
11502: 	if (($symbparm && $courseid) && 
11503: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11504: 
11505: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11506: 
11507: # ----------------------------------------------------- Cascading lookup scheme
11508: 	    my $symbp=$symbparm;
11509: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11510: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11511:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11512: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11513: 	    if (($env{'user.name'} eq $uname) &&
11514: 		($env{'user.domain'} eq $udom)) {
11515: 		$section=$env{'request.course.sec'};
11516:                 @groups = split(/:/,$env{'request.course.groups'});  
11517:                 @groups=&sort_course_groups($courseid,@groups); 
11518: 	    } else {
11519: 		if (! defined($usection)) {
11520: 		    $section=&getsection($udom,$uname,$courseid);
11521: 		} else {
11522: 		    $section = $usection;
11523: 		}
11524:                 @groups = &get_users_groups($udom,$uname,$courseid);
11525: 	    }
11526: 
11527: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11528: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11529:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11530: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11531: 
11532: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11533: 	    my $courselevelr=$courseid.'.'.$symbparm;
11534:             $courseleveli=$courseid.'.'.$recurseparm;
11535: 	    $courselevelm=$courseid.'.'.$mapparm;
11536: 
11537: # ----------------------------------------------------------- first, check user
11538: 
11539: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11540:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11541: 				       ([$courselevelr,'resource'],
11542: 					[$courselevelm,'map'     ],
11543:                                         [$courseleveli,'map'     ],
11544: 					[$courselevel, 'course'  ]));
11545: 	    if (defined($userreply)) { return &get_reply($userreply); }
11546: 
11547: # ------------------------------------------------ second, check some of course
11548:             my $coursereply;
11549:             if (@groups > 0) {
11550:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11551:                                        $recurseparm,$mapparm,$spacequalifierrest,
11552:                                        $mapp,\$recursed,\@recurseup);
11553:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11554:             }
11555: 
11556: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11557: 				  $env{'course.'.$courseid.'.domain'},
11558: 				  'course',$mapp,\$recursed,\@recurseup,
11559:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11560: 				  ([$seclevelr,   'resource'],
11561: 				   [$seclevelm,   'map'     ],
11562:                                    [$secleveli,   'map'     ],
11563: 				   [$seclevel,    'course'  ],
11564: 				   [$courselevelr,'resource']));
11565: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11566: 
11567: # ------------------------------------------------------ third, check map parms
11568: 	    my %parmhash=();
11569: 	    my $thisparm='';
11570: 	    if (tie(%parmhash,'GDBM_File',
11571: 		    $env{'request.course.fn'}.'_parms.db',
11572: 		    &GDBM_READER(),0640)) {
11573: 		$thisparm=$parmhash{$symbparm};
11574: 		untie(%parmhash);
11575: 	    }
11576: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11577: 	}
11578: # ------------------------------------------ fourth, look in resource metadata
11579:  
11580:         my $what = $spacequalifierrest;
11581: 	$what=~s/\./\_/;
11582: 	my $filename;
11583: 	if (!$symbparm) { $symbparm=&symbread(); }
11584: 	if ($symbparm) {
11585: 	    $filename=(&decode_symb($symbparm))[2];
11586: 	} else {
11587: 	    $filename=$env{'request.filename'};
11588: 	}
11589:         my $toolsymb;
11590:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11591:             $toolsymb = $symbparm;
11592:         }
11593: 	my $metadata=&metadata($filename,$what,$toolsymb);
11594: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11595: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11596: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11597: 
11598: # ----------------------------------------------- fifth, look in rest of course
11599: 	if ($symbparm && defined($courseid) && 
11600: 	    $courseid eq $env{'request.course.id'}) {
11601: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11602: 				     $env{'course.'.$courseid.'.domain'},
11603: 				     'course',$mapp,\$recursed,\@recurseup,
11604:                                      $courseid,'.',$spacequalifierrest,
11605: 				     ([$courselevelm,'map'   ],
11606:                                       [$courseleveli,'map'   ],
11607: 				      [$courselevel, 'course']));
11608: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11609: 	}
11610: # ------------------------------------------------------------------ Cascade up
11611: 	unless ($space eq '0') {
11612: 	    my @parts=split(/_/,$space);
11613: 	    my $id=pop(@parts);
11614: 	    my $part=join('_',@parts);
11615: 	    if ($part eq '') { $part='0'; }
11616: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11617: 				 $symbparm,$udom,$uname,$section,1);
11618: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11619: 	}
11620: 	if ($recurse) { return undef; }
11621: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11622: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11623: # ---------------------------------------------------- Any other user namespace
11624:     } elsif ($realm eq 'environment') {
11625: # ----------------------------------------------------------------- environment
11626: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11627: 	    return $env{'environment.'.$spacequalifierrest};
11628: 	} else {
11629: 	    if ($uname eq 'anonymous' && $udom eq '') {
11630: 		return '';
11631: 	    }
11632: 	    my %returnhash=&userenvironment($udom,$uname,
11633: 					    $spacequalifierrest);
11634: 	    return $returnhash{$spacequalifierrest};
11635: 	}
11636:     } elsif ($realm eq 'system') {
11637: # ----------------------------------------------------------------- system.time
11638: 	if ($space eq 'time') {
11639: 	    return time;
11640:         }
11641:     } elsif ($realm eq 'server') {
11642: # ----------------------------------------------------------------- system.time
11643: 	if ($space eq 'name') {
11644: 	    return $ENV{'SERVER_NAME'};
11645:         }
11646:     }
11647:     return '';
11648: }
11649: 
11650: sub get_reply {
11651:     my ($reply_value) = @_;
11652:     if (ref($reply_value) eq 'ARRAY') {
11653:         if (wantarray) {
11654: 	    return @$reply_value;
11655:         }
11656:         return $reply_value->[0];
11657:     } else {
11658:         return $reply_value;
11659:     }
11660: }
11661: 
11662: sub check_group_parms {
11663:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11664:         $recursed,$recurseupref) = @_;
11665:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11666:                   [$what,'course']);
11667:     my $coursereply;
11668:     foreach my $group (@{$groups}) {
11669:         my @groupitems = ();
11670:         foreach my $level (@levels) {
11671:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11672:              push(@groupitems,[$item,$level->[1]]);
11673:         }
11674:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11675:                                    $env{'course.'.$courseid.'.domain'},
11676:                                    'course',$mapp,$recursed,$recurseupref,
11677:                                    $courseid,'.['.$group.'].',$what,
11678:                                    @groupitems);
11679:         last if (defined($coursereply));
11680:     }
11681:     return $coursereply;
11682: }
11683: 
11684: sub get_map_hierarchy {
11685:     my ($mapname,$courseid) = @_;
11686:     my @recurseup = ();
11687:     if ($mapname) {
11688:         if (($cachedmapkey eq $courseid) &&
11689:             (abs($cachedmaptime-time)<5)) {
11690:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11691:                 return @{$cachedmaps{$mapname}};
11692:             }
11693:         }
11694:         my $navmap = Apache::lonnavmaps::navmap->new();
11695:         if (ref($navmap)) {
11696:             @recurseup = $navmap->recurseup_maps($mapname);
11697:             undef($navmap);
11698:             $cachedmaps{$mapname} = \@recurseup;
11699:             $cachedmaptime=time;
11700:             $cachedmapkey=$courseid;
11701:         }
11702:     }
11703:     return @recurseup;
11704: }
11705: 
11706: }
11707: 
11708: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11709:     my ($courseid,@groups) = @_;
11710:     @groups = sort(@groups);
11711:     return @groups;
11712: }
11713: 
11714: sub packages_tab_default {
11715:     my ($uri,$varname,$toolsymb)=@_;
11716:     my (undef,$part,$name)=split(/\./,$varname);
11717: 
11718:     my (@extension,@specifics,$do_default);
11719:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11720: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11721: 	if ($pack_type eq 'default') {
11722: 	    $do_default=1;
11723: 	} elsif ($pack_type eq 'extension') {
11724: 	    push(@extension,[$package,$pack_type,$pack_part]);
11725: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11726: 	    # only look at packages defaults for packages that this id is
11727: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11728: 	}
11729:     }
11730:     # first look for a package that matches the requested part id
11731:     foreach my $package (@specifics) {
11732: 	my (undef,$pack_type,$pack_part)=@{$package};
11733: 	next if ($pack_part ne $part);
11734: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11735: 	    return $packagetab{"$pack_type&$name&default"};
11736: 	}
11737:     }
11738:     # look for any possible matching non extension_ package
11739:     foreach my $package (@specifics) {
11740: 	my (undef,$pack_type,$pack_part)=@{$package};
11741: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11742: 	    return $packagetab{"$pack_type&$name&default"};
11743: 	}
11744: 	if ($pack_type eq 'part') { $pack_part='0'; }
11745: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11746: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11747: 	}
11748:     }
11749:     # look for any posible extension_ match
11750:     foreach my $package (@extension) {
11751: 	my ($package,$pack_type)=@{$package};
11752: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11753: 	    return $packagetab{"$pack_type&$name&default"};
11754: 	}
11755: 	if (defined($packagetab{$package."&$name&default"})) {
11756: 	    return $packagetab{$package."&$name&default"};
11757: 	}
11758:     }
11759:     # look for a global default setting
11760:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11761: 	return $packagetab{"default&$name&default"};
11762:     }
11763:     return undef;
11764: }
11765: 
11766: sub add_prefix_and_part {
11767:     my ($prefix,$part)=@_;
11768:     my $keyroot;
11769:     if (defined($prefix) && $prefix !~ /^__/) {
11770: 	# prefix that has a part already
11771: 	$keyroot=$prefix;
11772:     } elsif (defined($prefix)) {
11773: 	# prefix that is missing a part
11774: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11775:     } else {
11776: 	# no prefix at all
11777: 	if (defined($part)) { $keyroot='_'.$part; }
11778:     }
11779:     return $keyroot;
11780: }
11781: 
11782: # ---------------------------------------------------------------- Get metadata
11783: 
11784: my %metaentry;
11785: my %importedpartids;
11786: my %importedrespids;
11787: sub metadata {
11788:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11789:     $uri=&declutter($uri);
11790:     # if it is a non metadata possible uri return quickly
11791:     if (($uri eq '') || 
11792: 	(($uri =~ m|^/*adm/|) && 
11793: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11794:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11795: 	return undef;
11796:     }
11797:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11798: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11799: 	return undef;
11800:     }
11801:     my $filename=$uri;
11802:     $uri=~s/\.meta$//;
11803: #
11804: # Is the metadata already cached?
11805: # Look at timestamp of caching
11806: # Everything is cached by the main uri, libraries are never directly cached
11807: #
11808:     if (!defined($liburi)) {
11809: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11810: 	if (defined($cached)) { return $result->{':'.$what}; }
11811:     }
11812: 
11813: #
11814: # If the uri is for an external tool the file from
11815: # which metadata should be retrieved depends on whether
11816: # the tool had been configured to be gradable (set in the Course
11817: # Editor or Resource Editor).
11818: #
11819: # If a valid symb has been included as the third arg in the call
11820: # to &metadata() that can be used to retrieve the value of
11821: # parameter_0_gradable set for the resource, and included in the
11822: # uploaded map containing the tool. The value is retrieved via
11823: # &EXT(), if a valid symb is available.  Otherwise the value of
11824: # gradable in the exttool_$marker.db file for the tool instance
11825: # is retrieved via &get().
11826: #
11827: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11828: # hiddenresource and encrypturl (during course initialization)
11829: # the map-level parameter for resource.0.gradable included in the 
11830: # uploaded map containing the tool will not yet have been stored
11831: # in the user_course_parms.db file for the user's session, so in 
11832: # this case fall back to retrieving gradable status from the
11833: # exttool_$marker.db file.
11834: #
11835: # In order to avoid an infinite loop, &metadata() will return
11836: # before a call to &EXT(), if the uri is for an external tool
11837: # and the $what for which metadata is being requested is
11838: # parameter_0_gradable or 0_gradable.
11839: #
11840: 
11841:     if ($uri =~ /ext\.tool$/) {
11842:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11843:             return;
11844:         } else {
11845:             my ($checked,$use_passback);
11846:             if ($toolsymb ne '') {
11847:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11848:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11849:                     $checked = 1;
11850:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11851:                         $use_passback = 1;
11852:                     }
11853:                 }
11854:             }
11855:             unless ($checked) {
11856:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11857:                 $marker=~s/\D//g;
11858:                 if ($marker) {
11859:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11860:                     $use_passback = $toolsettings{'gradable'};
11861:                 }
11862:             }
11863:             if ($use_passback) {
11864:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11865:             } else {
11866:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11867:             }
11868:         }
11869:     }
11870: 
11871:     {
11872: # Imported parts would go here
11873:         my @origfiletagids=();
11874:         my $importedparts=0;
11875: 
11876: # Imported responseids would go here
11877:         my $importedresponses=0;
11878: #
11879: # Is this a recursive call for a library?
11880: #
11881: #	if (! exists($metacache{$uri})) {
11882: #	    $metacache{$uri}={};
11883: #	}
11884: 	my $cachetime = 60*60;
11885:         if ($liburi) {
11886: 	    $liburi=&declutter($liburi);
11887:             $filename=$liburi;
11888:         } else {
11889: 	    &devalidate_cache_new('meta',$uri);
11890: 	    undef(%metaentry);
11891: 	}
11892:         my %metathesekeys=();
11893:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11894: 	my $metastring;
11895: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11896: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11897: 	    $metastring = 
11898: 		&Apache::lonnet::ssi_body($which,
11899: 					  ('grade_target' => 'meta'));
11900: 	    $cachetime = 1; # only want this cached in the child not long term
11901: 	} elsif (($uri !~ m -^(editupload)/-) && 
11902:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11903: 	    my $file=&filelocation('',&clutter($filename));
11904: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11905: 	    $metastring=&getfile($file);
11906: 	}
11907:         my $parser=HTML::LCParser->new(\$metastring);
11908:         my $token;
11909:         undef %metathesekeys;
11910:         while ($token=$parser->get_token) {
11911: 	    if ($token->[0] eq 'S') {
11912: 		if (defined($token->[2]->{'package'})) {
11913: #
11914: # This is a package - get package info
11915: #
11916: 		    my $package=$token->[2]->{'package'};
11917: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11918: 		    if (defined($token->[2]->{'id'})) { 
11919: 			$keyroot.='_'.$token->[2]->{'id'}; 
11920: 		    }
11921: 		    if ($metaentry{':packages'}) {
11922: 			$metaentry{':packages'}.=','.$package.$keyroot;
11923: 		    } else {
11924: 			$metaentry{':packages'}=$package.$keyroot;
11925: 		    }
11926: 		    foreach my $pack_entry (keys(%packagetab)) {
11927: 			my $part=$keyroot;
11928: 			$part=~s/^\_//;
11929: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11930: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11931: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11932: 			    # ignore package.tab specified default values
11933:                             # here &package_tab_default() will fetch those
11934: 			    if ($subp eq 'default') { next; }
11935: 			    my $value=$packagetab{$pack_entry};
11936: 			    my $unikey;
11937: 			    if ($pack =~ /_0$/) {
11938: 				$unikey='parameter_0_'.$name;
11939: 				$part=0;
11940: 			    } else {
11941: 				$unikey='parameter'.$keyroot.'_'.$name;
11942: 			    }
11943: 			    if ($subp eq 'display') {
11944: 				$value.=' [Part: '.$part.']';
11945: 			    }
11946: 			    $metaentry{':'.$unikey.'.part'}=$part;
11947: 			    $metathesekeys{$unikey}=1;
11948: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11949: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11950: 			    }
11951: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11952: 				$metaentry{':'.$unikey}=
11953: 				    $metaentry{':'.$unikey.'.default'};
11954: 			    }
11955: 			}
11956: 		    }
11957: 		} else {
11958: #
11959: # This is not a package - some other kind of start tag
11960: #
11961: 		    my $entry=$token->[1];
11962: 		    my $unikey='';
11963: 
11964: 		    if ($entry eq 'import') {
11965: #
11966: # Importing a library here
11967: #
11968:                         my $location=$parser->get_text('/import');
11969:                         my $dir=$filename;
11970:                         $dir=~s|[^/]*$||;
11971:                         $location=&filelocation($dir,$location);
11972: 
11973:                         my $importid=$token->[2]->{'id'};
11974:                         my $importmode=$token->[2]->{'importmode'};
11975: #
11976: # Check metadata for imported file to
11977: # see if it contained response items
11978: #
11979:                         my ($origfile,@libfilekeys);
11980:                         my %currmetaentry = %metaentry;
11981:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
11982:                                                            $depthcount+1));
11983:                         if (grep(/^responseorder$/,@libfilekeys)) {
11984:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
11985:                                                              undef,$depthcount+1);
11986:                             if ($libresponseorder ne '') {
11987:                                 if ($#origfiletagids<0) {
11988:                                     undef(%importedrespids);
11989:                                     undef(%importedpartids);
11990:                                 }
11991:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
11992:                                 if (@respids) {
11993:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
11994:                                 }
11995:                                 if ($importedrespids{$importid} ne '') {
11996:                                     $importedresponses = 1;
11997: # We need to get the original file and the imported file to get the response order correct
11998: # Load and inspect original file
11999:                                     if ($#origfiletagids<0) {
12000:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12001:                                         $origfile=&getfile($origfilelocation);
12002:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12003:                                     }
12004:                                 }
12005:                             }
12006:                         }
12007: # Do not overwrite contents of %metaentry hash for resource itself with 
12008: # hash populated for imported library file
12009:                         %metaentry = %currmetaentry;
12010:                         undef(%currmetaentry);
12011:                         if ($importmode eq 'part') {
12012: # Import as part(s)
12013:                            $importedparts=1;
12014: # We need to get the original file and the imported file to get the part order correct
12015: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12016: # Load and inspect original file if we didn't do that already
12017:                            if ($#origfiletagids<0) {
12018:                                undef(%importedrespids);
12019:                                undef(%importedpartids);
12020:                                if ($origfile eq '') {
12021:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12022:                                    $origfile=&getfile($origfilelocation);
12023:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12024:                                }
12025:                            }
12026:                            my @impfilepartids;
12027: # If <partorder> tag is included in metadata for the imported file
12028: # get the parts in the imported file from that.
12029:                            if (grep(/^partorder$/,@libfilekeys)) {
12030:                                %currmetaentry = %metaentry;
12031:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12032:                                                             $depthcount+1);
12033:                                %metaentry = %currmetaentry;
12034:                                undef(%currmetaentry);
12035:                                if ($libpartorder ne '') {
12036:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12037:                                }
12038:                            } else {
12039: # If no <partorder> tag available, load and inspect imported file
12040:                                my $impfile=&getfile($location);
12041:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12042:                            }
12043:                            if ($#impfilepartids>=0) {
12044: # This problem had parts
12045:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12046:                            } else {
12047: # Importing by turning a single problem into a problem part
12048: # It gets the import-tags ID as part-ID
12049:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12050:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12051:                            }
12052:                         } else {
12053: # Import as problem or as normal import
12054:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12055:                             unless ($importmode eq 'problem') {
12056: # Normal import
12057:                                 if (defined($token->[2]->{'id'})) {
12058:                                     $unikey.='_'.$token->[2]->{'id'};
12059:                                 }
12060:                             }
12061: # Check metadata for imported file to
12062: # see if it contained parts
12063:                             if (grep(/^partorder$/,@libfilekeys)) {
12064:                                 %currmetaentry = %metaentry;
12065:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12066:                                                              $depthcount+1);
12067:                                 %metaentry = %currmetaentry;
12068:                                 undef(%currmetaentry);
12069:                                 if ($libpartorder ne '') {
12070:                                     $importedparts = 1;
12071:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12072:                                 }
12073:                             }
12074:                         }
12075: 			if ($depthcount<20) {
12076: 			    my $metadata = 
12077: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12078: 					  $depthcount+1);
12079: 			    foreach my $meta (split(',',$metadata)) {
12080: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12081: 				$metathesekeys{$meta}=1;
12082: 			    }
12083:                         }
12084: 		    } else {
12085: #
12086: # Not importing, some other kind of non-package, non-library start tag
12087: # 
12088:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12089:                         if (defined($token->[2]->{'id'})) {
12090:                             $unikey.='_'.$token->[2]->{'id'};
12091:                         }
12092: 			if (defined($token->[2]->{'name'})) { 
12093: 			    $unikey.='_'.$token->[2]->{'name'}; 
12094: 			}
12095: 			$metathesekeys{$unikey}=1;
12096: 			foreach my $param (@{$token->[3]}) {
12097: 			    $metaentry{':'.$unikey.'.'.$param} =
12098: 				$token->[2]->{$param};
12099: 			}
12100: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12101: 			my $default=$metaentry{':'.$unikey.'.default'};
12102: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12103: 		 # only ws inside the tag, and not in default, so use default
12104: 		 # as value
12105: 			    $metaentry{':'.$unikey}=$default;
12106: 			} elsif ( $internaltext =~ /\S/ ) {
12107: 		  # something interesting inside the tag
12108: 			    $metaentry{':'.$unikey}=$internaltext;
12109: 			} else {
12110: 		  # no interesting values, don't set a default
12111: 			}
12112: # end of not-a-package not-a-library import
12113: 		    }
12114: # end of not-a-package start tag
12115: 		}
12116: # the next is the end of "start tag"
12117: 	    }
12118: 	}
12119: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12120: 	$extension = lc($extension);
12121: 	if ($extension eq 'htm') { $extension='html'; }
12122: 
12123: 	foreach my $key (keys(%packagetab)) {
12124: 	    #no specific packages #how's our extension
12125: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12126: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12127: 					 \%metathesekeys);
12128: 	}
12129: 
12130: 	if (!exists($metaentry{':packages'})
12131: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12132: 	    foreach my $key (keys(%packagetab)) {
12133: 		#no specific packages well let's get default then
12134: 		if ($key!~/^default&/) { next; }
12135: 		&metadata_create_package_def($uri,$key,'default',
12136: 					     \%metathesekeys);
12137: 	    }
12138: 	}
12139: # are there custom rights to evaluate
12140: 	if ($metaentry{':copyright'} eq 'custom') {
12141: 
12142:     #
12143:     # Importing a rights file here
12144:     #
12145: 	    unless ($depthcount) {
12146: 		my $location=$metaentry{':customdistributionfile'};
12147: 		my $dir=$filename;
12148: 		$dir=~s|[^/]*$||;
12149: 		$location=&filelocation($dir,$location);
12150: 		my $rights_metadata =
12151: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12152: 			      $depthcount+1);
12153: 		foreach my $rights (split(',',$rights_metadata)) {
12154: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12155: 		    $metathesekeys{$rights}=1;
12156: 		}
12157: 	    }
12158: 	}
12159: 	# uniqifiy package listing
12160: 	my %seen;
12161: 	my @uniq_packages =
12162: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12163: 	$metaentry{':packages'} = join(',',@uniq_packages);
12164: 
12165:         if (($importedresponses) || ($importedparts)) {
12166:             if ($importedparts) {
12167: # We had imported parts and need to rebuild partorder
12168:                 $metaentry{':partorder'}='';
12169:                 $metathesekeys{'partorder'}=1;
12170:             }
12171:             if ($importedresponses) {
12172: # We had imported responses and need to rebuil responseorder
12173:                 $metaentry{':responseorder'}='';
12174:                 $metathesekeys{'responseorder'}=1;
12175:             }
12176:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12177:                 my $origid = $origfiletagids[$index+1];
12178:                 if ($origfiletagids[$index] eq 'part') {
12179: # Original part, part of the problem
12180:                     if ($importedparts) {
12181:                         $metaentry{':partorder'}.=','.$origid;
12182:                     }
12183:                 } elsif ($origfiletagids[$index] eq 'import') {
12184:                     if ($importedparts) {
12185: # We have imported parts at this position
12186:                         if ($importedpartids{$origid} ne '') {
12187:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12188:                         }
12189:                     }
12190:                     if ($importedresponses) {
12191: # We have imported responses at this position
12192:                         if ($importedrespids{$origid} ne '') {
12193:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12194:                         }
12195:                     }
12196:                 } else {
12197: # Original response item, part of the problem
12198:                     if ($importedresponses) {
12199:                         $metaentry{':responseorder'}.=','.$origid;
12200:                     }
12201:                 }
12202:             }
12203:             if ($importedparts) {
12204:                 $metaentry{':partorder'}=~s/^\,//;
12205:             }
12206:             if ($importedresponses) {
12207:                 $metaentry{':responseorder'}=~s/^\,//;
12208:             }
12209:         }
12210: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12211: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12212: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12213:         unless ($liburi) {
12214: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12215:         }
12216: # this is the end of "was not already recently cached
12217:     }
12218:     return $metaentry{':'.$what};
12219: }
12220: 
12221: sub metadata_create_package_def {
12222:     my ($uri,$key,$package,$metathesekeys)=@_;
12223:     my ($pack,$name,$subp)=split(/\&/,$key);
12224:     if ($subp eq 'default') { next; }
12225:     
12226:     if (defined($metaentry{':packages'})) {
12227: 	$metaentry{':packages'}.=','.$package;
12228:     } else {
12229: 	$metaentry{':packages'}=$package;
12230:     }
12231:     my $value=$packagetab{$key};
12232:     my $unikey;
12233:     $unikey='parameter_0_'.$name;
12234:     $metaentry{':'.$unikey.'.part'}=0;
12235:     $$metathesekeys{$unikey}=1;
12236:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12237: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12238:     }
12239:     if (defined($metaentry{':'.$unikey.'.default'})) {
12240: 	$metaentry{':'.$unikey}=
12241: 	    $metaentry{':'.$unikey.'.default'};
12242:     }
12243: }
12244: 
12245: sub metadata_generate_part0 {
12246:     my ($metadata,$metacache,$uri) = @_;
12247:     my %allnames;
12248:     foreach my $metakey (keys(%$metadata)) {
12249: 	if ($metakey=~/^parameter\_(.*)/) {
12250: 	  my $part=$$metacache{':'.$metakey.'.part'};
12251: 	  my $name=$$metacache{':'.$metakey.'.name'};
12252: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12253: 	    $allnames{$name}=$part;
12254: 	  }
12255: 	}
12256:     }
12257:     foreach my $name (keys(%allnames)) {
12258:       $$metadata{"parameter_0_$name"}=1;
12259:       my $key=":parameter_0_$name";
12260:       $$metacache{"$key.part"}='0';
12261:       $$metacache{"$key.name"}=$name;
12262:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12263: 					   $allnames{$name}.'_'.$name.
12264: 					   '.type'};
12265:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12266: 			     '.display'};
12267:       my $expr='[Part: '.$allnames{$name}.']';
12268:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12269:       $$metacache{"$key.display"}=$olddis;
12270:     }
12271: }
12272: 
12273: # ------------------------------------------------------ Devalidate title cache
12274: 
12275: sub devalidate_title_cache {
12276:     my ($url)=@_;
12277:     if (!$env{'request.course.id'}) { return; }
12278:     my $symb=&symbread($url);
12279:     if (!$symb) { return; }
12280:     my $key=$env{'request.course.id'}."\0".$symb;
12281:     &devalidate_cache_new('title',$key);
12282: }
12283: 
12284: # ------------------------------------------------- Get the title of a course
12285: 
12286: sub current_course_title {
12287:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12288: }
12289: # ------------------------------------------------- Get the title of a resource
12290: 
12291: sub gettitle {
12292:     my $urlsymb=shift;
12293:     my $symb=&symbread($urlsymb);
12294:     if ($symb) {
12295: 	my $key=$env{'request.course.id'}."\0".$symb;
12296: 	my ($result,$cached)=&is_cached_new('title',$key);
12297: 	if (defined($cached)) { 
12298: 	    return $result;
12299: 	}
12300: 	my ($map,$resid,$url)=&decode_symb($symb);
12301: 	my $title='';
12302: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12303: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12304: 	} else {
12305: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12306: 		    &GDBM_READER(),0640)) {
12307: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12308: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12309: 		untie(%bighash);
12310: 	    }
12311: 	}
12312: 	$title=~s/\&colon\;/\:/gs;
12313: 	if ($title) {
12314: # Remember both $symb and $title for dynamic metadata
12315:             $accesshash{$symb.'___crstitle'}=$title;
12316:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12317: # Cache this title and then return it
12318: 	    return &do_cache_new('title',$key,$title,600);
12319: 	}
12320: 	$urlsymb=$url;
12321:     }
12322:     my $title=&metadata($urlsymb,'title');
12323:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12324:     return $title;
12325: }
12326: 
12327: sub get_slot {
12328:     my ($which,$cnum,$cdom)=@_;
12329:     if (!$cnum || !$cdom) {
12330: 	(undef,my $courseid)=&whichuser();
12331: 	$cdom=$env{'course.'.$courseid.'.domain'};
12332: 	$cnum=$env{'course.'.$courseid.'.num'};
12333:     }
12334:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12335:     my %slotinfo;
12336:     if (exists($remembered{$key})) {
12337: 	$slotinfo{$which} = $remembered{$key};
12338:     } else {
12339: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12340: 	&Apache::lonhomework::showhash(%slotinfo);
12341: 	my ($tmp)=keys(%slotinfo);
12342: 	if ($tmp=~/^error:/) { return (); }
12343: 	$remembered{$key} = $slotinfo{$which};
12344:     }
12345:     if (ref($slotinfo{$which}) eq 'HASH') {
12346: 	return %{$slotinfo{$which}};
12347:     }
12348:     return $slotinfo{$which};
12349: }
12350: 
12351: sub get_reservable_slots {
12352:     my ($cnum,$cdom,$uname,$udom) = @_;
12353:     my $now = time;
12354:     my $reservable_info;
12355:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12356:     if (exists($remembered{$key})) {
12357:         $reservable_info = $remembered{$key};
12358:     } else {
12359:         my %resv;
12360:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12361:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12362:         $reservable_info = \%resv;
12363:         $remembered{$key} = $reservable_info;
12364:     }
12365:     return $reservable_info;
12366: }
12367: 
12368: sub get_course_slots {
12369:     my ($cnum,$cdom) = @_;
12370:     my $hashid=$cnum.':'.$cdom;
12371:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12372:     if (defined($cached)) {
12373:         if (ref($result) eq 'HASH') {
12374:             return %{$result};
12375:         }
12376:     } else {
12377:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12378:         my ($tmp) = keys(%slots);
12379:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12380:             &do_cache_new('allslots',$hashid,\%slots,600);
12381:             return %slots;
12382:         }
12383:     }
12384:     return;
12385: }
12386: 
12387: sub devalidate_slots_cache {
12388:     my ($cnum,$cdom)=@_;
12389:     my $hashid=$cnum.':'.$cdom;
12390:     &devalidate_cache_new('allslots',$hashid);
12391: }
12392: 
12393: sub get_coursechange {
12394:     my ($cdom,$cnum) = @_;
12395:     if ($cdom eq '' || $cnum eq '') {
12396:         return unless ($env{'request.course.id'});
12397:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12398:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12399:     }
12400:     my $hashid=$cdom.'_'.$cnum;
12401:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12402:     if ((defined($cached)) && ($change ne '')) {
12403:         return $change;
12404:     } else {
12405:         my %crshash;
12406:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12407:         if ($crshash{'internal.contentchange'} eq '') {
12408:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12409:             if ($change eq '') {
12410:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12411:                 $change = $crshash{'internal.created'};
12412:             }
12413:         } else {
12414:             $change = $crshash{'internal.contentchange'};
12415:         }
12416:         my $cachetime = 600;
12417:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12418:     }
12419:     return $change;
12420: }
12421: 
12422: sub devalidate_coursechange_cache {
12423:     my ($cnum,$cdom)=@_;
12424:     my $hashid=$cnum.':'.$cdom;
12425:     &devalidate_cache_new('crschange',$hashid);
12426: }
12427: 
12428: # ------------------------------------------------- Update symbolic store links
12429: 
12430: sub symblist {
12431:     my ($mapname,%newhash)=@_;
12432:     $mapname=&deversion(&declutter($mapname));
12433:     my %hash;
12434:     if (($env{'request.course.fn'}) && (%newhash)) {
12435:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12436:                       &GDBM_WRCREAT(),0640)) {
12437: 	    foreach my $url (keys(%newhash)) {
12438: 		next if ($url eq 'last_known'
12439: 			 && $env{'form.no_update_last_known'});
12440: 		$hash{declutter($url)}=&encode_symb($mapname,
12441: 						    $newhash{$url}->[1],
12442: 						    $newhash{$url}->[0]);
12443:             }
12444:             if (untie(%hash)) {
12445: 		return 'ok';
12446:             }
12447:         }
12448:     }
12449:     return 'error';
12450: }
12451: 
12452: # --------------------------------------------------------------- Verify a symb
12453: 
12454: sub symbverify {
12455:     my ($symb,$thisurl,$encstate)=@_;
12456:     my $thisfn=$thisurl;
12457:     $thisfn=&declutter($thisfn);
12458: # direct jump to resource in page or to a sequence - will construct own symbs
12459:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12460: # check URL part
12461:     my ($map,$resid,$url)=&decode_symb($symb);
12462: 
12463:     unless ($url eq $thisfn) { return 0; }
12464: 
12465:     $symb=&symbclean($symb);
12466:     $thisurl=&deversion($thisurl);
12467:     $thisfn=&deversion($thisfn);
12468: 
12469:     my %bighash;
12470:     my $okay=0;
12471: 
12472:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12473:                             &GDBM_READER(),0640)) {
12474:         my $noclutter;
12475:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12476:             $thisurl =~ s/\?.+$//;
12477:             if ($map =~ m{^uploaded/.+\.page$}) {
12478:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12479:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12480:                 $noclutter = 1;
12481:             }
12482:         }
12483:         my $ids;
12484:         if ($noclutter) {
12485:             $ids=$bighash{'ids_'.$thisurl};
12486:         } else {
12487:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12488:         }
12489:         unless ($ids) {
12490:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12491:             $ids=$bighash{$idkey};
12492:         }
12493:         if ($ids) {
12494: # ------------------------------------------------------------------- Has ID(s)
12495:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12496:                 $symb =~ s/\?.+$//;
12497:             }
12498: 	    foreach my $id (split(/\,/,$ids)) {
12499: 	       my ($mapid,$resid)=split(/\./,$id);
12500:                if (
12501:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12502:    eq $symb) {
12503:                    if (ref($encstate)) {
12504:                        $$encstate = $bighash{'encrypted_'.$id};
12505:                    }
12506: 		   if (($env{'request.role.adv'}) ||
12507: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12508:                        ($thisurl eq '/adm/navmaps')) {
12509: 		       $okay=1;
12510:                        last;
12511: 		   }
12512: 	       }
12513: 	   }
12514:         }
12515: 	untie(%bighash);
12516:     }
12517:     return $okay;
12518: }
12519: 
12520: # --------------------------------------------------------------- Clean-up symb
12521: 
12522: sub symbclean {
12523:     my $symb=shift;
12524:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12525: # remove version from map
12526:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12527: 
12528: # remove version from URL
12529:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12530: 
12531: # remove wrapper
12532: 
12533:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12534:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12535:     return $symb;
12536: }
12537: 
12538: # ---------------------------------------------- Split symb to find map and url
12539: 
12540: sub encode_symb {
12541:     my ($map,$resid,$url)=@_;
12542:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12543: }
12544: 
12545: sub decode_symb {
12546:     my $symb=shift;
12547:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12548:     my ($map,$resid,$url)=split(/___/,$symb);
12549:     return (&fixversion($map),$resid,&fixversion($url));
12550: }
12551: 
12552: sub fixversion {
12553:     my $fn=shift;
12554:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12555:     my %bighash;
12556:     my $uri=&clutter($fn);
12557:     my $key=$env{'request.course.id'}.'_'.$uri;
12558: # is this cached?
12559:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12560:     if (defined($cached)) { return $result; }
12561: # unfortunately not cached, or expired
12562:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12563: 	    &GDBM_READER(),0640)) {
12564:  	if ($bighash{'version_'.$uri}) {
12565:  	    my $version=$bighash{'version_'.$uri};
12566:  	    unless (($version eq 'mostrecent') || 
12567: 		    ($version==&getversion($uri))) {
12568:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12569:  	    }
12570:  	}
12571:  	untie %bighash;
12572:     }
12573:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12574: }
12575: 
12576: sub deversion {
12577:     my $url=shift;
12578:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12579:     return $url;
12580: }
12581: 
12582: # ------------------------------------------------------ Return symb list entry
12583: 
12584: sub symbread {
12585:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12586:     my $cache_str='request.symbread.cached.'.$thisfn;
12587:     if (defined($env{$cache_str})) {
12588:         if ($ignorecachednull) {
12589:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12590:         } else {
12591:             return $env{$cache_str};
12592:         }
12593:     }
12594: # no filename provided? try from environment
12595:     unless ($thisfn) {
12596:         if ($env{'request.symb'}) {
12597: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12598: 	}
12599: 	$thisfn=$env{'request.filename'};
12600:     }
12601:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12602: # is that filename actually a symb? Verify, clean, and return
12603:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12604: 	if (&symbverify($thisfn,$1)) {
12605: 	    return $env{$cache_str}=&symbclean($thisfn);
12606: 	}
12607:     }
12608:     $thisfn=declutter($thisfn);
12609:     my %hash;
12610:     my %bighash;
12611:     my $syval='';
12612:     if (($env{'request.course.fn'}) && ($thisfn)) {
12613:         my $targetfn = $thisfn;
12614:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12615:             $targetfn = 'adm/wrapper/'.$thisfn;
12616:         }
12617: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12618: 	    $targetfn=$1;
12619: 	}
12620:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12621:                       &GDBM_READER(),0640)) {
12622: 	    $syval=$hash{$targetfn};
12623:             untie(%hash);
12624:         }
12625: # ---------------------------------------------------------- There was an entry
12626:         if ($syval) {
12627: 	    #unless ($syval=~/\_\d+$/) {
12628: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12629: 		    #&appenv({'request.ambiguous' => $thisfn});
12630: 		    #return $env{$cache_str}='';
12631: 		#}    
12632: 		#$syval.=$1;
12633: 	    #}
12634:         } else {
12635: # ------------------------------------------------------- Was not in symb table
12636:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12637:                             &GDBM_READER(),0640)) {
12638: # ---------------------------------------------- Get ID(s) for current resource
12639:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12640:               unless ($ids) { 
12641:                  $ids=$bighash{'ids_/'.$thisfn};
12642:               }
12643:               unless ($ids) {
12644: # alias?
12645: 		  $ids=$bighash{'mapalias_'.$thisfn};
12646:               }
12647:               if ($ids) {
12648: # ------------------------------------------------------------------- Has ID(s)
12649:                  my @possibilities=split(/\,/,$ids);
12650:                  if ($#possibilities==0) {
12651: # ----------------------------------------------- There is only one possibility
12652: 		     my ($mapid,$resid)=split(/\./,$ids);
12653: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12654: 						    $resid,$thisfn);
12655:                      if (ref($possibles) eq 'HASH') {
12656:                          $possibles->{$syval} = 1;    
12657:                      }
12658:                      if ($checkforblock) {
12659:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12660:                          if (@blockers) {
12661:                              $syval = '';
12662:                              return;
12663:                          }
12664:                      }
12665:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12666: # ------------------------------------------ There is more than one possibility
12667:                      my $realpossible=0;
12668:                      foreach my $id (@possibilities) {
12669: 			 my $file=$bighash{'src_'.$id};
12670:                          my $canaccess;
12671:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12672:                              $canaccess = 1;
12673:                          } else { 
12674:                              $canaccess = &allowed('bre',$file);
12675:                          }
12676:                          if ($canaccess) {
12677:          		     my ($mapid,$resid)=split(/\./,$id);
12678:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12679:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12680: 						             $resid,$thisfn);
12681:                                  if (ref($possibles) eq 'HASH') {
12682:                                      $possibles->{$syval} = 1;
12683:                                  }
12684:                                  if ($checkforblock) {
12685:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12686:                                      unless (@blockers > 0) {
12687:                                          $syval = $poss_syval;
12688:                                          $realpossible++;
12689:                                      }
12690:                                  } else {
12691:                                      $syval = $poss_syval;
12692:                                      $realpossible++;
12693:                                  }
12694:                              }
12695: 			 }
12696:                      }
12697: 		     if ($realpossible!=1) { $syval=''; }
12698:                  } else {
12699:                      $syval='';
12700:                  }
12701: 	      }
12702:               untie(%bighash);
12703:            }
12704:         }
12705:         if ($syval) {
12706: 	    return $env{$cache_str}=$syval;
12707:         }
12708:     }
12709:     &appenv({'request.ambiguous' => $thisfn});
12710:     return $env{$cache_str}='';
12711: }
12712: 
12713: # ---------------------------------------------------------- Return random seed
12714: 
12715: sub numval {
12716:     my $txt=shift;
12717:     $txt=~tr/A-J/0-9/;
12718:     $txt=~tr/a-j/0-9/;
12719:     $txt=~tr/K-T/0-9/;
12720:     $txt=~tr/k-t/0-9/;
12721:     $txt=~tr/U-Z/0-5/;
12722:     $txt=~tr/u-z/0-5/;
12723:     $txt=~s/\D//g;
12724:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12725:     return int($txt);
12726: }
12727: 
12728: sub numval2 {
12729:     my $txt=shift;
12730:     $txt=~tr/A-J/0-9/;
12731:     $txt=~tr/a-j/0-9/;
12732:     $txt=~tr/K-T/0-9/;
12733:     $txt=~tr/k-t/0-9/;
12734:     $txt=~tr/U-Z/0-5/;
12735:     $txt=~tr/u-z/0-5/;
12736:     $txt=~s/\D//g;
12737:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12738:     my $total;
12739:     foreach my $val (@txts) { $total+=$val; }
12740:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12741:     return int($total);
12742: }
12743: 
12744: sub numval3 {
12745:     use integer;
12746:     my $txt=shift;
12747:     $txt=~tr/A-J/0-9/;
12748:     $txt=~tr/a-j/0-9/;
12749:     $txt=~tr/K-T/0-9/;
12750:     $txt=~tr/k-t/0-9/;
12751:     $txt=~tr/U-Z/0-5/;
12752:     $txt=~tr/u-z/0-5/;
12753:     $txt=~s/\D//g;
12754:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12755:     my $total;
12756:     foreach my $val (@txts) { $total+=$val; }
12757:     if ($_64bit) { $total=(($total<<32)>>32); }
12758:     return $total;
12759: }
12760: 
12761: sub digest {
12762:     my ($data)=@_;
12763:     my $digest=&Digest::MD5::md5($data);
12764:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12765:     my ($e,$f);
12766:     {
12767:         use integer;
12768:         $e=($a+$b);
12769:         $f=($c+$d);
12770:         if ($_64bit) {
12771:             $e=(($e<<32)>>32);
12772:             $f=(($f<<32)>>32);
12773:         }
12774:     }
12775:     if (wantarray) {
12776: 	return ($e,$f);
12777:     } else {
12778: 	my $g;
12779: 	{
12780: 	    use integer;
12781: 	    $g=($e+$f);
12782: 	    if ($_64bit) {
12783: 		$g=(($g<<32)>>32);
12784: 	    }
12785: 	}
12786: 	return $g;
12787:     }
12788: }
12789: 
12790: sub latest_rnd_algorithm_id {
12791:     return '64bit5';
12792: }
12793: 
12794: sub get_rand_alg {
12795:     my ($courseid)=@_;
12796:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12797:     if ($courseid) {
12798: 	return $env{"course.$courseid.rndseed"};
12799:     }
12800:     return &latest_rnd_algorithm_id();
12801: }
12802: 
12803: sub validCODE {
12804:     my ($CODE)=@_;
12805:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12806:     return 0;
12807: }
12808: 
12809: sub getCODE {
12810:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12811:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12812: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12813: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12814: 	return $Apache::lonhomework::history{'resource.CODE'};
12815:     }
12816:     return undef;
12817: }
12818: #
12819: #  Determines the random seed for a specific context:
12820: #
12821: # parameters:
12822: #   symb      - in course context the symb for the seed.
12823: #   course_id - The course id of the form domain_coursenum.
12824: #   domain    - Domain for the user.
12825: #   course    - Course for the user.
12826: #   cenv      - environment of the course.
12827: #
12828: # NOTE:
12829: #   All parameters are picked out of the environment if missing
12830: #   or not defined.
12831: #   If a symb cannot be determined the current time is used instead.
12832: #
12833: #  For a given well defined symb, courside, domain, username,
12834: #  and course environment, the seed is reproducible.
12835: #
12836: sub rndseed {
12837:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12838:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12839:     if (!defined($symb)) {
12840: 	unless ($symb=$wsymb) { return time; }
12841:     }
12842:     if (!defined $courseid) { 
12843: 	$courseid=$wcourseid; 
12844:     }
12845:     if (!defined $domain) { $domain=$wdomain; }
12846:     if (!defined $username) { $username=$wusername }
12847: 
12848:     my $which;
12849:     if (defined($cenv->{'rndseed'})) {
12850: 	$which = $cenv->{'rndseed'};
12851:     } else {
12852: 	$which =&get_rand_alg($courseid);
12853:     }
12854:     if (defined(&getCODE())) {
12855: 
12856: 	if ($which eq '64bit5') {
12857: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12858: 	} elsif ($which eq '64bit4') {
12859: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12860: 	} else {
12861: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12862: 	}
12863:     } elsif ($which eq '64bit5') {
12864: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12865:     } elsif ($which eq '64bit4') {
12866: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12867:     } elsif ($which eq '64bit3') {
12868: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12869:     } elsif ($which eq '64bit2') {
12870: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12871:     } elsif ($which eq '64bit') {
12872: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12873:     }
12874:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12875: }
12876: 
12877: sub rndseed_32bit {
12878:     my ($symb,$courseid,$domain,$username)=@_;
12879:     {
12880: 	use integer;
12881: 	my $symbchck=unpack("%32C*",$symb) << 27;
12882: 	my $symbseed=numval($symb) << 22;
12883: 	my $namechck=unpack("%32C*",$username) << 17;
12884: 	my $nameseed=numval($username) << 12;
12885: 	my $domainseed=unpack("%32C*",$domain) << 7;
12886: 	my $courseseed=unpack("%32C*",$courseid);
12887: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12888: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12889: 	#&logthis("rndseed :$num:$symb");
12890: 	if ($_64bit) { $num=(($num<<32)>>32); }
12891: 	return $num;
12892:     }
12893: }
12894: 
12895: sub rndseed_64bit {
12896:     my ($symb,$courseid,$domain,$username)=@_;
12897:     {
12898: 	use integer;
12899: 	my $symbchck=unpack("%32S*",$symb) << 21;
12900: 	my $symbseed=numval($symb) << 10;
12901: 	my $namechck=unpack("%32S*",$username);
12902: 	
12903: 	my $nameseed=numval($username) << 21;
12904: 	my $domainseed=unpack("%32S*",$domain) << 10;
12905: 	my $courseseed=unpack("%32S*",$courseid);
12906: 	
12907: 	my $num1=$symbchck+$symbseed+$namechck;
12908: 	my $num2=$nameseed+$domainseed+$courseseed;
12909: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12910: 	#&logthis("rndseed :$num:$symb");
12911: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12912: 	return "$num1,$num2";
12913:     }
12914: }
12915: 
12916: sub rndseed_64bit2 {
12917:     my ($symb,$courseid,$domain,$username)=@_;
12918:     {
12919: 	use integer;
12920: 	# strings need to be an even # of cahracters long, it it is odd the
12921:         # last characters gets thrown away
12922: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12923: 	my $symbseed=numval($symb) << 10;
12924: 	my $namechck=unpack("%32S*",$username.' ');
12925: 	
12926: 	my $nameseed=numval($username) << 21;
12927: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12928: 	my $courseseed=unpack("%32S*",$courseid.' ');
12929: 	
12930: 	my $num1=$symbchck+$symbseed+$namechck;
12931: 	my $num2=$nameseed+$domainseed+$courseseed;
12932: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12933: 	#&logthis("rndseed :$num:$symb");
12934: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12935: 	return "$num1,$num2";
12936:     }
12937: }
12938: 
12939: sub rndseed_64bit3 {
12940:     my ($symb,$courseid,$domain,$username)=@_;
12941:     {
12942: 	use integer;
12943: 	# strings need to be an even # of cahracters long, it it is odd the
12944:         # last characters gets thrown away
12945: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12946: 	my $symbseed=numval2($symb) << 10;
12947: 	my $namechck=unpack("%32S*",$username.' ');
12948: 	
12949: 	my $nameseed=numval2($username) << 21;
12950: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12951: 	my $courseseed=unpack("%32S*",$courseid.' ');
12952: 	
12953: 	my $num1=$symbchck+$symbseed+$namechck;
12954: 	my $num2=$nameseed+$domainseed+$courseseed;
12955: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12956: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12957: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12958: 	
12959: 	return "$num1:$num2";
12960:     }
12961: }
12962: 
12963: sub rndseed_64bit4 {
12964:     my ($symb,$courseid,$domain,$username)=@_;
12965:     {
12966: 	use integer;
12967: 	# strings need to be an even # of cahracters long, it it is odd the
12968:         # last characters gets thrown away
12969: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12970: 	my $symbseed=numval3($symb) << 10;
12971: 	my $namechck=unpack("%32S*",$username.' ');
12972: 	
12973: 	my $nameseed=numval3($username) << 21;
12974: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12975: 	my $courseseed=unpack("%32S*",$courseid.' ');
12976: 	
12977: 	my $num1=$symbchck+$symbseed+$namechck;
12978: 	my $num2=$nameseed+$domainseed+$courseseed;
12979: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12980: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12981: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12982: 	
12983: 	return "$num1:$num2";
12984:     }
12985: }
12986: 
12987: sub rndseed_64bit5 {
12988:     my ($symb,$courseid,$domain,$username)=@_;
12989:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12990:     return "$num1:$num2";
12991: }
12992: 
12993: sub rndseed_CODE_64bit {
12994:     my ($symb,$courseid,$domain,$username)=@_;
12995:     {
12996: 	use integer;
12997: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12998: 	my $symbseed=numval2($symb);
12999: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13000: 	my $CODEseed=numval(&getCODE());
13001: 	my $courseseed=unpack("%32S*",$courseid.' ');
13002: 	my $num1=$symbseed+$CODEchck;
13003: 	my $num2=$CODEseed+$courseseed+$symbchck;
13004: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13005: 	#&logthis("rndseed :$num1:$num2:$symb");
13006: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13007: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13008: 	return "$num1:$num2";
13009:     }
13010: }
13011: 
13012: sub rndseed_CODE_64bit4 {
13013:     my ($symb,$courseid,$domain,$username)=@_;
13014:     {
13015: 	use integer;
13016: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13017: 	my $symbseed=numval3($symb);
13018: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13019: 	my $CODEseed=numval3(&getCODE());
13020: 	my $courseseed=unpack("%32S*",$courseid.' ');
13021: 	my $num1=$symbseed+$CODEchck;
13022: 	my $num2=$CODEseed+$courseseed+$symbchck;
13023: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13024: 	#&logthis("rndseed :$num1:$num2:$symb");
13025: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13026: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13027: 	return "$num1:$num2";
13028:     }
13029: }
13030: 
13031: sub rndseed_CODE_64bit5 {
13032:     my ($symb,$courseid,$domain,$username)=@_;
13033:     my $code = &getCODE();
13034:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13035:     return "$num1:$num2";
13036: }
13037: 
13038: sub setup_random_from_rndseed {
13039:     my ($rndseed)=@_;
13040:     if ($rndseed =~/([,:])/) {
13041:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13042:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13043:             &Math::Random::random_set_seed_from_phrase($rndseed);
13044:         } else {
13045:             &Math::Random::random_set_seed($num1,$num2);
13046:         }
13047:     } else {
13048: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13049:     }
13050: }
13051: 
13052: sub latest_receipt_algorithm_id {
13053:     return 'receipt3';
13054: }
13055: 
13056: sub recunique {
13057:     my $fucourseid=shift;
13058:     my $unique;
13059:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13060: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13061: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13062:     } else {
13063: 	$unique=$perlvar{'lonReceipt'};
13064:     }
13065:     return unpack("%32C*",$unique);
13066: }
13067: 
13068: sub recprefix {
13069:     my $fucourseid=shift;
13070:     my $prefix;
13071:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13072: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13073: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13074:     } else {
13075: 	$prefix=$perlvar{'lonHostID'};
13076:     }
13077:     return unpack("%32C*",$prefix);
13078: }
13079: 
13080: sub ireceipt {
13081:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13082: 
13083:     my $return =&recprefix($fucourseid).'-';
13084: 
13085:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13086: 	$env{'request.state'} eq 'construct') {
13087: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13088: 	return $return;
13089:     }
13090: 
13091:     my $cuname=unpack("%32C*",$funame);
13092:     my $cudom=unpack("%32C*",$fudom);
13093:     my $cucourseid=unpack("%32C*",$fucourseid);
13094:     my $cusymb=unpack("%32C*",$fusymb);
13095:     my $cunique=&recunique($fucourseid);
13096:     my $cpart=unpack("%32S*",$part);
13097:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13098: 
13099: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13100: 			       
13101: 	$return.= ($cunique%$cuname+
13102: 		   $cunique%$cudom+
13103: 		   $cusymb%$cuname+
13104: 		   $cusymb%$cudom+
13105: 		   $cucourseid%$cuname+
13106: 		   $cucourseid%$cudom+
13107: 		   $cpart%$cuname+
13108: 		   $cpart%$cudom);
13109:     } else {
13110: 	$return.= ($cunique%$cuname+
13111: 		   $cunique%$cudom+
13112: 		   $cusymb%$cuname+
13113: 		   $cusymb%$cudom+
13114: 		   $cucourseid%$cuname+
13115: 		   $cucourseid%$cudom);
13116:     }
13117:     return $return;
13118: }
13119: 
13120: sub receipt {
13121:     my ($part)=@_;
13122:     my ($symb,$courseid,$domain,$name) = &whichuser();
13123:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13124: }
13125: 
13126: sub whichuser {
13127:     my ($passedsymb)=@_;
13128:     my ($symb,$courseid,$domain,$name,$publicuser);
13129:     if (defined($env{'form.grade_symb'})) {
13130: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13131: 	my $allowed=&allowed('vgr',$tmp_courseid);
13132: 	if (!$allowed &&
13133: 	    exists($env{'request.course.sec'}) &&
13134: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13135: 	    $allowed=&allowed('vgr',$tmp_courseid.
13136: 			      '/'.$env{'request.course.sec'});
13137: 	}
13138: 	if ($allowed) {
13139: 	    ($symb)=&get_env_multiple('form.grade_symb');
13140: 	    $courseid=$tmp_courseid;
13141: 	    ($domain)=&get_env_multiple('form.grade_domain');
13142: 	    ($name)=&get_env_multiple('form.grade_username');
13143: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13144: 	}
13145:     }
13146:     if (!$passedsymb) {
13147: 	$symb=&symbread();
13148:     } else {
13149: 	$symb=$passedsymb;
13150:     }
13151:     $courseid=$env{'request.course.id'};
13152:     $domain=$env{'user.domain'};
13153:     $name=$env{'user.name'};
13154:     if ($name eq 'public' && $domain eq 'public') {
13155: 	if (!defined($env{'form.username'})) {
13156: 	    $env{'form.username'}.=time.rand(10000000);
13157: 	}
13158: 	$name.=$env{'form.username'};
13159:     }
13160:     return ($symb,$courseid,$domain,$name,$publicuser);
13161: 
13162: }
13163: 
13164: # ------------------------------------------------------------ Serves up a file
13165: # returns either the contents of the file or 
13166: # -1 if the file doesn't exist
13167: #
13168: # if the target is a file that was uploaded via DOCS, 
13169: # a check will be made to see if a current copy exists on the local server,
13170: # if it does this will be served, otherwise a copy will be retrieved from
13171: # the home server for the course and stored in /home/httpd/html/userfiles on
13172: # the local server.   
13173: 
13174: sub getfile {
13175:     my ($file) = @_;
13176:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13177:     &repcopy($file);
13178:     return &readfile($file);
13179: }
13180: 
13181: sub repcopy_userfile {
13182:     my ($file)=@_;
13183:     my $londocroot = $perlvar{'lonDocRoot'};
13184:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13185:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13186:     my ($cdom,$cnum,$filename) = 
13187: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13188:     my $uri="/uploaded/$cdom/$cnum/$filename";
13189:     if (-e "$file") {
13190: # we already have a local copy, check it out
13191: 	my @fileinfo = stat($file);
13192: 	my $rtncode;
13193: 	my $info;
13194: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13195: 	if ($lwpresp ne 'ok') {
13196: # there is no such file anymore, even though we had a local copy
13197: 	    if ($rtncode eq '404') {
13198: 		unlink($file);
13199: 	    }
13200: 	    return -1;
13201: 	}
13202: 	if ($info < $fileinfo[9]) {
13203: # nice, the file we have is up-to-date, just say okay
13204: 	    return 'ok';
13205: 	} else {
13206: # the file is outdated, get rid of it
13207: 	    unlink($file);
13208: 	}
13209:     }
13210: # one way or the other, at this point, we don't have the file
13211: # construct the correct path for the file
13212:     my @parts = ($cdom,$cnum); 
13213:     if ($filename =~ m|^(.+)/[^/]+$|) {
13214: 	push @parts, split(/\//,$1);
13215:     }
13216:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13217:     foreach my $part (@parts) {
13218: 	$path .= '/'.$part;
13219: 	if (!-e $path) {
13220: 	    mkdir($path,0770);
13221: 	}
13222:     }
13223: # now the path exists for sure
13224: # get a user agent
13225:     my $transferfile=$file.'.in.transfer';
13226: # FIXME: this should flock
13227:     if (-e $transferfile) { return 'ok'; }
13228:     my $request;
13229:     $uri=~s/^\///;
13230:     my $homeserver = &homeserver($cnum,$cdom);
13231:     my $protocol = $protocol{$homeserver};
13232:     $protocol = 'http' if ($protocol ne 'https');
13233:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13234:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13235: # did it work?
13236:     if ($response->is_error()) {
13237: 	unlink($transferfile);
13238: 	&logthis("Userfile repcopy failed for $uri");
13239: 	return -1;
13240:     }
13241: # worked, rename the transfer file
13242:     rename($transferfile,$file);
13243:     return 'ok';
13244: }
13245: 
13246: sub tokenwrapper {
13247:     my $uri=shift;
13248:     $uri=~s|^https?\://([^/]+)||;
13249:     $uri=~s|^/||;
13250:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13251:     my $token=$1;
13252:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13253:     if ($udom && $uname && $file) {
13254: 	$file=~s|(\?\.*)*$||;
13255:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13256:         my $homeserver = &homeserver($uname,$udom);
13257:         my $protocol = $protocol{$homeserver};
13258:         $protocol = 'http' if ($protocol ne 'https');
13259:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13260:                (($uri=~/\?/)?'&':'?').'token='.$token.
13261:                                '&tokenissued='.$perlvar{'lonHostID'};
13262:     } else {
13263:         return '/adm/notfound.html';
13264:     }
13265: }
13266: 
13267: # call with reqtype HEAD: get last modification time
13268: # call with reqtype GET: get the file contents
13269: # Do not call this with reqtype GET for large files! It loads everything into memory
13270: #
13271: sub getuploaded {
13272:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13273:     $uri=~s/^\///;
13274:     my $homeserver = &homeserver($cnum,$cdom);
13275:     my $protocol = $protocol{$homeserver};
13276:     $protocol = 'http' if ($protocol ne 'https');
13277:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13278:     my $request=new HTTP::Request($reqtype,$uri);
13279:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13280:     $$rtncode = $response->code;
13281:     if (! $response->is_success()) {
13282: 	return 'failed';
13283:     }      
13284:     if ($reqtype eq 'HEAD') {
13285: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13286:     } elsif ($reqtype eq 'GET') {
13287: 	$$info = $response->content;
13288:     }
13289:     return 'ok';
13290: }
13291: 
13292: sub readfile {
13293:     my $file = shift;
13294:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13295:     my $fh;
13296:     open($fh,"<",$file);
13297:     my $a='';
13298:     while (my $line = <$fh>) { $a .= $line; }
13299:     return $a;
13300: }
13301: 
13302: sub filelocation {
13303:     my ($dir,$file) = @_;
13304:     my $location;
13305:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13306: 
13307:     if ($file =~ m-^/adm/-) {
13308: 	$file=~s-^/adm/wrapper/-/-;
13309: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13310:     }
13311: 
13312:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13313:         $location = $file;
13314:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13315:         my ($udom,$uname,$filename)=
13316:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13317:         my $home=&homeserver($uname,$udom);
13318:         my $is_me=0;
13319:         my @ids=&current_machine_ids();
13320:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13321:         if ($is_me) {
13322:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13323:         } else {
13324:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13325:   	      $udom.'/'.$uname.'/'.$filename;
13326:         }
13327:     } elsif ($file =~ m-^/adm/-) {
13328: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13329:     } else {
13330:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13331:         $file=~s:^/(res|priv)/:/:;
13332:         my $space=$1;
13333:         if ( !( $file =~ m:^/:) ) {
13334:             $location = $dir. '/'.$file;
13335:         } else {
13336:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13337:         }
13338:     }
13339:     $location=~s://+:/:g; # remove duplicate /
13340:     while ($location=~m{/\.\./}) {
13341: 	if ($location =~ m{/[^/]+/\.\./}) {
13342: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13343: 	} else {
13344: 	    $location=~ s{/\.\./}{/}g;
13345: 	}
13346:     } #remove dir/..
13347:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13348:     return $location;
13349: }
13350: 
13351: sub hreflocation {
13352:     my ($dir,$file)=@_;
13353:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13354: 	$file=filelocation($dir,$file);
13355:     } elsif ($file=~m-^/adm/-) {
13356: 	$file=~s-^/adm/wrapper/-/-;
13357: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13358:     }
13359:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13360: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13361:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13362: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13363: 	        {/uploaded/$1/$2/}x;
13364:     }
13365:     if ($file=~ m{^/userfiles/}) {
13366: 	$file =~ s{^/userfiles/}{/uploaded/};
13367:     }
13368:     return $file;
13369: }
13370: 
13371: 
13372: 
13373: 
13374: 
13375: sub current_machine_domains {
13376:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13377: }
13378: 
13379: sub machine_domains {
13380:     my ($hostname) = @_;
13381:     my @domains;
13382:     my %hostname = &all_hostnames();
13383:     while( my($id, $name) = each(%hostname)) {
13384: #	&logthis("-$id-$name-$hostname-");
13385: 	if ($hostname eq $name) {
13386: 	    push(@domains,&host_domain($id));
13387: 	}
13388:     }
13389:     return @domains;
13390: }
13391: 
13392: sub current_machine_ids {
13393:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13394: }
13395: 
13396: sub machine_ids {
13397:     my ($hostname) = @_;
13398:     $hostname ||= &hostname($perlvar{'lonHostID'});
13399:     my @ids;
13400:     my %name_to_host = &all_names();
13401:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13402: 	return @{ $name_to_host{$hostname} };
13403:     }
13404:     return;
13405: }
13406: 
13407: sub additional_machine_domains {
13408:     my @domains;
13409:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13410:     while( my $line = <$fh>) {
13411:         $line =~ s/\s//g;
13412:         push(@domains,$line);
13413:     }
13414:     return @domains;
13415: }
13416: 
13417: sub default_login_domain {
13418:     my $domain = $perlvar{'lonDefDomain'};
13419:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13420:     foreach my $posdom (&current_machine_domains(),
13421:                         &additional_machine_domains()) {
13422:         if (lc($posdom) eq lc($testdomain)) {
13423:             $domain=$posdom;
13424:             last;
13425:         }
13426:     }
13427:     return $domain;
13428: }
13429: 
13430: # ------------------------------------------------------------- Declutters URLs
13431: 
13432: sub declutter {
13433:     my $thisfn=shift;
13434:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13435:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13436:         $thisfn=~s{^/home/httpd/html}{};
13437:     }
13438:     $thisfn=~s/^\///;
13439:     $thisfn=~s|^adm/wrapper/||;
13440:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13441:     $thisfn=~s/^res\///;
13442:     $thisfn=~s/^priv\///;
13443:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13444:         $thisfn=~s/\?.+$//;
13445:     }
13446:     return $thisfn;
13447: }
13448: 
13449: # ------------------------------------------------------------- Clutter up URLs
13450: 
13451: sub clutter {
13452:     my $thisfn='/'.&declutter(shift);
13453:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13454: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13455:        $thisfn='/res'.$thisfn; 
13456:     }
13457:     if ($thisfn !~m|^/adm|) {
13458: 	if ($thisfn =~ m|^/ext/|) {
13459: 	    $thisfn='/adm/wrapper'.$thisfn;
13460: 	} else {
13461: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13462: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13463: 	    if ($embstyle eq 'ssi'
13464: 		|| ($embstyle eq 'hdn')
13465: 		|| ($embstyle eq 'rat')
13466: 		|| ($embstyle eq 'prv')
13467: 		|| ($embstyle eq 'ign')) {
13468: 		#do nothing with these
13469: 	    } elsif (($embstyle eq 'img') 
13470: 		|| ($embstyle eq 'emb')
13471: 		|| ($embstyle eq 'wrp')) {
13472: 		$thisfn='/adm/wrapper'.$thisfn;
13473: 	    } elsif ($embstyle eq 'unk'
13474: 		     && $thisfn!~/\.(sequence|page)$/) {
13475: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13476: 	    } else {
13477: #		&logthis("Got a blank emb style");
13478: 	    }
13479: 	}
13480:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13481:         $thisfn='/adm/wrapper'.$thisfn;
13482:     }
13483:     return $thisfn;
13484: }
13485: 
13486: sub clutter_with_no_wrapper {
13487:     my $uri = &clutter(shift);
13488:     if ($uri =~ m-^/adm/-) {
13489: 	$uri =~ s-^/adm/wrapper/-/-;
13490: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13491:     }
13492:     return $uri;
13493: }
13494: 
13495: sub freeze_escape {
13496:     my ($value)=@_;
13497:     if (ref($value)) {
13498: 	$value=&nfreeze($value);
13499: 	return '__FROZEN__'.&escape($value);
13500:     }
13501:     return &escape($value);
13502: }
13503: 
13504: 
13505: sub thaw_unescape {
13506:     my ($value)=@_;
13507:     if ($value =~ /^__FROZEN__/) {
13508: 	substr($value,0,10,undef);
13509: 	$value=&unescape($value);
13510: 	return &thaw($value);
13511:     }
13512:     return &unescape($value);
13513: }
13514: 
13515: sub correct_line_ends {
13516:     my ($result)=@_;
13517:     $$result =~s/\r\n/\n/mg;
13518:     $$result =~s/\r/\n/mg;
13519: }
13520: # ================================================================ Main Program
13521: 
13522: sub goodbye {
13523:    &logthis("Starting Shut down");
13524: #not converted to using infrastruture and probably shouldn't be
13525:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13526: #converted
13527: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13528:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13529: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13530: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13531: #1.1 only
13532: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13533: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13534: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13535: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13536:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13537:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13538:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13539:    &flushcourselogs();
13540:    &logthis("Shutting down");
13541: }
13542: 
13543: sub get_dns {
13544:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13545:     if (!$ignore_cache) {
13546: 	my ($content,$cached)=
13547: 	    &Apache::lonnet::is_cached_new('dns',$url);
13548: 	if ($cached) {
13549: 	    &$func($content,$hashref);
13550: 	    return;
13551: 	}
13552:     }
13553: 
13554:     my %alldns;
13555:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13556:         foreach my $dns (<$config>) {
13557: 	    next if ($dns !~ /^\^(\S*)/x);
13558:             my $line = $1;
13559:             my ($host,$protocol) = split(/:/,$line);
13560:             if ($protocol ne 'https') {
13561:                 $protocol = 'http';
13562:             }
13563: 	    $alldns{$host} = $protocol;
13564:         }
13565:         close($config);
13566:     }
13567:     while (%alldns) {
13568: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13569: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13570:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13571:         delete($alldns{$dns});
13572: 	next if ($response->is_error());
13573:         if ($url eq '/adm/dns/loncapaCRL') {
13574:             return &$func($response);
13575:         } else {
13576: 	    my @content = split("\n",$response->content);
13577: 	    unless ($nocache) {
13578: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13579: 	    }
13580: 	    &$func(\@content,$hashref);
13581:             return;
13582:         }
13583:     }
13584:     my $which = (split('/',$url,4))[3];
13585:     if ($which eq 'loncapaCRL') {
13586:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13587:         if (-e $diskfile) {
13588:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13589:         } else {
13590:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13591:         }
13592:     } else {
13593:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13594:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13595:             my @content = <$config>;
13596:             close($config);
13597:             &$func(\@content,$hashref);
13598:         }
13599:     }
13600:     return;
13601: }
13602: 
13603: # ------------------------------------------------------Get DNS checksums file
13604: sub parse_dns_checksums_tab {
13605:     my ($lines,$hashref) = @_;
13606:     my $lonhost = $perlvar{'lonHostID'};
13607:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13608:     my $loncaparev = &get_server_loncaparev($machine_dom);
13609:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13610:     my $webconfdir = '/etc/httpd/conf';
13611:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13612:         $webconfdir = '/etc/apache2';
13613:     } elsif ($distro =~ /^sles(\d+)$/) {
13614:         if ($1 >= 10) {
13615:             $webconfdir = '/etc/apache2';
13616:         }
13617:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13618:         if ($1 >= 10.0) {
13619:             $webconfdir = '/etc/apache2';
13620:         }
13621:     }
13622:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13623:     my (%chksum,%revnum);
13624:     if (ref($lines) eq 'ARRAY') {
13625:         chomp(@{$lines});
13626:         my $version = shift(@{$lines});
13627:         if ($version eq $release) {  
13628:             foreach my $line (@{$lines}) {
13629:                 my ($file,$version,$shasum) = split(/,/,$line);
13630:                 if ($file =~ m{^/etc/httpd/conf}) {
13631:                     if ($webconfdir eq '/etc/apache2') {
13632:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13633:                     }
13634:                 }
13635:                 $chksum{$file} = $shasum;
13636:                 $revnum{$file} = $version;
13637:             }
13638:             if (ref($hashref) eq 'HASH') {
13639:                 %{$hashref} = (
13640:                                 sums     => \%chksum,
13641:                                 versions => \%revnum,
13642:                               );
13643:             }
13644:         }
13645:     }
13646:     return;
13647: }
13648: 
13649: sub fetch_dns_checksums {
13650:     my %checksums;
13651:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13652:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13653:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13654:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13655:              \%checksums);
13656:     return \%checksums;
13657: }
13658: 
13659: sub fetch_crl_pemfile {
13660:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
13661: }
13662: 
13663: sub save_crl_pem {
13664:     my ($response) = @_;
13665:     my ($msg,$hadchanges);
13666:     if (ref($response)) {
13667:         my $now = time;
13668:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
13669:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
13670:         if (open(my $fh,'>',"$tmpcrl")) {
13671:             print $fh $response->content;
13672:             close($fh);
13673:             if (-e $lonca) {
13674:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
13675:                     my $check = <PIPE>;
13676:                     close(PIPE);
13677:                     chomp($check);
13678:                     if ($check eq 'verify OK') {
13679:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13680:                         my $backup;
13681:                         if (-e $dest) {
13682:                             if (&File::Copy::move($dest,"$dest.bak")) {
13683:                                 $backup = 'ok';
13684:                             }
13685:                         }
13686:                         if (&File::Copy::move($tmpcrl,$dest)) {
13687:                             $msg = 'ok';
13688:                             if ($backup) {
13689:                                 my (%oldnums,%newnums);
13690:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
13691:                                     while (<PIPE>) {
13692:                                         $oldnums{(split(/:/))[1]} = 1;
13693:                                     }
13694:                                     close(PIPE);
13695:                                 }
13696:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
13697:                                     while(<PIPE>) {
13698:                                         $newnums{(split(/:/))[1]} = 1;
13699:                                     }
13700:                                     close(PIPE);
13701:                                 }
13702:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
13703:                                     unless (exists($oldnums{$key})) {
13704:                                         $hadchanges = 1;
13705:                                         last;
13706:                                     }
13707:                                 }
13708:                                 unless ($hadchanges) {
13709:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
13710:                                         unless (exists($newnums{$key})) {
13711:                                             $hadchanges = 1;
13712:                                             last;
13713:                                         }
13714:                                     }
13715:                                 }
13716:                             }
13717:                         }
13718:                     } else {
13719:                         unlink($tmpcrl);
13720:                     }
13721:                 } else {
13722:                     unlink($tmpcrl);
13723:                 }
13724:             } else {
13725:                 unlink($tmpcrl);
13726:             }
13727:         }
13728:     }
13729:     return ($msg,$hadchanges);
13730: }
13731: 
13732: # ------------------------------------------------------------ Read domain file
13733: {
13734:     my $loaded;
13735:     my %domain;
13736: 
13737:     sub parse_domain_tab {
13738: 	my ($lines) = @_;
13739: 	foreach my $line (@$lines) {
13740: 	    next if ($line =~ /^(\#|\s*$ )/x);
13741: 
13742: 	    chomp($line);
13743: 	    my ($name,@elements) = split(/:/,$line,9);
13744: 	    my %this_domain;
13745: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13746: 			       'lang_def', 'city', 'longi', 'lati',
13747: 			       'primary') {
13748: 		$this_domain{$field} = shift(@elements);
13749: 	    }
13750: 	    $domain{$name} = \%this_domain;
13751: 	}
13752:     }
13753: 
13754:     sub reset_domain_info {
13755: 	undef($loaded);
13756: 	undef(%domain);
13757:     }
13758: 
13759:     sub load_domain_tab {
13760: 	my ($ignore_cache,$nocache) = @_;
13761: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13762: 	my $fh;
13763: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13764: 	    my @lines = <$fh>;
13765: 	    &parse_domain_tab(\@lines);
13766: 	}
13767: 	close($fh);
13768: 	$loaded = 1;
13769:     }
13770: 
13771:     sub domain {
13772: 	&load_domain_tab() if (!$loaded);
13773: 
13774: 	my ($name,$what) = @_;
13775: 	return if ( !exists($domain{$name}) );
13776: 
13777: 	if (!$what) {
13778: 	    return $domain{$name}{'description'};
13779: 	}
13780: 	return $domain{$name}{$what};
13781:     }
13782: 
13783:     sub domain_info {
13784:         &load_domain_tab() if (!$loaded);
13785:         return %domain;
13786:     }
13787: 
13788: }
13789: 
13790: 
13791: # ------------------------------------------------------------- Read hosts file
13792: {
13793:     my %hostname;
13794:     my %hostdom;
13795:     my %libserv;
13796:     my $loaded;
13797:     my %name_to_host;
13798:     my %internetdom;
13799:     my %LC_dns_serv;
13800: 
13801:     sub parse_hosts_tab {
13802: 	my ($file) = @_;
13803: 	foreach my $configline (@$file) {
13804: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13805:             chomp($configline);
13806: 	    if ($configline =~ /^\^/) {
13807:                 if ($configline =~ /^\^([\w.\-]+)/) {
13808:                     $LC_dns_serv{$1} = 1;
13809:                 }
13810:                 next;
13811:             }
13812: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13813: 	    $name=~s/\s//g;
13814: 	    if ($id && $domain && $role && $name) {
13815:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13816:                     my $curr = $hostname{$id};
13817:                     my $skip;
13818:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13819:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13820:                             $skip = 1;
13821:                         } else {
13822:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13823:                         }
13824:                     }
13825:                     unless ($skip) {
13826:                         push(@{$name_to_host{$name}},$id);
13827:                     }
13828:                 } else {
13829:                     push(@{$name_to_host{$name}},$id);
13830:                 }
13831: 		$hostname{$id}=$name;
13832: 		$hostdom{$id}=$domain;
13833: 		if ($role eq 'library') { $libserv{$id}=$name; }
13834:                 if (defined($protocol)) {
13835:                     if ($protocol eq 'https') {
13836:                         $protocol{$id} = $protocol;
13837:                     } else {
13838:                         $protocol{$id} = 'http'; 
13839:                     }
13840:                 } else {
13841:                     $protocol{$id} = 'http';
13842:                 }
13843:                 if (defined($intdom)) {
13844:                     $internetdom{$id} = $intdom;
13845:                 }
13846: 	    }
13847: 	}
13848:     }
13849:     
13850:     sub reset_hosts_info {
13851: 	&purge_remembered();
13852: 	&reset_domain_info();
13853: 	&reset_hosts_ip_info();
13854:         undef(%internetdom);
13855: 	undef(%name_to_host);
13856: 	undef(%hostname);
13857: 	undef(%hostdom);
13858: 	undef(%libserv);
13859: 	undef($loaded);
13860:     }
13861: 
13862:     sub load_hosts_tab {
13863: 	my ($ignore_cache,$nocache) = @_;
13864: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13865: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13866: 	my @config = <$config>;
13867: 	&parse_hosts_tab(\@config);
13868: 	close($config);
13869: 	$loaded=1;
13870:     }
13871: 
13872:     sub hostname {
13873: 	&load_hosts_tab() if (!$loaded);
13874: 
13875: 	my ($lonid) = @_;
13876: 	return $hostname{$lonid};
13877:     }
13878: 
13879:     sub all_hostnames {
13880: 	&load_hosts_tab() if (!$loaded);
13881: 
13882: 	return %hostname;
13883:     }
13884: 
13885:     sub all_names {
13886:         my ($ignore_cache,$nocache) = @_;
13887: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13888: 
13889: 	return %name_to_host;
13890:     }
13891: 
13892:     sub all_host_domain {
13893:         &load_hosts_tab() if (!$loaded);
13894:         return %hostdom;
13895:     }
13896: 
13897:     sub all_host_intdom {
13898:         &load_hosts_tab() if (!$loaded);
13899:         return %internetdom;
13900:     }
13901: 
13902:     sub is_library {
13903: 	&load_hosts_tab() if (!$loaded);
13904: 
13905: 	return exists($libserv{$_[0]});
13906:     }
13907: 
13908:     sub all_library {
13909: 	&load_hosts_tab() if (!$loaded);
13910: 
13911: 	return %libserv;
13912:     }
13913: 
13914:     sub unique_library {
13915: 	#2x reverse removes all hostnames that appear more than once
13916:         my %unique = reverse &all_library();
13917:         return reverse %unique;
13918:     }
13919: 
13920:     sub get_servers {
13921: 	&load_hosts_tab() if (!$loaded);
13922: 
13923: 	my ($domain,$type) = @_;
13924: 	my %possible_hosts = ($type eq 'library') ? %libserv
13925: 	                                          : %hostname;
13926: 	my %result;
13927: 	if (ref($domain) eq 'ARRAY') {
13928: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13929: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13930: 		    $result{$host} = $hostname;
13931: 		}
13932: 	    }
13933: 	} else {
13934: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13935: 		if ($hostdom{$host} eq $domain) {
13936: 		    $result{$host} = $hostname;
13937: 		}
13938: 	    }
13939: 	}
13940: 	return %result;
13941:     }
13942: 
13943:     sub get_unique_servers {
13944:         my %unique = reverse &get_servers(@_);
13945: 	return reverse %unique;
13946:     }
13947: 
13948:     sub host_domain {
13949: 	&load_hosts_tab() if (!$loaded);
13950: 
13951: 	my ($lonid) = @_;
13952: 	return $hostdom{$lonid};
13953:     }
13954: 
13955:     sub all_domains {
13956: 	&load_hosts_tab() if (!$loaded);
13957: 
13958: 	my %seen;
13959: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13960: 	return @uniq;
13961:     }
13962: 
13963:     sub internet_dom {
13964:         &load_hosts_tab() if (!$loaded);
13965: 
13966:         my ($lonid) = @_;
13967:         return $internetdom{$lonid};
13968:     }
13969: 
13970:     sub is_LC_dns {
13971:         &load_hosts_tab() if (!$loaded);
13972: 
13973:         my ($hostname) = @_;
13974:         return exists($LC_dns_serv{$hostname});
13975:     }
13976: 
13977: }
13978: 
13979: { 
13980:     my %iphost;
13981:     my %name_to_ip;
13982:     my %lonid_to_ip;
13983: 
13984:     sub get_hosts_from_ip {
13985: 	my ($ip) = @_;
13986: 	my %iphosts = &get_iphost();
13987: 	if (ref($iphosts{$ip})) {
13988: 	    return @{$iphosts{$ip}};
13989: 	}
13990: 	return;
13991:     }
13992:     
13993:     sub reset_hosts_ip_info {
13994: 	undef(%iphost);
13995: 	undef(%name_to_ip);
13996: 	undef(%lonid_to_ip);
13997:     }
13998: 
13999:     sub get_host_ip {
14000: 	my ($lonid) = @_;
14001: 	if (exists($lonid_to_ip{$lonid})) {
14002: 	    return $lonid_to_ip{$lonid};
14003: 	}
14004: 	my $name=&hostname($lonid);
14005:    	my $ip = gethostbyname($name);
14006: 	return if (!$ip || length($ip) ne 4);
14007: 	$ip=inet_ntoa($ip);
14008: 	$name_to_ip{$name}   = $ip;
14009: 	$lonid_to_ip{$lonid} = $ip;
14010: 	return $ip;
14011:     }
14012:     
14013:     sub get_iphost {
14014: 	my ($ignore_cache,$nocache) = @_;
14015: 
14016: 	if (!$ignore_cache) {
14017: 	    if (%iphost) {
14018: 		return %iphost;
14019: 	    }
14020: 	    my ($ip_info,$cached)=
14021: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14022: 	    if ($cached) {
14023: 		%iphost      = %{$ip_info->[0]};
14024: 		%name_to_ip  = %{$ip_info->[1]};
14025: 		%lonid_to_ip = %{$ip_info->[2]};
14026: 		return %iphost;
14027: 	    }
14028: 	}
14029: 
14030: 	# get yesterday's info for fallback
14031: 	my %old_name_to_ip;
14032: 	my ($ip_info,$cached)=
14033: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14034: 	if ($cached) {
14035: 	    %old_name_to_ip = %{$ip_info->[1]};
14036: 	}
14037: 
14038: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14039: 	foreach my $name (keys(%name_to_host)) {
14040: 	    my $ip;
14041: 	    if (!exists($name_to_ip{$name})) {
14042: 		$ip = gethostbyname($name);
14043: 		if (!$ip || length($ip) ne 4) {
14044: 		    if (defined($old_name_to_ip{$name})) {
14045: 			$ip = $old_name_to_ip{$name};
14046: 			&logthis("Can't find $name defaulting to old $ip");
14047: 		    } else {
14048: 			&logthis("Name $name no IP found");
14049: 			next;
14050: 		    }
14051: 		} else {
14052: 		    $ip=inet_ntoa($ip);
14053: 		}
14054: 		$name_to_ip{$name} = $ip;
14055: 	    } else {
14056: 		$ip = $name_to_ip{$name};
14057: 	    }
14058: 	    foreach my $id (@{ $name_to_host{$name} }) {
14059: 		$lonid_to_ip{$id} = $ip;
14060: 	    }
14061: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14062: 	}
14063:         unless ($nocache) {
14064: 	    &do_cache_new('iphost','iphost',
14065: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14066: 		          48*60*60);
14067:         }
14068: 
14069: 	return %iphost;
14070:     }
14071: 
14072:     #
14073:     #  Given a DNS returns the loncapa host name for that DNS 
14074:     # 
14075:     sub host_from_dns {
14076:         my ($dns) = @_;
14077:         my @hosts;
14078:         my $ip;
14079: 
14080:         if (exists($name_to_ip{$dns})) {
14081:             $ip = $name_to_ip{$dns};
14082:         }
14083:         if (!$ip) {
14084:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14085:             if (length($ip) == 4) { 
14086: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14087:             }
14088:         }
14089:         if ($ip) {
14090: 	    @hosts = get_hosts_from_ip($ip);
14091: 	    return $hosts[0];
14092:         }
14093:         return undef;
14094:     }
14095: 
14096:     sub get_internet_names {
14097:         my ($lonid) = @_;
14098:         return if ($lonid eq '');
14099:         my ($idnref,$cached)=
14100:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14101:         if ($cached) {
14102:             return $idnref;
14103:         }
14104:         my $ip = &get_host_ip($lonid);
14105:         my @hosts = &get_hosts_from_ip($ip);
14106:         my %iphost = &get_iphost();
14107:         my (@idns,%seen);
14108:         foreach my $id (@hosts) {
14109:             my $dom = &host_domain($id);
14110:             my $prim_id = &domain($dom,'primary');
14111:             my $prim_ip = &get_host_ip($prim_id);
14112:             next if ($seen{$prim_ip});
14113:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14114:                 foreach my $id (@{$iphost{$prim_ip}}) {
14115:                     my $intdom = &internet_dom($id);
14116:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14117:                         push(@idns,$intdom);
14118:                     }
14119:                 }
14120:             }
14121:             $seen{$prim_ip} = 1;
14122:         }
14123:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14124:     }
14125: 
14126: }
14127: 
14128: sub all_loncaparevs {
14129:     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);
14130: }
14131: 
14132: # ---------------------------------------------------------- Read loncaparev table
14133: {
14134:     sub load_loncaparevs { 
14135:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14136:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14137:                 while (my $configline=<$config>) {
14138:                     chomp($configline);
14139:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14140:                     $loncaparevs{$hostid}=$loncaparev;
14141:                 }
14142:                 close($config);
14143:             }
14144:         }
14145:     }
14146: }
14147: 
14148: # ---------------------------------------------------------- Read serverhostID table
14149: {
14150:     sub load_serverhomeIDs {
14151:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14152:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14153:                 while (my $configline=<$config>) {
14154:                     chomp($configline);
14155:                     my ($name,$id)=split(/:/,$configline);
14156:                     $serverhomeIDs{$name}=$id;
14157:                 }
14158:                 close($config);
14159:             }
14160:         }
14161:     }
14162: }
14163: 
14164: 
14165: BEGIN {
14166: 
14167: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14168:     unless ($readit) {
14169: {
14170:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14171:     %perlvar = (%perlvar,%{$configvars});
14172: }
14173: 
14174: 
14175: # ------------------------------------------------------ Read spare server file
14176: {
14177:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14178: 
14179:     while (my $configline=<$config>) {
14180:        chomp($configline);
14181:        if ($configline) {
14182: 	   my ($host,$type) = split(':',$configline,2);
14183: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14184: 	   push(@{ $spareid{$type} }, $host);
14185:        }
14186:     }
14187:     close($config);
14188: }
14189: # ------------------------------------------------------------ Read permissions
14190: {
14191:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14192: 
14193:     while (my $configline=<$config>) {
14194: 	chomp($configline);
14195: 	if ($configline) {
14196: 	    my ($role,$perm)=split(/ /,$configline);
14197: 	    if ($perm ne '') { $pr{$role}=$perm; }
14198: 	}
14199:     }
14200:     close($config);
14201: }
14202: 
14203: # -------------------------------------------- Read plain texts for permissions
14204: {
14205:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14206: 
14207:     while (my $configline=<$config>) {
14208: 	chomp($configline);
14209: 	if ($configline) {
14210: 	    my ($short,@plain)=split(/:/,$configline);
14211:             %{$prp{$short}} = ();
14212: 	    if (@plain > 0) {
14213:                 $prp{$short}{'std'} = $plain[0];
14214:                 for (my $i=1; $i<@plain; $i++) {
14215:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14216:                 }
14217:             }
14218: 	}
14219:     }
14220:     close($config);
14221: }
14222: 
14223: # ---------------------------------------------------------- Read package table
14224: {
14225:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14226: 
14227:     while (my $configline=<$config>) {
14228: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14229: 	chomp($configline);
14230: 	my ($short,$plain)=split(/:/,$configline);
14231: 	my ($pack,$name)=split(/\&/,$short);
14232: 	if ($plain ne '') {
14233: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14234: 	    $packagetab{$short}=$plain; 
14235: 	}
14236:     }
14237:     close($config);
14238: }
14239: 
14240: # ---------------------------------------------------------- Read loncaparev table
14241: 
14242: &load_loncaparevs();
14243: 
14244: # ---------------------------------------------------------- Read serverhostID table
14245: 
14246: &load_serverhomeIDs();
14247: 
14248: # ---------------------------------------------------------- Read releaseslist XML
14249: {
14250:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14251:     if (-e $file) {
14252:         my $parser = HTML::LCParser->new($file);
14253:         while (my $token = $parser->get_token()) {
14254:             if ($token->[0] eq 'S') {
14255:                 my $item = $token->[1];
14256:                 my $name = $token->[2]{'name'};
14257:                 my $value = $token->[2]{'value'};
14258:                 my $valuematch = $token->[2]{'valuematch'};
14259:                 my $namematch = $token->[2]{'namematch'};
14260:                 if ($item eq 'parameter') {
14261:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14262:                         my $release = $parser->get_text();
14263:                         $release =~ s/(^\s*|\s*$ )//gx;
14264:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14265:                     }
14266:                 } elsif ($item ne '' && $name ne '') {
14267:                     my $release = $parser->get_text();
14268:                     $release =~ s/(^\s*|\s*$ )//gx;
14269:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14270:                 }
14271:             }
14272:         }
14273:     }
14274: }
14275: 
14276: # ---------------------------------------------------------- Read managers table
14277: {
14278:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14279:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14280:             while (my $configline=<$config>) {
14281:                 chomp($configline);
14282:                 next if ($configline =~ /^\#/);
14283:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14284:                     $managerstab{$configline} = 1;
14285:                 }
14286:             }
14287:             close($config);
14288:         }
14289:     }
14290: }
14291: 
14292: # ------------- set up temporary directory
14293: {
14294:     $tmpdir = LONCAPA::tempdir();
14295: 
14296: }
14297: 
14298: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14299: 				'compress_threshold'=> 20_000,
14300:  			        });
14301: 
14302: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14303: $dumpcount=0;
14304: $locknum=0;
14305: 
14306: &logtouch();
14307: &logthis('<font color="yellow">INFO: Read configuration</font>');
14308: $readit=1;
14309:     {
14310: 	use integer;
14311: 	my $test=(2**32)+1;
14312: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14313: 	&logthis(" Detected 64bit platform ($_64bit)");
14314:     }
14315: }
14316: }
14317: 
14318: 1;
14319: __END__
14320: 
14321: =pod
14322: 
14323: =head1 NAME
14324: 
14325: Apache::lonnet - Subroutines to ask questions about things in the network.
14326: 
14327: =head1 SYNOPSIS
14328: 
14329: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14330: 
14331:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14332: 
14333: Common parameters:
14334: 
14335: =over 4
14336: 
14337: =item *
14338: 
14339: $uname : an internal username (if $cname expecting a course Id specifically)
14340: 
14341: =item *
14342: 
14343: $udom : a domain (if $cdom expecting a course's domain specifically)
14344: 
14345: =item *
14346: 
14347: $symb : a resource instance identifier
14348: 
14349: =item *
14350: 
14351: $namespace : the name of a .db file that contains the data needed or
14352: being set.
14353: 
14354: =back
14355: 
14356: =head1 OVERVIEW
14357: 
14358: lonnet provides subroutines which interact with the
14359: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14360: about classes, users, and resources.
14361: 
14362: For many of these objects you can also use this to store data about
14363: them or modify them in various ways.
14364: 
14365: =head2 Symbs
14366: 
14367: To identify a specific instance of a resource, LON-CAPA uses symbols
14368: or "symbs"X<symb>. These identifiers are built from the URL of the
14369: map, the resource number of the resource in the map, and the URL of
14370: the resource itself. The latter is somewhat redundant, but might help
14371: if maps change.
14372: 
14373: An example is
14374: 
14375:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14376: 
14377: The respective map entry is
14378: 
14379:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14380:   title="Problem 2">
14381:  </resource>
14382: 
14383: Symbs are used by the random number generator, as well as to store and
14384: restore data specific to a certain instance of for example a problem.
14385: 
14386: =head2 Storing And Retrieving Data
14387: 
14388: X<store()>X<cstore()>X<restore()>Three of the most important functions
14389: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14390: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14391: is is the non-critical message twin of cstore. These functions are for
14392: handlers to store a perl hash to a user's permanent data space in an
14393: easy manner, and to retrieve it again on another call. It is expected
14394: that a handler would use this once at the beginning to retrieve data,
14395: and then again once at the end to send only the new data back.
14396: 
14397: The data is stored in the user's data directory on the user's
14398: homeserver under the ID of the course.
14399: 
14400: The hash that is returned by restore will have all of the previous
14401: value for all of the elements of the hash.
14402: 
14403: Example:
14404: 
14405:  #creating a hash
14406:  my %hash;
14407:  $hash{'foo'}='bar';
14408: 
14409:  #storing it
14410:  &Apache::lonnet::cstore(\%hash);
14411: 
14412:  #changing a value
14413:  $hash{'foo'}='notbar';
14414: 
14415:  #adding a new value
14416:  $hash{'bar'}='foo';
14417:  &Apache::lonnet::cstore(\%hash);
14418: 
14419:  #retrieving the hash
14420:  my %history=&Apache::lonnet::restore();
14421: 
14422:  #print the hash
14423:  foreach my $key (sort(keys(%history))) {
14424:    print("\%history{$key} = $history{$key}");
14425:  }
14426: 
14427: Will print out:
14428: 
14429:  %history{1:foo} = bar
14430:  %history{1:keys} = foo:timestamp
14431:  %history{1:timestamp} = 990455579
14432:  %history{2:bar} = foo
14433:  %history{2:foo} = notbar
14434:  %history{2:keys} = foo:bar:timestamp
14435:  %history{2:timestamp} = 990455580
14436:  %history{bar} = foo
14437:  %history{foo} = notbar
14438:  %history{timestamp} = 990455580
14439:  %history{version} = 2
14440: 
14441: Note that the special hash entries C<keys>, C<version> and
14442: C<timestamp> were added to the hash. C<version> will be equal to the
14443: total number of versions of the data that have been stored. The
14444: C<timestamp> attribute will be the UNIX time the hash was
14445: stored. C<keys> is available in every historical section to list which
14446: keys were added or changed at a specific historical revision of a
14447: hash.
14448: 
14449: B<Warning>: do not store the hash that restore returns directly. This
14450: will cause a mess since it will restore the historical keys as if the
14451: were new keys. I.E. 1:foo will become 1:1:foo etc.
14452: 
14453: Calling convention:
14454: 
14455:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14456:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14457: 
14458: For more detailed information, see lonnet specific documentation.
14459: 
14460: =head1 RETURN MESSAGES
14461: 
14462: =over 4
14463: 
14464: =item * B<con_lost>: unable to contact remote host
14465: 
14466: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14467: when the connection is brought back up
14468: 
14469: =item * B<con_failed>: unable to contact remote host and unable to save message
14470: for later delivery
14471: 
14472: =item * B<error:>: an error a occurred, a description of the error follows the :
14473: 
14474: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14475: that was requested
14476: 
14477: =back
14478: 
14479: =head1 PUBLIC SUBROUTINES
14480: 
14481: =head2 Session Environment Functions
14482: 
14483: =over 4
14484: 
14485: =item * 
14486: X<appenv()>
14487: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14488: the user envirnoment file, and will be restored for each access this
14489: user makes during this session, also modifies the %env for the current
14490: process. Optional rolesarrayref - if defined contains a reference to an array
14491: of roles which are exempt from the restriction on modifying user.role entries 
14492: in the user's environment.db and in %env.    
14493: 
14494: =item *
14495: X<delenv()>
14496: B<delenv($delthis,$regexp)>: removes all items from the session
14497: environment file that begin with $delthis. If the 
14498: optional second arg - $regexp - is true, $delthis is treated as a 
14499: regular expression, otherwise \Q$delthis\E is used. 
14500: The values are also deleted from the current processes %env.
14501: 
14502: =item * get_env_multiple($name) 
14503: 
14504: gets $name from the %env hash, it seemlessly handles the cases where multiple
14505: values may be defined and end up as an array ref.
14506: 
14507: returns an array of values
14508: 
14509: =back
14510: 
14511: =head2 User Information
14512: 
14513: =over 4
14514: 
14515: =item *
14516: X<queryauthenticate()>
14517: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14518: authentication scheme
14519: 
14520: =item *
14521: X<authenticate()>
14522: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14523: authenticate user from domain's lib servers (first use the current
14524: one). C<$upass> should be the users password.
14525: $checkdefauth is optional (value is 1 if a check should be made to
14526:    authenticate user using default authentication method, and allow
14527:    account creation if username does not have account in the domain).
14528: $clientcancheckhost is optional (value is 1 if checking whether the
14529:    server can host will occur on the client side in lonauth.pm).   
14530: 
14531: =item *
14532: X<homeserver()>
14533: B<homeserver($uname,$udom)>: find the server which has
14534: the user's directory and files (there must be only one), this caches
14535: the answer, and also caches if there is a borken connection.
14536: 
14537: =item *
14538: X<idget()>
14539: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14540: a list of student/employee IDs or clicker IDs
14541: (student/employee IDs are a unique resource in a domain, there must be 
14542: only 1 ID per username, and only 1 username per ID in a specific domain).
14543: clickerIDs are not necessarily unique, as students might share clickers.
14544: (returns hash: id=>name,id=>name)
14545: 
14546: =item *
14547: X<idrget()>
14548: B<idrget($udom,@unames)>: find the IDs behind a list of
14549: usernames (returns hash: name=>id,name=>id)
14550: 
14551: =item *
14552: X<idput()>
14553: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14554: names and associated student/employee IDs or clicker IDs.
14555: 
14556: =item *
14557: X<iddel()>
14558: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14559: student/employee ID or clicker ID username look-ups from domain.
14560: The homeserver ($uhome) and namespace ($namespace) are optional.
14561: If no $uhome is provided, it will be determined usig &homeserver()
14562: for each user.  If no $namespace is provided, the default is ids.
14563: 
14564: =item *
14565: X<updateclickers()>
14566: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14567: clicker ID-to-username look-ups in clickers.db on library server.
14568: Permitted actions are add or del (i.e., add or delete). The 
14569: clickers.db contains clickerID as keys (escaped), and each corresponding
14570: value is an escaped comma-separated list of usernames (for whom the
14571: library server is the homeserver), who registered that particular ID.
14572: If $critical is true, the update will be sent via &critical, otherwise
14573: &reply() will be used.
14574: 
14575: =item *
14576: X<rolesinit()>
14577: B<rolesinit($udom,$username)>: get user privileges.
14578: returns user role, first access and timer interval hashes
14579: 
14580: =item *
14581: X<privileged()>
14582: B<privileged($username,$domain)>: returns a true if user has a
14583: privileged and active role (i.e. su or dc), false otherwise.
14584: 
14585: =item *
14586: X<getsection()>
14587: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14588: course $cname, return section name/number or '' for "not in course"
14589: and '-1' for "no section"
14590: 
14591: =item *
14592: X<userenvironment()>
14593: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14594: passed in @what from the requested user's environment, returns a hash
14595: 
14596: =item * 
14597: X<userlog_query()>
14598: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14599: activity.log file. %filters defines filters applied when parsing the
14600: log file. These can be start or end timestamps, or the type of action
14601: - log to look for Login or Logout events, check for Checkin or
14602: Checkout, role for role selection. The response is in the form
14603: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14604: escaped strings of the action recorded in the activity.log file.
14605: 
14606: =back
14607: 
14608: =head2 User Roles
14609: 
14610: =over 4
14611: 
14612: =item *
14613: 
14614: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14615: returns codes for allowed actions.
14616: 
14617: The first argument is required, all others are optional.
14618: 
14619: $priv is the privilege being checked.
14620: $uri contains additional information about what is being checked for access (e.g.,
14621: URL, course ID etc.). 
14622: $symb is the unique resource instance identifier in a course; if needed,
14623: but not provided, it will be retrieved via a call to &symbread(). 
14624: $role is the role for which a priv is being checked (only used if priv is evb). 
14625: $clientip is the user's IP address (only used when checking for access to portfolio 
14626: files).
14627: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14628: prevents recursive calls to &allowed.
14629: 
14630:  F: full access
14631:  U,I,K: authentication modes (cxx only)
14632:  '': forbidden
14633:  1: user needs to choose course
14634:  2: browse allowed
14635:  A: passphrase authentication needed
14636:  B: access temporarily blocked because of a blocking event in a course.
14637: 
14638: =item *
14639: 
14640: constructaccess($url,$setpriv) : check for access to construction space URL
14641: 
14642: See if the owner domain and name in the URL match those in the
14643: expected environment.  If so, return three element list
14644: ($ownername,$ownerdomain,$ownerhome).
14645: 
14646: Otherwise return the null string.
14647: 
14648: If second argument 'setpriv' is true, it assigns the privileges,
14649: and returns the same three element list, unless the owner has
14650: blocked "ad hoc" Domain Coordinator access to the Author Space,
14651: in which case the null string is returned.
14652: 
14653: =item *
14654: 
14655: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14656: define a custom role rolename set privileges in format of lonTabs/roles.tab
14657: for system, domain, and course level. $uname and $udom are optional (current
14658: user's username and domain will be used when either of $uname or $udom are absent.
14659: 
14660: =item *
14661: 
14662: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14663: (rolesplain.tab); plain text explanation of a user role term.
14664: $type is Course (default) or Community.
14665: If $forcedefault evaluates to true, text returned will be default 
14666: text for $type. Otherwise, if this is a course, the text returned 
14667: will be a custom name for the role (if defined in the course's 
14668: environment).  If no custom name is defined the default is returned.
14669:    
14670: =item *
14671: 
14672: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14673: All arguments are optional. Returns a hash of a roles, either for
14674: co-author/assistant author roles for a user's Construction Space
14675: (default), or if $context is 'userroles', roles for the user himself,
14676: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14677: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14678: For each key, value is set to colon-separated start and end times for
14679: the role.  If no username and domain are specified, will default to
14680: current user/domain. Types, roles, and roledoms are references to arrays
14681: of role statuses (active, future or previous), roles 
14682: (e.g., cc,in, st etc.) and domains of the roles which can be used
14683: to restrict the list of roles reported. If no array ref is 
14684: provided for types, will default to return only active roles.
14685: 
14686: =item *
14687: 
14688: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14689: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14690: 
14691: Additional optional arguments are: $type (if role checking is to be restricted 
14692: to certain user status types -- previous (expired roles), active (currently
14693: available roles) or future (roles available in the future), and
14694: $hideprivileged -- if true will not report course roles for users who
14695: have active Domain Coordinator role in course's domain or in additional
14696: domains (specified in 'Domains to check for privileged users' in course
14697: environment -- set via:  Course Settings -> Classlists and staff listing).
14698: 
14699: =item *
14700: 
14701: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14702: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14703: $possdomains and $possroles are optional array refs -- to domains to check and
14704: roles to check.  If $possdomains is not specified, a dump will be done of the
14705: users' roles.db to check for a dc or su role in any domain. This can be
14706: time consuming if &privileged is called repeatedly (e.g., when displaying a
14707: classlist), so in such cases, supplying a $possdomains array is preferred, as
14708: this then allows &privileged_by_domain() to be used, which caches the identity
14709: of privileged users, eliminating the need for repeated calls to &dump().
14710: 
14711: =item *
14712: 
14713: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14714: where the outer hash keys are domains specified in the $possdomains array ref,
14715: next inner hash keys are privileged roles specified in the $roles array ref,
14716: and the innermost hash contains key = value pairs for username:domain = end:start
14717: for active or future "privileged" users with that role in that domain. To avoid
14718: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14719: innerhash are cached using priv_$role and $dom as the identifiers.
14720: 
14721: =back
14722: 
14723: =head2 User Modification
14724: 
14725: =over 4
14726: 
14727: =item *
14728: 
14729: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14730: user for the level given by URL.  Optional start and end dates (leave empty
14731: string or zero for "no date")
14732: 
14733: =item *
14734: 
14735: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14736: change a users, password, possible return values are: ok,
14737: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14738: refused
14739: 
14740: =item *
14741: 
14742: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14743: 
14744: =item *
14745: 
14746: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14747:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14748: 
14749: will update user information (firstname,middlename,lastname,generation,
14750: permanentemail), and if forceid is true, student/employee ID also.
14751: A user's institutional affiliation(s) can also be updated.
14752: User information fields will not be overwritten with empty entries 
14753: unless the field is included in the $candelete array reference.
14754: This array is included when a single user is modified via "Manage Users",
14755: or when Autoupdate.pl is run by cron in a domain.
14756: 
14757: =item *
14758: 
14759: modifystudent
14760: 
14761: modify a student's enrollment and identification information.
14762: The course id is resolved based on the current user's environment.  
14763: This means the invoking user must be a course coordinator or otherwise
14764: associated with a course.
14765: 
14766: This call is essentially a wrapper for lonnet::modifyuser and
14767: lonnet::modify_student_enrollment
14768: 
14769: Inputs: 
14770: 
14771: =over 4
14772: 
14773: =item B<$udom> Student's loncapa domain
14774: 
14775: =item B<$uname> Student's loncapa login name
14776: 
14777: =item B<$uid> Student/Employee ID
14778: 
14779: =item B<$umode> Student's authentication mode
14780: 
14781: =item B<$upass> Student's password
14782: 
14783: =item B<$first> Student's first name
14784: 
14785: =item B<$middle> Student's middle name
14786: 
14787: =item B<$last> Student's last name
14788: 
14789: =item B<$gene> Student's generation
14790: 
14791: =item B<$usec> Student's section in course
14792: 
14793: =item B<$end> Unix time of the roles expiration
14794: 
14795: =item B<$start> Unix time of the roles start date
14796: 
14797: =item B<$forceid> If defined, allow $uid to be changed
14798: 
14799: =item B<$desiredhome> server to use as home server for student
14800: 
14801: =item B<$email> Student's permanent e-mail address
14802: 
14803: =item B<$type> Type of enrollment (auto or manual)
14804: 
14805: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14806: 
14807: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14808: 
14809: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14810: 
14811: =item B<$context> role change context (shown in User Management Logs display in a course)
14812: 
14813: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14814: 
14815: =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.
14816: 
14817: =back
14818: 
14819: =item *
14820: 
14821: modify_student_enrollment
14822: 
14823: Change a student's enrollment status in a class.  The environment variable
14824: 'role.request.course' must be defined for this function to proceed.
14825: 
14826: Inputs:
14827: 
14828: =over 4
14829: 
14830: =item $udom, student's domain
14831: 
14832: =item $uname, student's name
14833: 
14834: =item $uid, student's user id
14835: 
14836: =item $first, student's first name
14837: 
14838: =item $middle
14839: 
14840: =item $last
14841: 
14842: =item $gene
14843: 
14844: =item $usec
14845: 
14846: =item $end
14847: 
14848: =item $start
14849: 
14850: =item $type
14851: 
14852: =item $locktype
14853: 
14854: =item $cid
14855: 
14856: =item $selfenroll
14857: 
14858: =item $context
14859: 
14860: =item $credits, number of credits student will earn from this class
14861: 
14862: =item $instsec, institutional course section code for student
14863: 
14864: =back
14865: 
14866: 
14867: =item *
14868: 
14869: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14870: custom role; give a custom role to a user for the level given by URL.  Specify
14871: name and domain of role author, and role name
14872: 
14873: =item *
14874: 
14875: revokerole($udom,$uname,$url,$role) : revoke a role for url
14876: 
14877: =item *
14878: 
14879: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14880: 
14881: =back
14882: 
14883: =head2 Course Infomation
14884: 
14885: =over 4
14886: 
14887: =item *
14888: 
14889: coursedescription($courseid,$options) : returns a hash of information about the
14890: specified course id, including all environment settings for the
14891: course, the description of the course will be in the hash under the
14892: key 'description'
14893: 
14894: $options is an optional parameter that if supplied is a hash reference that controls
14895: what how this function works.  It has the following key/values:
14896: 
14897: =over 4
14898: 
14899: =item freshen_cache
14900: 
14901: If defined, and the environment cache for the course is valid, it is 
14902: returned in the returned hash.
14903: 
14904: =item one_time
14905: 
14906: If defined, the last cache time is set to _now_
14907: 
14908: =item user
14909: 
14910: If defined, the supplied username is used instead of the current user.
14911: 
14912: 
14913: =back
14914: 
14915: =item *
14916: 
14917: resdata($name,$domain,$type,@which) : request for current parameter
14918: setting for a specific $type, where $type is either 'course' or 'user',
14919: @what should be a list of parameters to ask about. This routine caches
14920: answers for 10 minutes.
14921: 
14922: =item *
14923: 
14924: get_courseresdata($courseid, $domain) : dump the entire course resource
14925: data base, returning a hash that is keyed by the resource name and has
14926: values that are the resource value.  I believe that the timestamps and
14927: versions are also returned.
14928: 
14929: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14930: supplemental content area. This routine caches the number of files for 
14931: 10 minutes.
14932: 
14933: =back
14934: 
14935: =head2 Course Modification
14936: 
14937: =over 4
14938: 
14939: =item *
14940: 
14941: writecoursepref($courseid,%prefs) : write preferences (environment
14942: database) for a course
14943: 
14944: =item *
14945: 
14946: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14947: 
14948: =item *
14949: 
14950: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14951: 
14952: =item *
14953: 
14954: is_course($courseid), is_course($cdom, $cnum)
14955: 
14956: Accepts either a combined $courseid (in the form of domain_courseid) or the
14957: two component version $cdom, $cnum. It checks if the specified course exists.
14958: 
14959: Returns:
14960:     undef if the course doesn't exist, otherwise
14961:     in scalar context the combined courseid.
14962:     in list context the two components of the course identifier, domain and 
14963:     courseid.    
14964: 
14965: =back
14966: 
14967: =head2 Resource Subroutines
14968: 
14969: =over 4
14970: 
14971: =item *
14972: 
14973: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14974: 
14975: =item *
14976: 
14977: repcopy($filename) : subscribes to the requested file, and attempts to
14978: replicate from the owning library server, Might return
14979: 'unavailable', 'not_found', 'forbidden', 'ok', or
14980: 'bad_request', also attempts to grab the metadata for the
14981: resource. Expects the local filesystem pathname
14982: (/home/httpd/html/res/....)
14983: 
14984: =back
14985: 
14986: =head2 Resource Information
14987: 
14988: =over 4
14989: 
14990: =item *
14991: 
14992: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14993: and returns the value of a variety of different possible values,
14994: $varname should be a request string, and the other parameters can be
14995: used to specify who and what one is asking about. Ordinarily, $cid 
14996: does not need to be specified, as it is retrived from 
14997: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14998: within lonuserstate::loadmap() when initializing a course, before
14999: $env{'request.course.id'} has been set, so it needs to be provided
15000: in that one case.
15001: 
15002: Possible values for $varname are environment.lastname (or other item
15003: from the envirnment hash), user.name (or someother aspect about the
15004: user), resource.0.maxtries (or some other part and parameter of a
15005: resource)
15006: 
15007: =item *
15008: 
15009: directcondval($number) : get current value of a condition; reads from a state
15010: string
15011: 
15012: =item *
15013: 
15014: condval($condidx) : value of condition index based on state
15015: 
15016: =item *
15017: 
15018: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15019: resource's metadata, $what should be either a specific key, or either
15020: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15021: packages that this resource currently uses, the last 3 arguments are 
15022: only used internally for recursive metadata.
15023: 
15024: the toolsymb is only used where the uri is for an external tool (for which
15025: the uri as well as the symb are guaranteed to be unique).
15026: 
15027: this function automatically caches all requests except any made recursively
15028: to retrieve a list of metadata keys for an imported library file ($liburi is 
15029: defined).
15030: 
15031: =item *
15032: 
15033: metadata_query($query,$custom,$customshow) : make a metadata query against the
15034: network of library servers; returns file handle of where SQL and regex results
15035: will be stored for query
15036: 
15037: =item *
15038: 
15039: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15040: return symbolic list entry (all arguments optional). 
15041: 
15042: Args: filename is the filename (including path) for the file for which a symb 
15043: is required; donotrecurse, if true will prevent calls to allowed() being made 
15044: to check access status if more than one resource was found in the bighash 
15045: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15046: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15047: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15048: cause possible symbs to be checked to determine if they are subject to content
15049: blocking, if so they will not be included as possible symbs; possibles is a
15050: ref to a hash, which, as a side effect, will be populated with all possible 
15051: symbs (content blocking not tested).
15052:  
15053: returns the data handle
15054: 
15055: =item *
15056: 
15057: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15058: and is a possible symb for the URL in $thisfn, and if is an encrypted
15059: resource that the user accessed using /enc/ returns a 1 on success, 0
15060: on failure, user must be in a course, as it assumes the existence of
15061: the course initial hash, and uses $env('request.course.id'}.  The third
15062: arg is an optional reference to a scalar.  If this arg is passed in the 
15063: call to symbverify, it will be set to 1 if the symb has been set to be 
15064: encrypted; otherwise it will be null.  
15065: 
15066: =item *
15067: 
15068: symbclean($symb) : removes versions numbers from a symb, returns the
15069: cleaned symb
15070: 
15071: =item *
15072: 
15073: is_on_map($uri) : checks if the $uri is somewhere on the current
15074: course map, user must be in a course for it to work.
15075: 
15076: =item *
15077: 
15078: numval($salt) : return random seed value (addend for rndseed)
15079: 
15080: =item *
15081: 
15082: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15083: a random seed, all arguments are optional, if they aren't sent it uses the
15084: environment to derive them. Note: if symb isn't sent and it can't get one
15085: from &symbread it will use the current time as its return value
15086: 
15087: =item *
15088: 
15089: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15090: unfakeable, receipt
15091: 
15092: =item *
15093: 
15094: receipt() : API to ireceipt working off of env values; given out to users
15095: 
15096: =item *
15097: 
15098: countacc($url) : count the number of accesses to a given URL
15099: 
15100: =item *
15101: 
15102: 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
15103: 
15104: =item *
15105: 
15106: 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)
15107: 
15108: =item *
15109: 
15110: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15111: 
15112: =item *
15113: 
15114: devalidate($symb) : devalidate temporary spreadsheet calculations,
15115: forcing spreadsheet to reevaluate the resource scores next time.
15116: 
15117: =item * 
15118: 
15119: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15120: when viewing in course context.
15121: 
15122:  input: six args -- filename (decluttered), course number, course domain,
15123:                     url, symb (if registered) and group (if this is a 
15124:                     group item -- e.g., bulletin board, group page etc.).
15125: 
15126:  output: array of five scalars --
15127:          $cfile -- url for file editing if editable on current server
15128:          $home -- homeserver of resource (i.e., for author if published,
15129:                                           or course if uploaded.).
15130:          $switchserver --  1 if server switch will be needed.
15131:          $forceedit -- 1 if icon/link should be to go to edit mode 
15132:          $forceview -- 1 if icon/link should be to go to view mode
15133: 
15134: =item *
15135: 
15136: is_course_upload($file,$cnum,$cdom)
15137: 
15138: Used in course context to determine if current file was uploaded to 
15139: the course (i.e., would be found in /userfiles/docs on the course's 
15140: homeserver.
15141: 
15142:   input: 3 args -- filename (decluttered), course number and course domain.
15143:   output: boolean -- 1 if file was uploaded.
15144: 
15145: =back
15146: 
15147: =head2 Storing/Retreiving Data
15148: 
15149: =over 4
15150: 
15151: =item *
15152: 
15153: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15154: permanently for this url; hashref needs to be given and should be a \%hashname;
15155: the remaining args aren't required and if they aren't passed or are '' they will
15156: be derived from the env (with the exception of $laststore, which is an 
15157: optional arg used when a user's submission is stored in grading).
15158: $laststore is $version=$timestamp, where $version is the most recent version
15159: number retrieved for the corresponding $symb in the $namespace db file, and
15160: $timestamp is the timestamp for that transaction (UNIX time).
15161: $laststore is currently only passed when cstore() is called by 
15162: structuretags::finalize_storage().
15163: 
15164: =item *
15165: 
15166: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15167: but uses critical subroutine
15168: 
15169: =item *
15170: 
15171: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15172: all args are optional
15173: 
15174: =item *
15175: 
15176: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15177: dumps the complete (or key matching regexp) namespace into a hash
15178: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15179: normally &store()ed into
15180: 
15181: $range should be either an integer '100' (give me the first 100
15182:                                            matching records)
15183:               or be  two integers sperated by a - with no spaces
15184:                  '30-50' (give me the 30th through the 50th matching
15185:                           records)
15186: 
15187: 
15188: =item *
15189: 
15190: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15191: replaces a &store() version of data with a replacement set of data
15192: for a particular resource in a namespace passed in the $storehash hash 
15193: reference. If $tolog is true, the transaction is logged in the courselog
15194: with an action=PUTSTORE.
15195: 
15196: =item *
15197: 
15198: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15199: works very similar to store/cstore, but all data is stored in a
15200: temporary location and can be reset using tmpreset, $storehash should
15201: be a hash reference, returns nothing on success
15202: 
15203: =item *
15204: 
15205: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15206: similar to restore, but all data is stored in a temporary location and
15207: can be reset using tmpreset. Returns a hash of values on success,
15208: error string otherwise.
15209: 
15210: =item *
15211: 
15212: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15213: deltes all keys for $symb form the temporary storage hash.
15214: 
15215: =item *
15216: 
15217: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15218: reference filled in from namesp ($udom and $uname are optional)
15219: 
15220: =item *
15221: 
15222: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15223: namesp ($udom and $uname are optional)
15224: 
15225: =item *
15226: 
15227: dump($namespace,$udom,$uname,$regexp,$range) : 
15228: dumps the complete (or key matching regexp) namespace into a hash
15229: ($udom, $uname, $regexp, $range are optional)
15230: 
15231: $range should be either an integer '100' (give me the first 100
15232:                                            matching records)
15233:               or be  two integers sperated by a - with no spaces
15234:                  '30-50' (give me the 30th through the 50th matching
15235:                           records)
15236: =item *
15237: 
15238: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15239: $store can be a scalar, an array reference, or if the amount to be 
15240: incremented is > 1, a hash reference.
15241: 
15242: ($udom and $uname are optional)
15243: 
15244: =item *
15245: 
15246: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15247: ($udom and $uname are optional)
15248: 
15249: =item *
15250: 
15251: cput($namespace,$storehash,$udom,$uname) : critical put
15252: ($udom and $uname are optional)
15253: 
15254: =item *
15255: 
15256: newput($namespace,$storehash,$udom,$uname) :
15257: 
15258: Attempts to store the items in the $storehash, but only if they don't
15259: currently exist, if this succeeds you can be certain that you have 
15260: successfully created a new key value pair in the $namespace db.
15261: 
15262: 
15263: Args:
15264:  $namespace: name of database to store values to
15265:  $storehash: hashref to store to the db
15266:  $udom: (optional) domain of user containing the db
15267:  $uname: (optional) name of user caontaining the db
15268: 
15269: Returns:
15270:  'ok' -> succeeded in storing all keys of $storehash
15271:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15272:                         least <key> already existed in the db (other
15273:                         requested keys may also already exist)
15274:  'error: <msg>' -> unable to tie the DB or other error occurred
15275:  'con_lost' -> unable to contact request server
15276:  'refused' -> action was not allowed by remote machine
15277: 
15278: 
15279: =item *
15280: 
15281: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15282: reference filled in from namesp (encrypts the return communication)
15283: ($udom and $uname are optional)
15284: 
15285: =item *
15286: 
15287: log($udom,$name,$home,$message) : write to permanent log for user; use
15288: critical subroutine
15289: 
15290: =item *
15291: 
15292: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15293: array reference filled in from namespace found in domain level on either
15294: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15295: 
15296: =item *
15297: 
15298: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15299: domain level either on specified domain server ($uhome) or primary domain 
15300: server ($udom and $uhome are optional)
15301: 
15302: =item * 
15303: 
15304: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15305: for: authentication, language, quotas, timezone, date locale, and portal URL in
15306: the target domain.
15307: 
15308: May also include additional key => value pairs for the following groups:
15309: 
15310: =over
15311: 
15312: =item
15313: disk quotas (MB allocated by default to portfolios and authoring spaces).
15314: 
15315: =over
15316: 
15317: =item defaultquota, authorquota
15318: 
15319: =back
15320: 
15321: =item
15322: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15323: portfolio for users).
15324: 
15325: =over
15326: 
15327: =item
15328: aboutme, blog, webdav, portfolio
15329: 
15330: =back
15331: 
15332: =item
15333: requestcourses: ability to request courses, and how requests are processed.
15334: 
15335: =over
15336: 
15337: =item
15338: official, unofficial, community, textbook, placement
15339: 
15340: =back
15341: 
15342: =item
15343: inststatus: types of institutional affiliation, and order in which they are displayed.
15344: 
15345: =over
15346: 
15347: =item
15348: inststatustypes, inststatusorder, inststatusguest
15349: 
15350: =back
15351: 
15352: =item
15353: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15354: for course's uploaded content.
15355: 
15356: =over
15357: 
15358: =item
15359: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15360: communityquota, textbookquota, placementquota
15361: 
15362: =back
15363: 
15364: =item
15365: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15366: on your servers.
15367: 
15368: =over
15369: 
15370: =item 
15371: remotesessions, hostedsessions
15372: 
15373: =back
15374: 
15375: =back
15376: 
15377: In cases where a domain coordinator has never used the "Set Domain Configuration"
15378: utility to create a configuration.db file on a domain's primary library server 
15379: only the following domain defaults: auth_def, auth_arg_def, lang_def
15380: -- corresponding values are authentication type (internal, krb4, krb5,
15381: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15382: will be available. Values are retrieved from cache (if current), unless the
15383: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15384: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15385: 
15386: Typical usage:
15387: 
15388: %domdefaults = &get_domain_defaults($target_domain);
15389: 
15390: =back
15391: 
15392: =head2 Network Status Functions
15393: 
15394: =over 4
15395: 
15396: =item *
15397: 
15398: dirlist() : return directory list based on URI (first arg).
15399: 
15400: Inputs: 1 required, 5 optional.
15401: 
15402: =over
15403: 
15404: =item 
15405: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15406: 
15407: =item
15408: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15409: 
15410: =item
15411: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15412: 
15413: =item
15414: $getpropath - boolean: 1 if prepend path using &propath(). 
15415: 
15416: =item
15417: $getuserdir - boolean: 1 if prepend path for "userfiles".
15418: 
15419: =item 
15420: $alternateRoot - path to prepend in place of path from $uri.
15421: 
15422: =back
15423: 
15424: Returns: Array of up to two items.
15425: 
15426: =over
15427: 
15428: a reference to an array of files/subdirectories
15429: 
15430: =over
15431: 
15432: Each element in the array of files/subdirectories is a & separated list of
15433: item name and the result of running stat on the item.  If dirlist was requested
15434: for a file instead of a directory, the item name will be ''. For a directory 
15435: listing, if the item is a metadata file, the element will end &N&M 
15436: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15437: default copyright set (1).  
15438: 
15439: =back
15440: 
15441: a scalar containing error condition (if encountered).
15442: 
15443: =over
15444: 
15445: =item 
15446: no_host (no homeserver identified for $username:$domain).
15447: 
15448: =item 
15449: no_such_host (server contacted for listing not identified as valid host).
15450: 
15451: =item 
15452: con_lost (connection to remote server failed).
15453: 
15454: =item 
15455: refused (invalid $username:$domain received on lond side).
15456: 
15457: =item 
15458: no_such_dir (directory at specified path on lond side does not exist). 
15459: 
15460: =item 
15461: empty (directory at specified path on lond side is empty).
15462: 
15463: =over
15464: 
15465: This is currently not encountered because the &ls3, &ls2, 
15466: &ls (_handler) routines on the lond side do not filter out
15467: . and .. from a directory listing. 
15468: 
15469: =back
15470: 
15471: =back
15472: 
15473: =back
15474: 
15475: =item *
15476: 
15477: spareserver() : find server with least workload from spare.tab
15478: 
15479: 
15480: =item *
15481: 
15482: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15483: if there is no corresponding loncapa host.
15484: 
15485: =back
15486: 
15487: 
15488: =head2 Apache Request
15489: 
15490: =over 4
15491: 
15492: =item *
15493: 
15494: ssi($url,%hash) : server side include, does a complete request cycle on url to
15495: localhost, posts hash
15496: 
15497: =back
15498: 
15499: =head2 Data to String to Data
15500: 
15501: =over 4
15502: 
15503: =item *
15504: 
15505: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15506: and '&' separators, supports elements that are arrayrefs and hashrefs
15507: 
15508: =item *
15509: 
15510: hashref2str($hashref) : convert a hashref into a string complete with
15511: escaping and '=' and '&' separators, supports elements that are
15512: arrayrefs and hashrefs
15513: 
15514: =item *
15515: 
15516: arrayref2str($arrayref) : convert an arrayref into a string complete
15517: with escaping and '&' separators, supports elements that are arrayrefs
15518: and hashrefs
15519: 
15520: =item *
15521: 
15522: str2hash($string) : convert string to hash using unescaping and
15523: splitting on '=' and '&', supports elements that are arrayrefs and
15524: hashrefs
15525: 
15526: =item *
15527: 
15528: str2array($string) : convert string to hash using unescaping and
15529: splitting on '&', supports elements that are arrayrefs and hashrefs
15530: 
15531: =back
15532: 
15533: =head2 Logging Routines
15534: 
15535: 
15536: These routines allow one to make log messages in the lonnet.log and
15537: lonnet.perm logfiles.
15538: 
15539: =over 4
15540: 
15541: =item *
15542: 
15543: logtouch() : make sure the logfile, lonnet.log, exists
15544: 
15545: =item *
15546: 
15547: logthis() : append message to the normal lonnet.log file, it gets
15548: preiodically rolled over and deleted.
15549: 
15550: =item *
15551: 
15552: logperm() : append a permanent message to lonnet.perm.log, this log
15553: file never gets deleted by any automated portion of the system, only
15554: messages of critical importance should go in here.
15555: 
15556: 
15557: =back
15558: 
15559: =head2 General File Helper Routines
15560: 
15561: =over 4
15562: 
15563: =item *
15564: 
15565: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15566: (a) files in /uploaded
15567:   (i) If a local copy of the file exists - 
15568:       compares modification date of local copy with last-modified date for 
15569:       definitive version stored on home server for course. If local copy is 
15570:       stale, requests a new version from the home server and stores it. 
15571:       If the original has been removed from the home server, then local copy 
15572:       is unlinked.
15573:   (ii) If local copy does not exist -
15574:       requests the file from the home server and stores it. 
15575:   
15576:   If $caller is 'uploadrep':  
15577:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15578:     for request for files originally uploaded via DOCS. 
15579:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15580:   
15581:   Otherwise:
15582:      This indicates a call from the content generation phase of the request.
15583:      -  returns the entire contents of the file or -1.
15584:      
15585: (b) files in /res
15586:    - returns the entire contents of a file or -1; 
15587:    it properly subscribes to and replicates the file if neccessary.
15588: 
15589: 
15590: =item *
15591: 
15592: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15593:                   reference
15594: 
15595: returns either a stat() list of data about the file or an empty list
15596: if the file doesn't exist or couldn't find out about it (connection
15597: problems or user unknown)
15598: 
15599: =item *
15600: 
15601: filelocation($dir,$file) : returns file system location of a file
15602: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15603: directory that relative $file lookups are to looked in ($dir of /a/dir
15604: and a file of ../bob will become /a/bob)
15605: 
15606: =item *
15607: 
15608: hreflocation($dir,$file) : returns file system location or a URL; same as
15609: filelocation except for hrefs
15610: 
15611: =item *
15612: 
15613: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15614: also removes beginning /home/httpd/html unless /priv/ follows it.
15615: 
15616: =back
15617: 
15618: =head2 Usererfile file routines (/uploaded*)
15619: 
15620: =over 4
15621: 
15622: =item *
15623: 
15624: userfileupload(): main rotine for putting a file in a user or course's
15625:                   filespace, arguments are,
15626: 
15627:  formname - required - this is the name of the element in $env where the
15628:            filename, and the contents of the file to create/modifed exist
15629:            the filename is in $env{'form.'.$formname.'.filename'} and the
15630:            contents of the file is located in $env{'form.'.$formname}
15631:  context - if coursedoc, store the file in the course of the active role
15632:              of the current user; 
15633:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15634:            if 'canceloverwrite': delete file in tmp/overwrites directory
15635:  subdir - required - subdirectory to put the file in under ../userfiles/
15636:          if undefined, it will be placed in "unknown"
15637: 
15638:  (This routine calls clean_filename() to remove any dangerous
15639:  characters from the filename, and then calls finuserfileupload() to
15640:  complete the transaction)
15641: 
15642:  returns either the url of the uploaded file (/uploaded/....) if successful
15643:  and /adm/notfound.html if unsuccessful
15644: 
15645: =item *
15646: 
15647: clean_filename(): routine for cleaing a filename up for storage in
15648:                  userfile space, argument is:
15649: 
15650:  filename - proposed filename
15651: 
15652: returns: the new clean filename
15653: 
15654: =item *
15655: 
15656: finishuserfileupload(): routine that creates and sends the file to
15657: userspace, probably shouldn't be called directly
15658: 
15659:   docuname: username or courseid of destination for the file
15660:   docudom: domain of user/course of destination for the file
15661:   formname: same as for userfileupload()
15662:   fname: filename (including subdirectories) for the file
15663:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15664:   allfiles: reference to hash used to store objects found by parser
15665:   codebase: reference to hash used for codebases of java objects found by parser
15666:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15667:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15668:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15669:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15670:   context: if 'overwrite', will move the uploaded file from its temporary location to
15671:             userfiles to facilitate overwriting a previously uploaded file with same name.
15672:   mimetype: reference to scalar to accommodate mime type determined
15673:             from File::MMagic if $parser = parse.
15674: 
15675:  returns either the url of the uploaded file (/uploaded/....) if successful
15676:  and /adm/notfound.html if unsuccessful (or an error message if context 
15677:  was 'overwrite').
15678:  
15679: 
15680: =item *
15681: 
15682: renameuserfile(): renames an existing userfile to a new name
15683: 
15684:   Args:
15685:    docuname: username or courseid of destination for the file
15686:    docudom: domain of user/course of destination for the file
15687:    old: current file name (including any subdirs under userfiles)
15688:    new: desired file name (including any subdirs under userfiles)
15689: 
15690: =item *
15691: 
15692: mkdiruserfile(): creates a directory is a userfiles dir
15693: 
15694:   Args:
15695:    docuname: username or courseid of destination for the file
15696:    docudom: domain of user/course of destination for the file
15697:    dir: dir to create (including any subdirs under userfiles)
15698: 
15699: =item *
15700: 
15701: removeuserfile(): removes a file that exists in userfiles
15702: 
15703:   Args:
15704:    docuname: username or courseid of destination for the file
15705:    docudom: domain of user/course of destination for the file
15706:    fname: filname to delete (including any subdirs under userfiles)
15707: 
15708: =item *
15709: 
15710: removeuploadedurl(): convience function for removeuserfile()
15711: 
15712:   Args:
15713:    url:  a full /uploaded/... url to delete
15714: 
15715: =item * 
15716: 
15717: get_portfile_permissions():
15718:   Args:
15719:     domain: domain of user or course contain the portfolio files
15720:     user: name of user or num of course contain the portfolio files
15721:   Returns:
15722:     hashref of a dump of the proper file_permissions.db
15723:    
15724: 
15725: =item * 
15726: 
15727: get_access_controls():
15728: 
15729: Args:
15730:   current_permissions: the hash ref returned from get_portfile_permissions()
15731:   group: (optional) the group you want the files associated with
15732:   file: (optional) the file you want access info on
15733: 
15734: Returns:
15735:     a hash (keys are file names) of hashes containing
15736:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15737:         values are XML containing access control settings (see below) 
15738: 
15739: Internal notes:
15740: 
15741:  access controls are stored in file_permissions.db as key=value pairs.
15742:     key -> path to file/file_name\0uniqueID:scope_end_start
15743:         where scope -> public,guest,course,group,domains or users.
15744:               end -> UNIX time for end of access (0 -> no end date)
15745:               start -> UNIX time for start of access
15746: 
15747:     value -> XML description of access control
15748:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15749:             <start></start>
15750:             <end></end>
15751: 
15752:             <password></password>  for scope type = guest
15753: 
15754:             <domain></domain>     for scope type = course or group
15755:             <number></number>
15756:             <roles id="">
15757:              <role></role>
15758:              <access></access>
15759:              <section></section>
15760:              <group></group>
15761:             </roles>
15762: 
15763:             <dom></dom>         for scope type = domains
15764: 
15765:             <users>             for scope type = users
15766:              <user>
15767:               <uname></uname>
15768:               <udom></udom>
15769:              </user>
15770:             </users>
15771:            </scope> 
15772:               
15773:  Access data is also aggregated for each file in an additional key=value pair:
15774:  key -> path to file/file_name\0accesscontrol 
15775:  value -> reference to hash
15776:           hash contains key = value pairs
15777:           where key = uniqueID:scope_end_start
15778:                 value = UNIX time record was last updated
15779: 
15780:           Used to improve speed of look-ups of access controls for each file.  
15781:  
15782:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15783: 
15784: =item *
15785: 
15786: modify_access_controls():
15787: 
15788: Modifies access controls for a portfolio file
15789: Args
15790: 1. file name
15791: 2. reference to hash of required changes,
15792: 3. domain
15793: 4. username
15794:   where domain,username are the domain of the portfolio owner 
15795:   (either a user or a course) 
15796: 
15797: Returns:
15798: 1. result of additions or updates ('ok' or 'error', with error message). 
15799: 2. result of deletions ('ok' or 'error', with error message).
15800: 3. reference to hash of any new or updated access controls.
15801: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15802:    key = integer (inbound ID)
15803:    value = uniqueID
15804: 
15805: =item *
15806: 
15807: get_timebased_id():
15808: 
15809: Attempts to get a unique timestamp-based suffix for use with items added to a 
15810: course via the Course Editor (e.g., folders, composite pages, 
15811: group bulletin boards).
15812: 
15813: Args: (first three required; six others optional)
15814: 
15815: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15816:    docssequence, or name of group
15817: 
15818: 2. keyid (alphanumeric): name of temporary locking key in hash,
15819:    e.g., num, boardids
15820: 
15821: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15822:    file will be named nohist_namespace.db
15823: 
15824: 4. cdom: domain of course; default is current course domain from %env
15825: 
15826: 5. cnum: course number; default is current course number from %env
15827: 
15828: 6. idtype: set to concat if an additional digit is to be appended to the 
15829:    unix timestamp to form the suffix, if the plain timestamp is already
15830:    in use.  Default is to not do this, but simply increment the unix 
15831:    timestamp by 1 until a unique key is obtained.
15832: 
15833: 7. who: holder of locking key; defaults to user:domain for user.
15834: 
15835: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15836:    retrying); default is 3.
15837: 
15838: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15839: 
15840: Returns:
15841: 
15842: 1. suffix obtained (numeric)
15843: 
15844: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15845: 
15846: 3. error: contains (localized) error message if an error occurred.
15847: 
15848: 
15849: =back
15850: 
15851: =head2 HTTP Helper Routines
15852: 
15853: =over 4
15854: 
15855: =item *
15856: 
15857: escape() : unpack non-word characters into CGI-compatible hex codes
15858: 
15859: =item *
15860: 
15861: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15862: 
15863: =back
15864: 
15865: =head1 PRIVATE SUBROUTINES
15866: 
15867: =head2 Underlying communication routines (Shouldn't call)
15868: 
15869: =over 4
15870: 
15871: =item *
15872: 
15873: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15874: 
15875: =item *
15876: 
15877: reply() : uses subreply to send a message to remote machine, logs all failures
15878: 
15879: =item *
15880: 
15881: critical() : passes a critical message to another server; if cannot
15882: get through then place message in connection buffer directory and
15883: returns con_delayed, if incapable of saving message, returns
15884: con_failed
15885: 
15886: =item *
15887: 
15888: reconlonc() : tries to reconnect lonc client processes.
15889: 
15890: =back
15891: 
15892: =head2 Resource Access Logging
15893: 
15894: =over 4
15895: 
15896: =item *
15897: 
15898: flushcourselogs() : flush (save) buffer logs and access logs
15899: 
15900: =item *
15901: 
15902: courselog($what) : save message for course in hash
15903: 
15904: =item *
15905: 
15906: courseacclog($what) : save message for course using &courselog().  Perform
15907: special processing for specific resource types (problems, exams, quizzes, etc).
15908: 
15909: =item *
15910: 
15911: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15912: as a PerlChildExitHandler
15913: 
15914: =back
15915: 
15916: =head2 Other
15917: 
15918: =over 4
15919: 
15920: =item *
15921: 
15922: symblist($mapname,%newhash) : update symbolic storage links
15923: 
15924: =back
15925: 
15926: =cut
15927: 

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