File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1390: download - view: text, annotated - select for diffs
Sun Nov 25 02:27:04 2018 UTC (5 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Eliminate double count when computing userload for servers with SSL.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1390 2018/11/25 02:27:04 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$hostname,$context) = @_;
  234:     return if ($lonhost eq '');
  235:     if ($hostname eq '') {
  236:         $hostname = &hostname($lonhost);
  237:     }
  238:     return if ($hostname eq '');
  239:     my ($rep,$uselocal);
  240:     if ($context eq 'install') {
  241:         $uselocal = 1;
  242:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  243:         $uselocal = 1;
  244:     }
  245:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  246:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  247:         if ($distro eq '') {
  248:             $uselocal = 0;
  249:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  250:             if ($1 < 6) {
  251:                 $uselocal = 0;
  252:             }
  253:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  254:             if ($1 < 12) {
  255:                 $uselocal = 0;
  256:             }
  257:         }
  258:     }
  259:     if ($uselocal) {
  260:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  261:     } else {
  262:         $rep=&reply('servercerts',$lonhost);
  263:     }
  264:     my ($result,%returnhash);
  265:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  266:         ($rep eq 'unknown_cmd')) {
  267:         $result = $rep;
  268:     } else {
  269:         $result = 'ok';
  270:         my @pairs=split(/\&/,$rep);
  271:         foreach my $item (@pairs) {
  272:             my ($key,$value)=split(/=/,$item,2);
  273:             my $what = &unescape($key);
  274:             $returnhash{$what}=&thaw_unescape($value);
  275:         }
  276:     }
  277:     return ($result,\%returnhash);
  278: }
  279: 
  280: sub get_server_loncaparev {
  281:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  282:     if (defined($lonhost)) {
  283:         if (!defined(&hostname($lonhost))) {
  284:             undef($lonhost);
  285:         }
  286:     }
  287:     if (!defined($lonhost)) {
  288:         if (defined(&domain($dom,'primary'))) {
  289:             $lonhost=&domain($dom,'primary');
  290:             if ($lonhost eq 'no_host') {
  291:                 undef($lonhost);
  292:             }
  293:         }
  294:     }
  295:     if (defined($lonhost)) {
  296:         my $cachetime = 12*3600;
  297:         if (!$ignore_cache) {
  298:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  299:             if (defined($cached)) {
  300:                 return $loncaparev;
  301:             }
  302:         }
  303:         my ($answer,$loncaparev);
  304:         my @ids=&current_machine_ids();
  305:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  306:             $answer = $perlvar{'lonVersion'};
  307:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  308:                 $loncaparev = $1;
  309:             }
  310:         } else {
  311:             $answer = &reply('serverloncaparev',$lonhost);
  312:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  313:                 if ($caller eq 'loncron') {
  314:                     my $protocol = $protocol{$lonhost};
  315:                     $protocol = 'http' if ($protocol ne 'https');
  316:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  317:                     my $request=new HTTP::Request('GET',$url);
  318:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  319:                     unless ($response->is_error()) {
  320:                         my $content = $response->content;
  321:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  322:                             $loncaparev = $1;
  323:                         }
  324:                     }
  325:                 } else {
  326:                     $loncaparev = $loncaparevs{$lonhost};
  327:                 }
  328:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  329:                 $loncaparev = $1;
  330:             }
  331:         }
  332:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  333:     }
  334: }
  335: 
  336: sub get_server_homeID {
  337:     my ($hostname,$ignore_cache,$caller) = @_;
  338:     unless ($ignore_cache) {
  339:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  340:         if (defined($cached)) {
  341:             return $serverhomeID;
  342:         }
  343:     }
  344:     my $cachetime = 12*3600;
  345:     my $serverhomeID;
  346:     if ($caller eq 'loncron') { 
  347:         my @machine_ids = &machine_ids($hostname);
  348:         foreach my $id (@machine_ids) {
  349:             my $response = &reply('serverhomeID',$id);
  350:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  351:                 $serverhomeID = $response;
  352:                 last;
  353:             }
  354:         }
  355:         if ($serverhomeID eq '') {
  356:             $serverhomeID = $machine_ids[-1];
  357:         }
  358:     } else {
  359:         $serverhomeID = $serverhomeIDs{$hostname};
  360:     }
  361:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  362: }
  363: 
  364: sub get_remote_globals {
  365:     my ($lonhost,$whathash,$ignore_cache) = @_;
  366:     my ($result,%returnhash,%whatneeded);
  367:     if (ref($whathash) eq 'HASH') {
  368:         foreach my $what (sort(keys(%{$whathash}))) {
  369:             my $hashid = $lonhost.'-'.$what;
  370:             my ($response,$cached);
  371:             unless ($ignore_cache) {
  372:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  373:             }
  374:             if (defined($cached)) {
  375:                 $returnhash{$what} = $response;
  376:             } else {
  377:                 $whatneeded{$what} = 1;
  378:             }
  379:         }
  380:         if (keys(%whatneeded) == 0) {
  381:             $result = 'ok';
  382:         } else {
  383:             my $requested = &freeze_escape(\%whatneeded);
  384:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  385:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  386:                 ($rep eq 'unknown_cmd')) {
  387:                 $result = $rep;
  388:             } else {
  389:                 $result = 'ok';
  390:                 my @pairs=split(/\&/,$rep);
  391:                 foreach my $item (@pairs) {
  392:                     my ($key,$value)=split(/=/,$item,2);
  393:                     my $what = &unescape($key);
  394:                     my $hashid = $lonhost.'-'.$what;
  395:                     $returnhash{$what}=&thaw_unescape($value);
  396:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  397:                 }
  398:             }
  399:         }
  400:     }
  401:     return ($result,\%returnhash);
  402: }
  403: 
  404: sub remote_devalidate_cache {
  405:     my ($lonhost,$cachekeys) = @_;
  406:     my $items;
  407:     return unless (ref($cachekeys) eq 'ARRAY');
  408:     my $cachestr = join('&',@{$cachekeys});
  409:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  410:     return $response;
  411: }
  412: 
  413: # -------------------------------------------------- Non-critical communication
  414: sub subreply {
  415:     my ($cmd,$server)=@_;
  416:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  417:     #
  418:     #  With loncnew process trimming, there's a timing hole between lonc server
  419:     #  process exit and the master server picking up the listen on the AF_UNIX
  420:     #  socket.  In that time interval, a lock file will exist:
  421: 
  422:     my $lockfile=$peerfile.".lock";
  423:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  424: 	sleep(0.1);
  425:     }
  426:     # At this point, either a loncnew parent is listening or an old lonc
  427:     # or loncnew child is listening so we can connect or everything's dead.
  428:     #
  429:     #   We'll give the connection a few tries before abandoning it.  If
  430:     #   connection is not possible, we'll con_lost back to the client.
  431:     #   
  432:     my $client;
  433:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  434: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  435: 				      Type    => SOCK_STREAM,
  436: 				      Timeout => 10);
  437: 	if ($client) {
  438: 	    last;		# Connected!
  439: 	} else {
  440: 	    &create_connection(&hostname($server),$server);
  441: 	}
  442:         sleep(0.1);	# Try again later if failed connection.
  443:     }
  444:     my $answer;
  445:     if ($client) {
  446: 	print $client "sethost:$server:$cmd\n";
  447: 	$answer=<$client>;
  448: 	if (!$answer) { $answer="con_lost"; }
  449: 	chomp($answer);
  450:     } else {
  451: 	$answer = 'con_lost';	# Failed connection.
  452:     }
  453:     return $answer;
  454: }
  455: 
  456: sub reply {
  457:     my ($cmd,$server)=@_;
  458:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  459:     my $answer=subreply($cmd,$server);
  460:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  461:        &logthis("<font color=\"blue\">WARNING:".
  462:                 " $cmd to $server returned $answer</font>");
  463:     }
  464:     return $answer;
  465: }
  466: 
  467: # ----------------------------------------------------------- Send USR1 to lonc
  468: 
  469: sub reconlonc {
  470:     my ($lonid) = @_;
  471:     if ($lonid) {
  472:         my $hostname = &hostname($lonid);
  473: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  474: 	if ($hostname && -e $peerfile) {
  475: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  476: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  477: 					     Type    => SOCK_STREAM,
  478: 					     Timeout => 10);
  479: 	    if ($client) {
  480: 		print $client ("reset_retries\n");
  481: 		my $answer=<$client>;
  482: 		#reset just this one.
  483: 	    }
  484: 	}
  485: 	return;
  486:     }
  487: 
  488:     &logthis("Trying to reconnect lonc");
  489:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  490:     if (open(my $fh,"<",$loncfile)) {
  491: 	my $loncpid=<$fh>;
  492:         chomp($loncpid);
  493:         if (kill 0 => $loncpid) {
  494: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  495:             kill USR1 => $loncpid;
  496:             sleep 1;
  497:         } else {
  498: 	    &logthis(
  499:                "<font color=\"blue\">WARNING:".
  500:                " lonc at pid $loncpid not responding, giving up</font>");
  501:         }
  502:     } else {
  503: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  504:     }
  505: }
  506: 
  507: # ------------------------------------------------------ Critical communication
  508: 
  509: sub critical {
  510:     my ($cmd,$server)=@_;
  511:     unless (&hostname($server)) {
  512:         &logthis("<font color=\"blue\">WARNING:".
  513:                " Critical message to unknown server ($server)</font>");
  514:         return 'no_such_host';
  515:     }
  516:     my $answer=reply($cmd,$server);
  517:     if ($answer eq 'con_lost') {
  518: 	&reconlonc($server);
  519: 	my $answer=reply($cmd,$server);
  520:         if ($answer eq 'con_lost') {
  521:             my $now=time;
  522:             my $middlename=$cmd;
  523:             $middlename=substr($middlename,0,16);
  524:             $middlename=~s/\W//g;
  525:             my $dfilename=
  526:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  527:             $dumpcount++;
  528:             {
  529: 		my $dfh;
  530: 		if (open($dfh,">",$dfilename)) {
  531: 		    print $dfh "$cmd\n"; 
  532: 		    close($dfh);
  533: 		}
  534:             }
  535:             sleep 1;
  536:             my $wcmd='';
  537:             {
  538: 		my $dfh;
  539: 		if (open($dfh,"<",$dfilename)) {
  540: 		    $wcmd=<$dfh>; 
  541: 		    close($dfh);
  542: 		}
  543:             }
  544:             chomp($wcmd);
  545:             if ($wcmd eq $cmd) {
  546: 		&logthis("<font color=\"blue\">WARNING: ".
  547:                          "Connection buffer $dfilename: $cmd</font>");
  548:                 &logperm("D:$server:$cmd");
  549: 	        return 'con_delayed';
  550:             } else {
  551:                 &logthis("<font color=\"red\">CRITICAL:"
  552:                         ." Critical connection failed: $server $cmd</font>");
  553:                 &logperm("F:$server:$cmd");
  554:                 return 'con_failed';
  555:             }
  556:         }
  557:     }
  558:     return $answer;
  559: }
  560: 
  561: # ------------------------------------------- check if return value is an error
  562: 
  563: sub error {
  564:     my ($result) = @_;
  565:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  566: 	if ($2 == 2) { return undef; }
  567: 	return $1;
  568:     }
  569:     return undef;
  570: }
  571: 
  572: sub convert_and_load_session_env {
  573:     my ($lonidsdir,$handle)=@_;
  574:     my @profile;
  575:     {
  576: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  577: 	if (!$opened) {
  578: 	    return 0;
  579: 	}
  580: 	flock($idf,LOCK_SH);
  581: 	@profile=<$idf>;
  582: 	close($idf);
  583:     }
  584:     my %temp_env;
  585:     foreach my $line (@profile) {
  586: 	if ($line !~ m/=/) {
  587: 	    return 0;
  588: 	}
  589: 	chomp($line);
  590: 	my ($envname,$envvalue)=split(/=/,$line,2);
  591: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  592:     }
  593:     unlink("$lonidsdir/$handle.id");
  594:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  595: 	    0640)) {
  596: 	%disk_env = %temp_env;
  597: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  598: 	untie(%disk_env);
  599:     }
  600:     return 1;
  601: }
  602: 
  603: # ------------------------------------------- Transfer profile into environment
  604: my $env_loaded;
  605: sub transfer_profile_to_env {
  606:     my ($lonidsdir,$handle,$force_transfer) = @_;
  607:     if (!$force_transfer && $env_loaded) { return; } 
  608: 
  609:     if (!defined($lonidsdir)) {
  610: 	$lonidsdir = $perlvar{'lonIDsDir'};
  611:     }
  612:     if (!defined($handle)) {
  613:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  614:     }
  615: 
  616:     my $convert;
  617:     {
  618:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  619: 	if (!$opened) {
  620: 	    return;
  621: 	}
  622: 	flock($idf,LOCK_SH);
  623: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  624: 		&GDBM_READER(),0640)) {
  625: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  626: 	    untie(%disk_env);
  627: 	} else {
  628: 	    $convert = 1;
  629: 	}
  630:     }
  631:     if ($convert) {
  632: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  633: 	    &logthis("Failed to load session, or convert session.");
  634: 	}
  635:     }
  636: 
  637:     my %remove;
  638:     while ( my $envname = each(%env) ) {
  639:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  640:             if ($time < time-300) {
  641:                 $remove{$key}++;
  642:             }
  643:         }
  644:     }
  645: 
  646:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  647:     $env_loaded=1;
  648:     foreach my $expired_key (keys(%remove)) {
  649:         &delenv($expired_key);
  650:     }
  651: }
  652: 
  653: # ---------------------------------------------------- Check for valid session 
  654: sub check_for_valid_session {
  655:     my ($r,$name,$userhashref,$domref) = @_;
  656:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  657:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  658:     if ($name eq 'lonDAV') {
  659:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  660:     } else {
  661:         $lonidsdir=$r->dir_config('lonIDsDir');
  662:         if ($name eq '') {
  663:             $name = 'lonID';
  664:         }
  665:     }
  666:     if ($name eq 'lonID') {
  667:         $secure = 'lonSID';
  668:         $linkname = 'lonLinkID';
  669:         $pubname = 'lonPubID';
  670:         if (exists($cookies{$secure})) {
  671:             $lonid=$cookies{$secure};
  672:         } elsif (exists($cookies{$name})) {
  673:             $lonid=$cookies{$name};
  674:         } elsif (exists($cookies{$linkname})) {
  675:             $lonid=$cookies{$linkname};
  676:         } elsif (exists($cookies{$pubname})) {
  677:             $lonid=$cookies{$pubname};
  678:         }
  679:     } else {
  680:         $lonid=$cookies{$name};
  681:     }
  682:     return undef if (!$lonid);
  683: 
  684:     my $handle=&LONCAPA::clean_handle($lonid->value);
  685:     if (-l "$lonidsdir/$handle.id") {
  686:         my $link = readlink("$lonidsdir/$handle.id");
  687:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  688:             $handle = $1;
  689:         }
  690:     }
  691:     if (!-e "$lonidsdir/$handle.id") {
  692:         if ((ref($domref)) && ($name eq 'lonID') && 
  693:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  694:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  695:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  696:                 $$domref = $possudom;
  697:             }
  698:         }
  699:         return undef;
  700:     }
  701: 
  702:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  703:     return undef if (!$opened);
  704: 
  705:     flock($idf,LOCK_SH);
  706:     my %disk_env;
  707:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  708: 	    &GDBM_READER(),0640)) {
  709: 	return undef;	
  710:     }
  711: 
  712:     if (!defined($disk_env{'user.name'})
  713: 	|| !defined($disk_env{'user.domain'})) {
  714: 	return undef;
  715:     }
  716: 
  717:     if (ref($userhashref) eq 'HASH') {
  718:         $userhashref->{'name'} = $disk_env{'user.name'};
  719:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  720:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  721:         if ($userhashref->{'lti'}) {
  722:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  723:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  724:         }
  725:     }
  726: 
  727:     return $handle;
  728: }
  729: 
  730: sub timed_flock {
  731:     my ($file,$lock_type) = @_;
  732:     my $failed=0;
  733:     eval {
  734: 	local $SIG{__DIE__}='DEFAULT';
  735: 	local $SIG{ALRM}=sub {
  736: 	    $failed=1;
  737: 	    die("failed lock");
  738: 	};
  739: 	alarm(13);
  740: 	flock($file,$lock_type);
  741: 	alarm(0);
  742:     };
  743:     if ($failed) {
  744: 	return undef;
  745:     } else {
  746: 	return 1;
  747:     }
  748: }
  749: 
  750: # ---------------------------------------------------------- Append Environment
  751: 
  752: sub appenv {
  753:     my ($newenv,$roles) = @_;
  754:     if (ref($newenv) eq 'HASH') {
  755:         foreach my $key (keys(%{$newenv})) {
  756:             my $refused = 0;
  757: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  758:                 $refused = 1;
  759:                 if (ref($roles) eq 'ARRAY') {
  760:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  761:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  762:                         $refused = 0;
  763:                     }
  764:                 }
  765:             }
  766:             if ($refused) {
  767:                 &logthis("<font color=\"blue\">WARNING: ".
  768:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  769:                          .'</font>');
  770: 	        delete($newenv->{$key});
  771:             } else {
  772:                 $env{$key}=$newenv->{$key};
  773:             }
  774:         }
  775:         my $lonids = $perlvar{'lonIDsDir'};
  776:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  777:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  778:             if ($opened
  779: 	        && &timed_flock($env_file,LOCK_EX)
  780: 	        &&
  781: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  782: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  783: 	        while (my ($key,$value) = each(%{$newenv})) {
  784: 	            $disk_env{$key} = $value;
  785: 	        }
  786: 	        untie(%disk_env);
  787:             }
  788:         }
  789:     }
  790:     return 'ok';
  791: }
  792: # ----------------------------------------------------- Delete from Environment
  793: 
  794: sub delenv {
  795:     my ($delthis,$regexp,$roles) = @_;
  796:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  797:         my $refused = 1;
  798:         if (ref($roles) eq 'ARRAY') {
  799:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  800:             if (grep(/^\Q$role\E$/,@{$roles})) {
  801:                 $refused = 0;
  802:             }
  803:         }
  804:         if ($refused) {
  805:             &logthis("<font color=\"blue\">WARNING: ".
  806:                      "Attempt to delete from environment ".$delthis);
  807:             return 'error';
  808:         }
  809:     }
  810:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  811:     if ($opened
  812: 	&& &timed_flock($env_file,LOCK_EX)
  813: 	&&
  814: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  815: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  816: 	foreach my $key (keys(%disk_env)) {
  817: 	    if ($regexp) {
  818:                 if ($key=~/^$delthis/) {
  819:                     delete($env{$key});
  820:                     delete($disk_env{$key});
  821:                 } 
  822:             } else {
  823:                 if ($key=~/^\Q$delthis\E/) {
  824: 		    delete($env{$key});
  825: 		    delete($disk_env{$key});
  826: 	        }
  827:             }
  828: 	}
  829: 	untie(%disk_env);
  830:     }
  831:     return 'ok';
  832: }
  833: 
  834: sub get_env_multiple {
  835:     my ($name) = @_;
  836:     my @values;
  837:     if (defined($env{$name})) {
  838:         # exists is it an array
  839:         if (ref($env{$name})) {
  840:             @values=@{ $env{$name} };
  841:         } else {
  842:             $values[0]=$env{$name};
  843:         }
  844:     }
  845:     return(@values);
  846: }
  847: 
  848: # ------------------------------------------------------------------- Locking
  849: 
  850: sub set_lock {
  851:     my ($text)=@_;
  852:     $locknum++;
  853:     my $id=$$.'-'.$locknum;
  854:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  855:              'session.lock.'.$id => $text});
  856:     return $id;
  857: }
  858: 
  859: sub get_locks {
  860:     my $num=0;
  861:     my %texts=();
  862:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  863:        if ($lock=~/\w/) {
  864:           $num++;
  865:           $texts{$lock}=$env{'session.lock.'.$lock};
  866:        }
  867:    }
  868:    return ($num,%texts);
  869: }
  870: 
  871: sub remove_lock {
  872:     my ($id)=@_;
  873:     my $newlocks='';
  874:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  875:        if (($lock=~/\w/) && ($lock ne $id)) {
  876:           $newlocks.=','.$lock;
  877:        }
  878:     }
  879:     &appenv({'session.locks' => $newlocks});
  880:     &delenv('session.lock.'.$id);
  881: }
  882: 
  883: sub remove_all_locks {
  884:     my $activelocks=$env{'session.locks'};
  885:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  886:        if ($lock=~/\w/) {
  887:           &remove_lock($lock);
  888:        }
  889:     }
  890: }
  891: 
  892: 
  893: # ------------------------------------------ Find out current server userload
  894: sub userload {
  895:     my $numusers=0;
  896:     {
  897: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  898: 	my $filename;
  899: 	my $curtime=time;
  900: 	while ($filename=readdir(LONIDS)) {
  901: 	    next if ($filename eq '.' || $filename eq '..');
  902: 	    next if ($filename =~ /publicuser_\d+\.id/);
  903:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  904: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  905: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  906: 	}
  907: 	closedir(LONIDS);
  908:     }
  909:     my $userloadpercent=0;
  910:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  911:     if ($maxuserload) {
  912: 	$userloadpercent=100*$numusers/$maxuserload;
  913:     }
  914:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  915:     return $userloadpercent;
  916: }
  917: 
  918: # ------------------------------ Find server with least workload from spare.tab
  919: 
  920: sub spareserver {
  921:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  922:     my $spare_server;
  923:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  924:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  925:                                                      :  $userloadpercent;
  926:     my ($uint_dom,$remotesessions);
  927:     if (($udom ne '') && (&domain($udom) ne '')) {
  928:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  929:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  930:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  931:         $remotesessions = $udomdefaults{'remotesessions'};
  932:     }
  933:     my $spareshash = &this_host_spares($udom);
  934:     if (ref($spareshash) eq 'HASH') {
  935:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  936:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  937:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  938:                                              $try_server));
  939: 	        ($spare_server, $lowest_load) =
  940: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  941:             }
  942:         }
  943: 
  944:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  945: 
  946:         if (!$found_server) {
  947:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  948: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  949:                     next unless (&spare_can_host($udom,$uint_dom,
  950:                                                  $remotesessions,$try_server));
  951: 	            ($spare_server, $lowest_load) =
  952: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  953:                 }
  954: 	    }
  955:         }
  956:     }
  957: 
  958:     if (!$want_server_name) {
  959:         my $protocol = 'http';
  960:         if ($protocol{$spare_server} eq 'https') {
  961:             $protocol = $protocol{$spare_server};
  962:         }
  963:         if (defined($spare_server)) {
  964:             my $hostname = &hostname($spare_server);
  965:             if (defined($hostname)) {
  966: 	        $spare_server = $protocol.'://'.$hostname;
  967:             }
  968:         }
  969:     }
  970:     return $spare_server;
  971: }
  972: 
  973: sub compare_server_load {
  974:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  975: 
  976:     if ($required) {
  977:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  978:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  979:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  980:         if (($major eq '' && $minor eq '') ||
  981:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  982:             return ($spare_server,$lowest_load);
  983:         }
  984:     }
  985: 
  986:     my $loadans     = &reply('load',    $try_server);
  987:     my $userloadans = &reply('userload',$try_server);
  988: 
  989:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  990: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  991:     }
  992: 
  993:     my $load;
  994:     if ($loadans =~ /\d/) {
  995: 	if ($userloadans =~ /\d/) {
  996: 	    #both are numbers, pick the bigger one
  997: 	    $load = ($loadans > $userloadans) ? $loadans 
  998: 		                              : $userloadans;
  999: 	} else {
 1000: 	    $load = $loadans;
 1001: 	}
 1002:     } else {
 1003: 	$load = $userloadans;
 1004:     }
 1005: 
 1006:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1007: 	$spare_server = $try_server;
 1008: 	$lowest_load  = $load;
 1009:     }
 1010:     return ($spare_server,$lowest_load);
 1011: }
 1012: 
 1013: # --------------------------- ask offload servers if user already has a session
 1014: sub find_existing_session {
 1015:     my ($udom,$uname) = @_;
 1016:     my $spareshash = &this_host_spares($udom);
 1017:     if (ref($spareshash) eq 'HASH') {
 1018:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1019:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1020:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1021:             }
 1022:         }
 1023:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1024:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1025:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1026:             }
 1027:         }
 1028:     }
 1029:     return;
 1030: }
 1031: 
 1032: # check if user's browser sent load balancer cookie and server still has session
 1033: # and is not overloaded.
 1034: sub check_for_balancer_cookie {
 1035:     my ($r,$update_mtime) = @_;
 1036:     my ($otherserver,$cookie);
 1037:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1038:     if (exists($cookies{'balanceID'})) {
 1039:         my $balid = $cookies{'balanceID'};
 1040:         $cookie=&LONCAPA::clean_handle($balid->value);
 1041:         my $balancedir=$r->dir_config('lonBalanceDir');
 1042:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1043:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1044:                 my ($possudom,$possuname) = ($1,$2);
 1045:                 my $has_session = 0;
 1046:                 if ((&domain($possudom) ne '') &&
 1047:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1048:                     my $try_server;
 1049:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1050:                     if ($opened) {
 1051:                         flock($idf,LOCK_SH);
 1052:                         while (my $line = <$idf>) {
 1053:                             chomp($line);
 1054:                             if (&hostname($line) ne '') {
 1055:                                 $try_server = $line;
 1056:                                 last;
 1057:                             }
 1058:                         }
 1059:                         close($idf);
 1060:                         if (($try_server) &&
 1061:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1062:                             my $lowest_load = 30000;
 1063:                             ($otherserver,$lowest_load) =
 1064:                                 &compare_server_load($try_server,undef,$lowest_load);
 1065:                             if ($otherserver ne '' && $lowest_load < 100) {
 1066:                                 $has_session = 1;
 1067:                             } else {
 1068:                                 undef($otherserver);
 1069:                             }
 1070:                         }
 1071:                     }
 1072:                 }
 1073:                 if ($has_session) {
 1074:                     if ($update_mtime) {
 1075:                         my $atime = my $mtime = time;
 1076:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1077:                     }
 1078:                 } else {
 1079:                     unlink("$balancedir/$cookie.id");
 1080:                 }
 1081:             }
 1082:         }
 1083:     }
 1084:     return ($otherserver,$cookie);
 1085: }
 1086: 
 1087: sub delbalcookie {
 1088:     my ($cookie,$balancer) =@_;
 1089:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1090:         my ($udom,$uname) = ($1,$2);
 1091:         my $uprimary_id = &domain($udom,'primary');
 1092:         my $uintdom = &internet_dom($uprimary_id);
 1093:         my $intdom = &internet_dom($balancer);
 1094:         my $serverhomedom = &host_domain($balancer);
 1095:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1096:             return &reply("delbalcookie:$cookie",$balancer);
 1097:         }
 1098:     }
 1099: }
 1100: 
 1101: # -------------------------------- ask if server already has a session for user
 1102: sub has_user_session {
 1103:     my ($lonid,$udom,$uname) = @_;
 1104:     my $result = &reply(join(':','userhassession',
 1105: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1106:     return 1 if ($result eq 'ok');
 1107: 
 1108:     return 0;
 1109: }
 1110: 
 1111: # --------- determine least loaded server in a user's domain which allows login
 1112: 
 1113: sub choose_server {
 1114:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1115:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1116:     my %servers = &get_servers($udom);
 1117:     my $lowest_load = 30000;
 1118:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1119:     if ($skiploadbal) {
 1120:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1121:         unless (defined($cached)) {
 1122:             my $cachetime = 60*60*24;
 1123:             my %domconfig =
 1124:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1125:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1126:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1127:                                            $cachetime);
 1128:             }
 1129:         }
 1130:     }
 1131:     foreach my $lonhost (keys(%servers)) {
 1132:         if ($skiploadbal) {
 1133:             if (ref($balancers) eq 'HASH') {
 1134:                 next if (exists($balancers->{$lonhost}));
 1135:             }
 1136:         }
 1137:         my $loginvia;
 1138:         if ($checkloginvia) {
 1139:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1140:             if ($loginvia) {
 1141:                 my ($server,$path) = split(/:/,$loginvia);
 1142:                 ($login_host, $lowest_load) =
 1143:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1144:                 if ($login_host eq $server) {
 1145:                     $portal_path = $path;
 1146:                     $isredirect = 1;
 1147:                 }
 1148:             } else {
 1149:                 ($login_host, $lowest_load) =
 1150:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1151:                 if ($login_host eq $lonhost) {
 1152:                     $portal_path = '';
 1153:                     $isredirect = ''; 
 1154:                 }
 1155:             }
 1156:         } else {
 1157:             ($login_host, $lowest_load) =
 1158:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1159:         }
 1160:     }
 1161:     if ($login_host ne '') {
 1162:         $hostname = &hostname($login_host);
 1163:     }
 1164:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1165: }
 1166: 
 1167: # --------------------------------------------- Try to change a user's password
 1168: 
 1169: sub changepass {
 1170:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1171:     $currentpass = &escape($currentpass);
 1172:     $newpass     = &escape($newpass);
 1173:     my $lonhost = $perlvar{'lonHostID'};
 1174:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1175: 		       $server);
 1176:     if (! $answer) {
 1177: 	&logthis("No reply on password change request to $server ".
 1178: 		 "by $uname in domain $udom.");
 1179:     } elsif ($answer =~ "^ok") {
 1180:         &logthis("$uname in $udom successfully changed their password ".
 1181: 		 "on $server.");
 1182:     } elsif ($answer =~ "^pwchange_failure") {
 1183: 	&logthis("$uname in $udom was unable to change their password ".
 1184: 		 "on $server.  The action was blocked by either lcpasswd ".
 1185: 		 "or pwchange");
 1186:     } elsif ($answer =~ "^non_authorized") {
 1187:         &logthis("$uname in $udom did not get their password correct when ".
 1188: 		 "attempting to change it on $server.");
 1189:     } elsif ($answer =~ "^auth_mode_error") {
 1190:         &logthis("$uname in $udom attempted to change their password despite ".
 1191: 		 "not being locally or internally authenticated on $server.");
 1192:     } elsif ($answer =~ "^unknown_user") {
 1193:         &logthis("$uname in $udom attempted to change their password ".
 1194: 		 "on $server but were unable to because $server is not ".
 1195: 		 "their home server.");
 1196:     } elsif ($answer =~ "^refused") {
 1197: 	&logthis("$server refused to change $uname in $udom password because ".
 1198: 		 "it was sent an unencrypted request to change the password.");
 1199:     } elsif ($answer =~ "invalid_client") {
 1200:         &logthis("$server refused to change $uname in $udom password because ".
 1201:                  "it was a reset by e-mail originating from an invalid server.");
 1202:     }
 1203:     return $answer;
 1204: }
 1205: 
 1206: # ----------------------- Try to determine user's current authentication scheme
 1207: 
 1208: sub queryauthenticate {
 1209:     my ($uname,$udom)=@_;
 1210:     my $uhome=&homeserver($uname,$udom);
 1211:     if (!$uhome) {
 1212: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1213: 	return 'no_host';
 1214:     }
 1215:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1216:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1217: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1218:     }
 1219:     return $answer;
 1220: }
 1221: 
 1222: # --------- Try to authenticate user from domain's lib servers (first this one)
 1223: 
 1224: sub authenticate {
 1225:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1226:     $upass=&escape($upass);
 1227:     $uname= &LONCAPA::clean_username($uname);
 1228:     my $uhome=&homeserver($uname,$udom,1);
 1229:     my $newhome;
 1230:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1231: # Maybe the machine was offline and only re-appeared again recently?
 1232:         &reconlonc();
 1233: # One more
 1234: 	$uhome=&homeserver($uname,$udom,1);
 1235:         if (($uhome eq 'no_host') && $checkdefauth) {
 1236:             if (defined(&domain($udom,'primary'))) {
 1237:                 $newhome=&domain($udom,'primary');
 1238:             }
 1239:             if ($newhome ne '') {
 1240:                 $uhome = $newhome;
 1241:             }
 1242:         }
 1243: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1244: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1245: 	    return 'no_host';
 1246:         }
 1247:     }
 1248:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1249:     if ($answer eq 'authorized') {
 1250:         if ($newhome) {
 1251:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1252:             return 'no_account_on_host'; 
 1253:         } else {
 1254:             &logthis("User $uname at $udom authorized by $uhome");
 1255:             return $uhome;
 1256:         }
 1257:     }
 1258:     if ($answer eq 'non_authorized') {
 1259: 	&logthis("User $uname at $udom rejected by $uhome");
 1260: 	return 'no_host'; 
 1261:     }
 1262:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1263:     return 'no_host';
 1264: }
 1265: 
 1266: sub can_host_session {
 1267:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1268:     my $canhost = 1;
 1269:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1270:     if (ref($remotesessions) eq 'HASH') {
 1271:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1272:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1273:                 $canhost = 0;
 1274:             } else {
 1275:                 $canhost = 1;
 1276:             }
 1277:         }
 1278:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1279:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1280:                 $canhost = 1;
 1281:             } else {
 1282:                 $canhost = 0;
 1283:             }
 1284:         }
 1285:         if ($canhost) {
 1286:             if ($remotesessions->{'version'} ne '') {
 1287:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1288:                 if ($reqmajor ne '' && $reqminor ne '') {
 1289:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1290:                         my $major = $1;
 1291:                         my $minor = $2;
 1292:                         if (($major < $reqmajor ) ||
 1293:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1294:                             $canhost = 0;
 1295:                         }
 1296:                     } else {
 1297:                         $canhost = 0;
 1298:                     }
 1299:                 }
 1300:             }
 1301:         }
 1302:     }
 1303:     if ($canhost) {
 1304:         if (ref($hostedsessions) eq 'HASH') {
 1305:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1306:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1307:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1308:                 if (($uint_dom ne '') && 
 1309:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1310:                     $canhost = 0;
 1311:                 } else {
 1312:                     $canhost = 1;
 1313:                 }
 1314:             }
 1315:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1316:                 if (($uint_dom ne '') && 
 1317:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1318:                     $canhost = 1;
 1319:                 } else {
 1320:                     $canhost = 0;
 1321:                 }
 1322:             }
 1323:         }
 1324:     }
 1325:     return $canhost;
 1326: }
 1327: 
 1328: sub spare_can_host {
 1329:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1330:     my $canhost=1;
 1331:     my $try_server_hostname = &hostname($try_server);
 1332:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1333:     my $serverhomedom = &host_domain($serverhomeID);
 1334:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1335:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1336:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1337:             $canhost = 0;
 1338:         }
 1339:     }
 1340:     if (($canhost) && ($uint_dom)) {
 1341:         my @intdoms;
 1342:         my $internet_names = &get_internet_names($try_server);
 1343:         if (ref($internet_names) eq 'ARRAY') {
 1344:             @intdoms = @{$internet_names};
 1345:         }
 1346:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1347:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1348:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1349:                                          $remotesessions,
 1350:                                          $defdomdefaults{'hostedsessions'});
 1351:         }
 1352:     }
 1353:     return $canhost;
 1354: }
 1355: 
 1356: sub this_host_spares {
 1357:     my ($dom) = @_;
 1358:     my ($dom_in_use,$lonhost_in_use,$result);
 1359:     my @hosts = &current_machine_ids();
 1360:     foreach my $lonhost (@hosts) {
 1361:         if (&host_domain($lonhost) eq $dom) {
 1362:             $dom_in_use = $dom;
 1363:             $lonhost_in_use = $lonhost;
 1364:             last;
 1365:         }
 1366:     }
 1367:     if ($dom_in_use ne '') {
 1368:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1369:     }
 1370:     if (ref($result) ne 'HASH') {
 1371:         $lonhost_in_use = $perlvar{'lonHostID'};
 1372:         $dom_in_use = &host_domain($lonhost_in_use);
 1373:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1374:         if (ref($result) ne 'HASH') {
 1375:             $result = \%spareid;
 1376:         }
 1377:     }
 1378:     return $result;
 1379: }
 1380: 
 1381: sub spares_for_offload  {
 1382:     my ($dom_in_use,$lonhost_in_use) = @_;
 1383:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1384:     if (defined($cached)) {
 1385:         return $result;
 1386:     } else {
 1387:         my $cachetime = 60*60*24;
 1388:         my %domconfig =
 1389:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1390:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1391:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1392:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1393:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1394:                 }
 1395:             }
 1396:         }
 1397:     }
 1398:     return;
 1399: }
 1400: 
 1401: sub get_lonbalancer_config {
 1402:     my ($servers) = @_;
 1403:     my ($currbalancer,$currtargets);
 1404:     if (ref($servers) eq 'HASH') {
 1405:         foreach my $server (keys(%{$servers})) {
 1406:             my %what = (
 1407:                          spareid => 1,
 1408:                          perlvar => 1,
 1409:                        );
 1410:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1411:             if ($result eq 'ok') {
 1412:                 if (ref($returnhash) eq 'HASH') {
 1413:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1414:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1415:                             $currbalancer = $server;
 1416:                             $currtargets = {};
 1417:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1418:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1419:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1420:                                 }
 1421:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1422:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1423:                                 }
 1424:                             }
 1425:                             last;
 1426:                         }
 1427:                     }
 1428:                 }
 1429:             }
 1430:         }
 1431:     }
 1432:     return ($currbalancer,$currtargets);
 1433: }
 1434: 
 1435: sub check_loadbalancing {
 1436:     my ($uname,$udom,$caller) = @_;
 1437:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1438:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
 1439:     my $lonhost = $perlvar{'lonHostID'};
 1440:     my @hosts = &current_machine_ids();
 1441:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1442:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1443:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1444:     my $serverhomedom = &host_domain($lonhost);
 1445:     my $domneedscache;
 1446:     my $cachetime = 60*60*24;
 1447: 
 1448:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1449:         $dom_in_use = $udom;
 1450:         $homeintdom = 1;
 1451:     } else {
 1452:         $dom_in_use = $serverhomedom;
 1453:     }
 1454:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1455:     unless (defined($cached)) {
 1456:         my %domconfig =
 1457:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1458:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1459:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1460:         } else {
 1461:             $domneedscache = $dom_in_use;
 1462:         }
 1463:     }
 1464:     if (ref($result) eq 'HASH') {
 1465:         ($is_balancer,$currtargets,$currrules,$setcookie) =
 1466:             &check_balancer_result($result,@hosts);
 1467:         if ($is_balancer) {
 1468:             if (ref($currrules) eq 'HASH') {
 1469:                 if ($homeintdom) {
 1470:                     if ($uname ne '') {
 1471:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1472:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1473:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1474:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1475:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1476:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1477:                             }
 1478:                         }
 1479:                         if ($rule_in_effect eq '') {
 1480:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1481:                             if ($userenv{'inststatus'} ne '') {
 1482:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1483:                                 my ($othertitle,$usertypes,$types) =
 1484:                                     &Apache::loncommon::sorted_inst_types($udom);
 1485:                                 if (ref($types) eq 'ARRAY') {
 1486:                                     foreach my $type (@{$types}) {
 1487:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1488:                                             if (exists($currrules->{$type})) {
 1489:                                                 $rule_in_effect = $currrules->{$type};
 1490:                                             }
 1491:                                         }
 1492:                                     }
 1493:                                 }
 1494:                             } else {
 1495:                                 if (exists($currrules->{'default'})) {
 1496:                                     $rule_in_effect = $currrules->{'default'};
 1497:                                 }
 1498:                             }
 1499:                         }
 1500:                     } else {
 1501:                         if (exists($currrules->{'default'})) {
 1502:                             $rule_in_effect = $currrules->{'default'};
 1503:                         }
 1504:                     }
 1505:                 } else {
 1506:                     if ($currrules->{'_LC_external'} ne '') {
 1507:                         $rule_in_effect = $currrules->{'_LC_external'};
 1508:                     }
 1509:                 }
 1510:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1511:                                                        $uname,$udom);
 1512:             }
 1513:         }
 1514:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1515:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1516:         unless (defined($cached)) {
 1517:             my %domconfig =
 1518:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1519:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1520:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1521:             } else {
 1522:                 $domneedscache = $serverhomedom;
 1523:             }
 1524:         }
 1525:         if (ref($result) eq 'HASH') {
 1526:             ($is_balancer,$currtargets,$currrules,$setcookie) =
 1527:                 &check_balancer_result($result,@hosts);
 1528:             if ($is_balancer) {
 1529:                 if (ref($currrules) eq 'HASH') {
 1530:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1531:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1532:                     }
 1533:                 }
 1534:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1535:                                                        $uname,$udom);
 1536:             }
 1537:         } else {
 1538:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1539:                 $is_balancer = 1;
 1540:                 $offloadto = &this_host_spares($dom_in_use);
 1541:             }
 1542:             unless (defined($cached)) {
 1543:                 $domneedscache = $serverhomedom;
 1544:             }
 1545:         }
 1546:     } else {
 1547:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1548:             $is_balancer = 1;
 1549:             $offloadto = &this_host_spares($dom_in_use);
 1550:         }
 1551:         unless (defined($cached)) {
 1552:             $domneedscache = $serverhomedom;
 1553:         }
 1554:     }
 1555:     if ($domneedscache) {
 1556:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1557:     }
 1558:     if ($is_balancer) {
 1559:         my $lowest_load = 30000;
 1560:         if (ref($offloadto) eq 'HASH') {
 1561:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1562:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1563:                     ($otherserver,$lowest_load) =
 1564:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1565:                 }
 1566:             }
 1567:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1568: 
 1569:             if (!$found_server) {
 1570:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1571:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1572:                         ($otherserver,$lowest_load) =
 1573:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1574:                     }
 1575:                 }
 1576:             }
 1577:         } elsif (ref($offloadto) eq 'ARRAY') {
 1578:             if (@{$offloadto} == 1) {
 1579:                 $otherserver = $offloadto->[0];
 1580:             } elsif (@{$offloadto} > 1) {
 1581:                 foreach my $try_server (@{$offloadto}) {
 1582:                     ($otherserver,$lowest_load) =
 1583:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1584:                 }
 1585:             }
 1586:         }
 1587:         unless ($caller eq 'login') {
 1588:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1589:                 $is_balancer = 0;
 1590:                 if ($uname ne '' && $udom ne '') {
 1591:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1592:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1593:                                  'user.loadbalcheck.time' => time});
 1594:                     }
 1595:                 }
 1596:             }
 1597:         }
 1598:         unless ($homeintdom) {
 1599:             undef($setcookie);
 1600:         }
 1601:     }
 1602:     return ($is_balancer,$otherserver,$setcookie);
 1603: }
 1604: 
 1605: sub check_balancer_result {
 1606:     my ($result,@hosts) = @_;
 1607:     my ($is_balancer,$currtargets,$currrules,$setcookie);
 1608:     if (ref($result) eq 'HASH') {
 1609:         if ($result->{'lonhost'} ne '') {
 1610:             my $currbalancer = $result->{'lonhost'};
 1611:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1612:                 $is_balancer = 1;
 1613:                 $currtargets = $result->{'targets'};
 1614:                 $currrules = $result->{'rules'};
 1615:             }
 1616:         } else {
 1617:             foreach my $key (keys(%{$result})) {
 1618:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1619:                     (ref($result->{$key}) eq 'HASH')) {
 1620:                     $is_balancer = 1;
 1621:                     $currrules = $result->{$key}{'rules'};
 1622:                     $currtargets = $result->{$key}{'targets'};
 1623:                     $setcookie = $result->{$key}{'cookie'};
 1624:                     last;
 1625:                 }
 1626:             }
 1627:         }
 1628:     }
 1629:     return ($is_balancer,$currtargets,$currrules,$setcookie);
 1630: }
 1631: 
 1632: sub get_loadbalancer_targets {
 1633:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1634:     my $offloadto;
 1635:     if ($rule_in_effect eq 'none') {
 1636:         return [$perlvar{'lonHostID'}];
 1637:     } elsif ($rule_in_effect eq '') {
 1638:         $offloadto = $currtargets;
 1639:     } else {
 1640:         if ($rule_in_effect eq 'homeserver') {
 1641:             my $homeserver = &homeserver($uname,$udom);
 1642:             if ($homeserver ne 'no_host') {
 1643:                 $offloadto = [$homeserver];
 1644:             }
 1645:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1646:             my %domconfig =
 1647:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1648:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1649:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1650:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1651:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1652:                     }
 1653:                 }
 1654:             } else {
 1655:                 my %servers = &internet_dom_servers($udom);
 1656:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1657:                 if (&hostname($remotebalancer) ne '') {
 1658:                     $offloadto = [$remotebalancer];
 1659:                 }
 1660:             }
 1661:         } elsif (&hostname($rule_in_effect) ne '') {
 1662:             $offloadto = [$rule_in_effect];
 1663:         }
 1664:     }
 1665:     return $offloadto;
 1666: }
 1667: 
 1668: sub internet_dom_servers {
 1669:     my ($dom) = @_;
 1670:     my (%uniqservers,%servers);
 1671:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1672:     my @machinedoms = &machine_domains($primaryserver);
 1673:     foreach my $mdom (@machinedoms) {
 1674:         my %currservers = %servers;
 1675:         my %server = &get_servers($mdom);
 1676:         %servers = (%currservers,%server);
 1677:     }
 1678:     my %by_hostname;
 1679:     foreach my $id (keys(%servers)) {
 1680:         push(@{$by_hostname{$servers{$id}}},$id);
 1681:     }
 1682:     foreach my $hostname (sort(keys(%by_hostname))) {
 1683:         if (@{$by_hostname{$hostname}} > 1) {
 1684:             my $match = 0;
 1685:             foreach my $id (@{$by_hostname{$hostname}}) {
 1686:                 if (&host_domain($id) eq $dom) {
 1687:                     $uniqservers{$id} = $hostname;
 1688:                     $match = 1;
 1689:                 }
 1690:             }
 1691:             unless ($match) {
 1692:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1693:             }
 1694:         } else {
 1695:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1696:         }
 1697:     }
 1698:     return %uniqservers;
 1699: }
 1700: 
 1701: sub trusted_domains {
 1702:     my ($cmdtype,$calldom) = @_;
 1703:     my ($trusted,$untrusted);
 1704:     if (&domain($calldom) eq '') {
 1705:         return ($trusted,$untrusted);
 1706:     }
 1707:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1708:         return ($trusted,$untrusted);
 1709:     }
 1710:     my $callprimary = &domain($calldom,'primary');
 1711:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1712:     if ($intcalldom eq '') {
 1713:         return ($trusted,$untrusted);
 1714:     }
 1715: 
 1716:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1717:     unless (defined($cached)) {
 1718:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1719:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1720:         $trustconfig = $domconfig{'trust'};
 1721:     }
 1722:     if (ref($trustconfig)) {
 1723:         my (%possexc,%possinc,@allexc,@allinc); 
 1724:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1725:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1726:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1727:             }
 1728:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1729:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1730:             }
 1731:         }
 1732:         if (keys(%possexc)) {
 1733:             if (keys(%possinc)) {
 1734:                 foreach my $key (sort(keys(%possexc))) {
 1735:                     next if ($key eq $intcalldom);
 1736:                     unless ($possinc{$key}) {
 1737:                         push(@allexc,$key);
 1738:                     }
 1739:                 }
 1740:             } else {
 1741:                 @allexc = sort(keys(%possexc));
 1742:             }
 1743:         }
 1744:         if (keys(%possinc)) {
 1745:             $possinc{$intcalldom} = 1;
 1746:             @allinc = sort(keys(%possinc));
 1747:         }
 1748:         if ((@allexc > 0) || (@allinc > 0)) {
 1749:             my %doms_by_intdom;
 1750:             my %allintdoms = &all_host_intdom();
 1751:             my %alldoms = &all_host_domain();
 1752:             foreach my $key (%allintdoms) {
 1753:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1754:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1755:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1756:                     }
 1757:                 } else {
 1758:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1759:                 }
 1760:             }
 1761:             foreach my $exc (@allexc) {
 1762:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1763:                     $untrusted = $doms_by_intdom{$exc};
 1764:                 }
 1765:             }
 1766:             foreach my $inc (@allinc) {
 1767:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1768:                     $trusted = $doms_by_intdom{$inc};
 1769:                 }
 1770:             }
 1771:         }
 1772:     }
 1773:     return ($trusted,$untrusted);
 1774: }
 1775: 
 1776: sub will_trust {
 1777:     my ($cmdtype,$domain,$possdom) = @_;
 1778:     return 1 if ($domain eq $possdom);
 1779:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1780:     my $willtrust; 
 1781:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1782:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1783:             $willtrust = 1;
 1784:         }
 1785:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1786:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1787:             $willtrust = 1;
 1788:         }
 1789:     } else {
 1790:         $willtrust = 1;
 1791:     }
 1792:     return $willtrust;
 1793: }
 1794: 
 1795: # ---------------------- Find the homebase for a user from domain's lib servers
 1796: 
 1797: my %homecache;
 1798: sub homeserver {
 1799:     my ($uname,$udom,$ignoreBadCache)=@_;
 1800:     my $index="$uname:$udom";
 1801: 
 1802:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1803: 
 1804:     my %servers = &get_servers($udom,'library');
 1805:     foreach my $tryserver (keys(%servers)) {
 1806:         next if ($ignoreBadCache ne 'true' && 
 1807: 		 exists($badServerCache{$tryserver}));
 1808: 
 1809: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1810: 	if ($answer eq 'found') {
 1811: 	    delete($badServerCache{$tryserver}); 
 1812: 	    return $homecache{$index}=$tryserver;
 1813: 	} elsif ($answer eq 'no_host') {
 1814: 	    $badServerCache{$tryserver}=1;
 1815: 	}
 1816:     }    
 1817:     return 'no_host';
 1818: }
 1819: 
 1820: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1821: 
 1822: sub idget {
 1823:     my ($udom,$idsref,$namespace)=@_;
 1824:     my %returnhash=();
 1825:     my @ids=(); 
 1826:     if (ref($idsref) eq 'ARRAY') {
 1827:         @ids = @{$idsref};
 1828:     } else {
 1829:         return %returnhash; 
 1830:     }
 1831:     if ($namespace eq '') {
 1832:         $namespace = 'ids';
 1833:     }
 1834:     
 1835:     my %servers = &get_servers($udom,'library');
 1836:     foreach my $tryserver (keys(%servers)) {
 1837: 	my $idlist=join('&', map { &escape($_); } @ids);
 1838: 	if ($namespace eq 'ids') {
 1839: 	    $idlist=~tr/A-Z/a-z/;
 1840: 	}
 1841: 	my $reply;
 1842: 	if ($namespace eq 'ids') {
 1843: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1844: 	} else {
 1845: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1846: 	}
 1847: 	my @answer=();
 1848: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1849: 	    @answer=split(/\&/,$reply);
 1850: 	}                    ;
 1851: 	my $i;
 1852: 	for ($i=0;$i<=$#ids;$i++) {
 1853: 	    if ($answer[$i]) {
 1854: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1855: 	    }
 1856: 	}
 1857:     }
 1858:     return %returnhash;
 1859: }
 1860: 
 1861: # ------------------------------------- Find the IDs behind a list of usernames
 1862: 
 1863: sub idrget {
 1864:     my ($udom,@unames)=@_;
 1865:     my %returnhash=();
 1866:     foreach my $uname (@unames) {
 1867:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1868:     }
 1869:     return %returnhash;
 1870: }
 1871: 
 1872: # Store away a list of names and associated student/employee IDs or clicker IDs
 1873: 
 1874: sub idput {
 1875:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1876:     my %servers=();
 1877:     my %ids=();
 1878:     my %byid = ();
 1879:     if (ref($idsref) eq 'HASH') {
 1880:         %ids=%{$idsref};
 1881:     }
 1882:     if ($namespace eq '') {
 1883:         $namespace = 'ids'; 
 1884:     }
 1885:     foreach my $uname (keys(%ids)) {
 1886: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1887:         if ($uhom eq '') {
 1888:             $uhom=&homeserver($uname,$udom);
 1889:         }
 1890:         if ($uhom ne 'no_host') {
 1891:             my $esc_unam=&escape($uname);
 1892:             if ($namespace eq 'ids') {
 1893:                 my $id=&escape($ids{$uname});
 1894:                 $id=~tr/A-Z/a-z/;
 1895:                 my $esc_unam=&escape($uname);
 1896:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1897:             } else {
 1898:                 my @currids = split(/,/,$ids{$uname});
 1899:                 foreach my $id (@currids) {
 1900:                     $byid{$uhom}{$id} .= $uname.',';
 1901:                 }
 1902:             }
 1903:         }
 1904:     }
 1905:     if ($namespace eq 'clickers') {
 1906:         foreach my $server (keys(%byid)) {
 1907:             if (ref($byid{$server}) eq 'HASH') {
 1908:                 foreach my $id (keys(%{$byid{$server}})) {
 1909:                     $byid{$server} =~ s/,$//;
 1910:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1911:                 }
 1912:             }
 1913:         }
 1914:     }
 1915:     foreach my $server (keys(%servers)) {
 1916:         $servers{$server} =~ s/\&$//;
 1917:         if ($namespace eq 'ids') {     
 1918:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1919:         } else {
 1920:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1921:         }
 1922:     }
 1923: }
 1924: 
 1925: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1926: 
 1927: sub iddel {
 1928:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1929:     my %result=();
 1930:     my %ids=();
 1931:     my %byid = ();
 1932:     if (ref($idshashref) eq 'HASH') {
 1933:         %ids=%{$idshashref};
 1934:     } else {
 1935:         return %result;
 1936:     }
 1937:     if ($namespace eq '') {
 1938:         $namespace = 'ids';
 1939:     }
 1940:     my %servers=();
 1941:     while (my ($id,$unamestr) = each(%ids)) {
 1942:         if ($namespace eq 'ids') {
 1943:             my $uhom = $uhome;
 1944:             if ($uhom eq '') { 
 1945:                 $uhom=&homeserver($unamestr,$udom);
 1946:             }
 1947:             if ($uhom ne 'no_host') {
 1948:                 $servers{$uhom}.='&'.&escape($id);
 1949:             }
 1950:          } else {
 1951:             my @curritems = split(/,/,$ids{$id});
 1952:             foreach my $uname (@curritems) {
 1953:                 my $uhom = $uhome;
 1954:                 if ($uhom eq '') {
 1955:                     $uhom=&homeserver($uname,$udom);
 1956:                 }
 1957:                 if ($uhom ne 'no_host') { 
 1958:                     $byid{$uhom}{$id} .= $uname.',';
 1959:                 }
 1960:             }
 1961:         }
 1962:     }
 1963:     if ($namespace eq 'clickers') {
 1964:         foreach my $server (keys(%byid)) {
 1965:             if (ref($byid{$server}) eq 'HASH') {
 1966:                 foreach my $id (keys(%{$byid{$server}})) {
 1967:                     $byid{$server}{$id} =~ s/,$//;
 1968:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1969:                 }
 1970:             }
 1971:         }
 1972:     }
 1973:     foreach my $server (keys(%servers)) {
 1974:         $servers{$server} =~ s/\&$//;
 1975:         if ($namespace eq 'ids') {
 1976:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1977:         } elsif ($namespace eq 'clickers') {
 1978:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1979:         }
 1980:     }
 1981:     return %result;
 1982: }
 1983: 
 1984: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1985: 
 1986: sub updateclickers {
 1987:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1988:     my %clickers;
 1989:     if (ref($idshashref) eq 'HASH') {
 1990:         %clickers=%{$idshashref};
 1991:     } else {
 1992:         return;
 1993:     }
 1994:     my $items='';
 1995:     foreach my $item (keys(%clickers)) {
 1996:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1997:     }
 1998:     $items=~s/\&$//;
 1999:     my $request = "updateclickers:$udom:$action:$items";
 2000:     if ($critical) {
 2001:         return &critical($request,$uhome);
 2002:     } else {
 2003:         return &reply($request,$uhome);
 2004:     }
 2005: }
 2006: 
 2007: # ------------------------------dump from db file owned by domainconfig user
 2008: sub dump_dom {
 2009:     my ($namespace, $udom, $regexp) = @_;
 2010: 
 2011:     $udom ||= $env{'user.domain'};
 2012: 
 2013:     return () unless $udom;
 2014: 
 2015:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2016: }
 2017: 
 2018: # ------------------------------------------ get items from domain db files   
 2019: 
 2020: sub get_dom {
 2021:     my ($namespace,$storearr,$udom,$uhome)=@_;
 2022:     return if ($udom eq 'public');
 2023:     my $items='';
 2024:     foreach my $item (@$storearr) {
 2025:         $items.=&escape($item).'&';
 2026:     }
 2027:     $items=~s/\&$//;
 2028:     if (!$udom) {
 2029:         $udom=$env{'user.domain'};
 2030:         return if ($udom eq 'public');
 2031:         if (defined(&domain($udom,'primary'))) {
 2032:             $uhome=&domain($udom,'primary');
 2033:         } else {
 2034:             undef($uhome);
 2035:         }
 2036:     } else {
 2037:         if (!$uhome) {
 2038:             if (defined(&domain($udom,'primary'))) {
 2039:                 $uhome=&domain($udom,'primary');
 2040:             }
 2041:         }
 2042:     }
 2043:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2044:         my $rep;
 2045:         if ($namespace =~ /^enc/) {
 2046:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2047:         } else {
 2048:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2049:         }
 2050:         my %returnhash;
 2051:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2052:             return %returnhash;
 2053:         }
 2054:         my @pairs=split(/\&/,$rep);
 2055:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2056:             return @pairs;
 2057:         }
 2058:         my $i=0;
 2059:         foreach my $item (@$storearr) {
 2060:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2061:             $i++;
 2062:         }
 2063:         return %returnhash;
 2064:     } else {
 2065:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2066:     }
 2067: }
 2068: 
 2069: # -------------------------------------------- put items in domain db files 
 2070: 
 2071: sub put_dom {
 2072:     my ($namespace,$storehash,$udom,$uhome)=@_;
 2073:     if (!$udom) {
 2074:         $udom=$env{'user.domain'};
 2075:         if (defined(&domain($udom,'primary'))) {
 2076:             $uhome=&domain($udom,'primary');
 2077:         } else {
 2078:             undef($uhome);
 2079:         }
 2080:     } else {
 2081:         if (!$uhome) {
 2082:             if (defined(&domain($udom,'primary'))) {
 2083:                 $uhome=&domain($udom,'primary');
 2084:             }
 2085:         }
 2086:     } 
 2087:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2088:         my $items='';
 2089:         foreach my $item (keys(%$storehash)) {
 2090:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2091:         }
 2092:         $items=~s/\&$//;
 2093:         if ($namespace =~ /^enc/) {
 2094:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2095:         } else {
 2096:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2097:         }
 2098:     } else {
 2099:         &logthis("put_dom failed - no homeserver and/or domain");
 2100:     }
 2101: }
 2102: 
 2103: # --------------------- newput for items in db file owned by domainconfig user
 2104: sub newput_dom {
 2105:     my ($namespace,$storehash,$udom) = @_;
 2106:     my $result;
 2107:     if (!$udom) {
 2108:         $udom=$env{'user.domain'};
 2109:     }
 2110:     if ($udom) {
 2111:         my $uname = &get_domainconfiguser($udom);
 2112:         $result = &newput($namespace,$storehash,$udom,$uname);
 2113:     }
 2114:     return $result;
 2115: }
 2116: 
 2117: # --------------------- delete for items in db file owned by domainconfig user
 2118: sub del_dom {
 2119:     my ($namespace,$storearr,$udom)=@_;
 2120:     if (ref($storearr) eq 'ARRAY') {
 2121:         if (!$udom) {
 2122:             $udom=$env{'user.domain'};
 2123:         }
 2124:         if ($udom) {
 2125:             my $uname = &get_domainconfiguser($udom); 
 2126:             return &del($namespace,$storearr,$udom,$uname);
 2127:         }
 2128:     }
 2129: }
 2130: 
 2131: # ----------------------------------construct domainconfig user for a domain 
 2132: sub get_domainconfiguser {
 2133:     my ($udom) = @_;
 2134:     return $udom.'-domainconfig';
 2135: }
 2136: 
 2137: sub retrieve_inst_usertypes {
 2138:     my ($udom) = @_;
 2139:     my (%returnhash,@order);
 2140:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2141:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2142:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2143:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2144:     } else {
 2145:         if (defined(&domain($udom,'primary'))) {
 2146:             my $uhome=&domain($udom,'primary');
 2147:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2148:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2149:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2150:                 return (\%returnhash,\@order);
 2151:             }
 2152:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2153:             my @pairs=split(/\&/,$hashitems);
 2154:             foreach my $item (@pairs) {
 2155:                 my ($key,$value)=split(/=/,$item,2);
 2156:                 $key = &unescape($key);
 2157:                 next if ($key =~ /^error: 2 /);
 2158:                 $returnhash{$key}=&thaw_unescape($value);
 2159:             }
 2160:             my @esc_order = split(/\&/,$orderitems);
 2161:             foreach my $item (@esc_order) {
 2162:                 push(@order,&unescape($item));
 2163:             }
 2164:         } else {
 2165:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2166:         }
 2167:         return (\%returnhash,\@order);
 2168:     }
 2169: }
 2170: 
 2171: sub is_domainimage {
 2172:     my ($url) = @_;
 2173:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2174:         if (&domain($1) ne '') {
 2175:             return '1';
 2176:         }
 2177:     }
 2178:     return;
 2179: }
 2180: 
 2181: sub inst_directory_query {
 2182:     my ($srch) = @_;
 2183:     my $udom = $srch->{'srchdomain'};
 2184:     my %results;
 2185:     my $homeserver = &domain($udom,'primary');
 2186:     my $outcome;
 2187:     if ($homeserver ne '') {
 2188:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2189:             if ($srch->{'srchby'} eq 'email') {
 2190:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2191:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2192:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2193:                     (($major == 2) && ($minor < 12))) {
 2194:                     return;
 2195:                 }
 2196:             }
 2197:         }
 2198: 	my $queryid=&reply("querysend:instdirsearch:".
 2199: 			   &escape($srch->{'srchby'}).':'.
 2200: 			   &escape($srch->{'srchterm'}).':'.
 2201: 			   &escape($srch->{'srchtype'}),$homeserver);
 2202: 	my $host=&hostname($homeserver);
 2203: 	if ($queryid !~/^\Q$host\E\_/) {
 2204: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2205: 	    return;
 2206: 	}
 2207: 	my $response = &get_query_reply($queryid);
 2208: 	my $maxtries = 5;
 2209: 	my $tries = 1;
 2210: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2211: 	    $response = &get_query_reply($queryid);
 2212: 	    $tries ++;
 2213: 	}
 2214: 
 2215:         if (!&error($response) && $response ne 'refused') {
 2216:             if ($response eq 'unavailable') {
 2217:                 $outcome = $response;
 2218:             } else {
 2219:                 $outcome = 'ok';
 2220:                 my @matches = split(/\n/,$response);
 2221:                 foreach my $match (@matches) {
 2222:                     my ($key,$value) = split(/=/,$match);
 2223:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2224:                 }
 2225:             }
 2226:         }
 2227:     }
 2228:     return ($outcome,%results);
 2229: }
 2230: 
 2231: sub usersearch {
 2232:     my ($srch) = @_;
 2233:     my $dom = $srch->{'srchdomain'};
 2234:     my %results;
 2235:     my %libserv = &all_library();
 2236:     my $query = 'usersearch';
 2237:     foreach my $tryserver (keys(%libserv)) {
 2238:         if (&host_domain($tryserver) eq $dom) {
 2239:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2240:                 if ($srch->{'srchby'} eq 'email') {
 2241:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2242:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2243:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2244:                              (($major == 2) && ($minor < 12)));
 2245:                 }
 2246:             }
 2247:             my $host=&hostname($tryserver);
 2248:             my $queryid=
 2249:                 &reply("querysend:".&escape($query).':'.
 2250:                        &escape($srch->{'srchby'}).':'.
 2251:                        &escape($srch->{'srchtype'}).':'.
 2252:                        &escape($srch->{'srchterm'}),$tryserver);
 2253:             if ($queryid !~/^\Q$host\E\_/) {
 2254:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2255:                 next;
 2256:             }
 2257:             my $reply = &get_query_reply($queryid);
 2258:             my $maxtries = 1;
 2259:             my $tries = 1;
 2260:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2261:                 $reply = &get_query_reply($queryid);
 2262:                 $tries ++;
 2263:             }
 2264:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2265:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2266:             } else {
 2267:                 my @matches;
 2268:                 if ($reply =~ /\n/) {
 2269:                     @matches = split(/\n/,$reply);
 2270:                 } else {
 2271:                     @matches = split(/\&/,$reply);
 2272:                 }
 2273:                 foreach my $match (@matches) {
 2274:                     my ($uname,$udom,%userhash);
 2275:                     foreach my $entry (split(/:/,$match)) {
 2276:                         my ($key,$value) =
 2277:                             map {&unescape($_);} split(/=/,$entry);
 2278:                         $userhash{$key} = $value;
 2279:                         if ($key eq 'username') {
 2280:                             $uname = $value;
 2281:                         } elsif ($key eq 'domain') {
 2282:                             $udom = $value;
 2283:                         }
 2284:                     }
 2285:                     $results{$uname.':'.$udom} = \%userhash;
 2286:                 }
 2287:             }
 2288:         }
 2289:     }
 2290:     return %results;
 2291: }
 2292: 
 2293: sub get_instuser {
 2294:     my ($udom,$uname,$id) = @_;
 2295:     my $homeserver = &domain($udom,'primary');
 2296:     my ($outcome,%results);
 2297:     if ($homeserver ne '') {
 2298:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2299:                            &escape($id).':'.&escape($udom),$homeserver);
 2300:         my $host=&hostname($homeserver);
 2301:         if ($queryid !~/^\Q$host\E\_/) {
 2302:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2303:             return;
 2304:         }
 2305:         my $response = &get_query_reply($queryid);
 2306:         my $maxtries = 5;
 2307:         my $tries = 1;
 2308:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2309:             $response = &get_query_reply($queryid);
 2310:             $tries ++;
 2311:         }
 2312:         if (!&error($response) && $response ne 'refused') {
 2313:             if ($response eq 'unavailable') {
 2314:                 $outcome = $response;
 2315:             } else {
 2316:                 $outcome = 'ok';
 2317:                 my @matches = split(/\n/,$response);
 2318:                 foreach my $match (@matches) {
 2319:                     my ($key,$value) = split(/=/,$match);
 2320:                     $results{&unescape($key)} = &thaw_unescape($value);
 2321:                 }
 2322:             }
 2323:         }
 2324:     }
 2325:     my %userinfo;
 2326:     if (ref($results{$uname}) eq 'HASH') {
 2327:         %userinfo = %{$results{$uname}};
 2328:     } 
 2329:     return ($outcome,%userinfo);
 2330: }
 2331: 
 2332: sub get_multiple_instusers {
 2333:     my ($udom,$users,$caller) = @_;
 2334:     my ($outcome,$results);
 2335:     if (ref($users) eq 'HASH') {
 2336:         my $count = keys(%{$users}); 
 2337:         my $requested = &freeze_escape($users);
 2338:         my $homeserver = &domain($udom,'primary');
 2339:         if ($homeserver ne '') {
 2340:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2341:             my $host=&hostname($homeserver);
 2342:             if ($queryid !~/^\Q$host\E\_/) {
 2343:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2344:                          ' for host: '.$homeserver.'in domain '.$udom);
 2345:                 return ($outcome,$results);
 2346:             }
 2347:             my $response = &get_query_reply($queryid);
 2348:             my $maxtries = 5;
 2349:             if ($count > 100) {
 2350:                 $maxtries = 1+int($count/20);
 2351:             }
 2352:             my $tries = 1;
 2353:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2354:                 $response = &get_query_reply($queryid);
 2355:                 $tries ++;
 2356:             }
 2357:             if ($response eq '') {
 2358:                 $results = {};
 2359:                 foreach my $key (keys(%{$users})) {
 2360:                     my ($uname,$id);
 2361:                     if ($caller eq 'id') {
 2362:                         $id = $key;
 2363:                     } else {
 2364:                         $uname = $key;
 2365:                     }
 2366:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2367:                     $outcome = $resp;
 2368:                     if ($resp eq 'ok') {
 2369:                         %{$results} = (%{$results}, %info);
 2370:                     } else {
 2371:                         last;
 2372:                     }
 2373:                 }
 2374:             } elsif(!&error($response) && ($response ne 'refused')) {
 2375:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2376:                     $outcome = $response;
 2377:                 } else {
 2378:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2379:                     if ($outcome eq 'ok') {
 2380:                         $results = &thaw_unescape($userdata); 
 2381:                     }
 2382:                 }
 2383:             }
 2384:         }
 2385:     }
 2386:     return ($outcome,$results);
 2387: }
 2388: 
 2389: sub inst_rulecheck {
 2390:     my ($udom,$uname,$id,$item,$rules) = @_;
 2391:     my %returnhash;
 2392:     if ($udom ne '') {
 2393:         if (ref($rules) eq 'ARRAY') {
 2394:             @{$rules} = map {&escape($_);} (@{$rules});
 2395:             my $rulestr = join(':',@{$rules});
 2396:             my $homeserver=&domain($udom,'primary');
 2397:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2398:                 my $response;
 2399:                 if ($item eq 'username') {                
 2400:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2401:                                               ':'.&escape($uname).':'.$rulestr,
 2402:                                               $homeserver));
 2403:                 } elsif ($item eq 'id') {
 2404:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2405:                                               ':'.&escape($id).':'.$rulestr,
 2406:                                               $homeserver));
 2407:                 } elsif ($item eq 'selfcreate') {
 2408:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2409:                                                &escape($udom).':'.&escape($uname).
 2410:                                               ':'.$rulestr,$homeserver));
 2411:                 }
 2412:                 if ($response ne 'refused') {
 2413:                     my @pairs=split(/\&/,$response);
 2414:                     foreach my $item (@pairs) {
 2415:                         my ($key,$value)=split(/=/,$item,2);
 2416:                         $key = &unescape($key);
 2417:                         next if ($key =~ /^error: 2 /);
 2418:                         $returnhash{$key}=&thaw_unescape($value);
 2419:                     }
 2420:                 }
 2421:             }
 2422:         }
 2423:     }
 2424:     return %returnhash;
 2425: }
 2426: 
 2427: sub inst_userrules {
 2428:     my ($udom,$check) = @_;
 2429:     my (%ruleshash,@ruleorder);
 2430:     if ($udom ne '') {
 2431:         my $homeserver=&domain($udom,'primary');
 2432:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2433:             my $response;
 2434:             if ($check eq 'id') {
 2435:                 $response=&reply('instidrules:'.&escape($udom),
 2436:                                  $homeserver);
 2437:             } elsif ($check eq 'email') {
 2438:                 $response=&reply('instemailrules:'.&escape($udom),
 2439:                                  $homeserver);
 2440:             } else {
 2441:                 $response=&reply('instuserrules:'.&escape($udom),
 2442:                                  $homeserver);
 2443:             }
 2444:             if (($response ne 'refused') && ($response ne 'error') && 
 2445:                 ($response ne 'unknown_cmd') && 
 2446:                 ($response ne 'no_such_host')) {
 2447:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2448:                 my @pairs=split(/\&/,$hashitems);
 2449:                 foreach my $item (@pairs) {
 2450:                     my ($key,$value)=split(/=/,$item,2);
 2451:                     $key = &unescape($key);
 2452:                     next if ($key =~ /^error: 2 /);
 2453:                     $ruleshash{$key}=&thaw_unescape($value);
 2454:                 }
 2455:                 my @esc_order = split(/\&/,$orderitems);
 2456:                 foreach my $item (@esc_order) {
 2457:                     push(@ruleorder,&unescape($item));
 2458:                 }
 2459:             }
 2460:         }
 2461:     }
 2462:     return (\%ruleshash,\@ruleorder);
 2463: }
 2464: 
 2465: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2466: 
 2467: sub get_domain_defaults {
 2468:     my ($domain,$ignore_cache) = @_;
 2469:     return if (($domain eq '') || ($domain eq 'public'));
 2470:     my $cachetime = 60*60*24;
 2471:     unless ($ignore_cache) {
 2472:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2473:         if (defined($cached)) {
 2474:             if (ref($result) eq 'HASH') {
 2475:                 return %{$result};
 2476:             }
 2477:         }
 2478:     }
 2479:     my %domdefaults;
 2480:     my %domconfig =
 2481:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2482:                                   'requestcourses','inststatus',
 2483:                                   'coursedefaults','usersessions',
 2484:                                   'requestauthor','selfenrollment',
 2485:                                   'coursecategories','ssl','autoenroll',
 2486:                                   'trust','helpsettings'],$domain);
 2487:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2488:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2489:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2490:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2491:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2492:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2493:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2494:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2495:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2496:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2497:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2498:     } else {
 2499:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2500:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2501:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2502:     }
 2503:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2504:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2505:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2506:         } else {
 2507:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2508:         }
 2509:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2510:         foreach my $item (@usertools) {
 2511:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2512:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2513:             }
 2514:         }
 2515:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2516:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2517:         }
 2518:     }
 2519:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2520:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2521:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2522:         }
 2523:     }
 2524:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2525:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2526:     }
 2527:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2528:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2529:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2530:         }
 2531:     }
 2532:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2533:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2534:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2535:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2536:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2537:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2538:         }
 2539:         foreach my $type (@coursetypes) {
 2540:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2541:                 unless ($type eq 'community') {
 2542:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2543:                 }
 2544:             }
 2545:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2546:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2547:             }
 2548:             if ($domdefaults{'postsubmit'} eq 'on') {
 2549:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2550:                     $domdefaults{$type.'postsubtimeout'} = 
 2551:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2552:                 }
 2553:             }
 2554:         }
 2555:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2556:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2557:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2558:                 if (@clonecodes) {
 2559:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2560:                 }
 2561:             }
 2562:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2563:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2564:         }
 2565:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2566:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2567:         } 
 2568:     }
 2569:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2570:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2571:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2572:         }
 2573:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2574:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2575:         }
 2576:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2577:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2578:         }
 2579:     }
 2580:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2581:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2582:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2583:                             'approval','limit');
 2584:             foreach my $type (@coursetypes) {
 2585:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2586:                     my @mgrdc = ();
 2587:                     foreach my $item (@settings) {
 2588:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2589:                             push(@mgrdc,$item);
 2590:                         }
 2591:                     }
 2592:                     if (@mgrdc) {
 2593:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2594:                     }
 2595:                 }
 2596:             }
 2597:         }
 2598:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2599:             foreach my $type (@coursetypes) {
 2600:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2601:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2602:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2603:                     }
 2604:                 }
 2605:             }
 2606:         }
 2607:     }
 2608:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2609:         $domdefaults{'catauth'} = 'std';
 2610:         $domdefaults{'catunauth'} = 'std';
 2611:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2612:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2613:         }
 2614:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2615:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2616:         }
 2617:     }
 2618:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2619:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2620:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2621:         }
 2622:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2623:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2624:         }
 2625:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2626:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2627:         }
 2628:     }
 2629:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2630:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2631:         foreach my $prefix (@prefixes) {
 2632:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2633:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2634:             }
 2635:         }
 2636:     }
 2637:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2638:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2639:     }
 2640:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2641:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2642:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2643:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2644:         }
 2645:     }
 2646:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2647:     return %domdefaults;
 2648: }
 2649: 
 2650: sub course_portal_url {
 2651:     my ($cnum,$cdom) = @_;
 2652:     my $chome = &homeserver($cnum,$cdom);
 2653:     my $hostname = &hostname($chome);
 2654:     my $protocol = $protocol{$chome};
 2655:     $protocol = 'http' if ($protocol ne 'https');
 2656:     my %domdefaults = &get_domain_defaults($cdom);
 2657:     my $firsturl;
 2658:     if ($domdefaults{'portal_def'}) {
 2659:         $firsturl = $domdefaults{'portal_def'};
 2660:     } else {
 2661:         $firsturl = $protocol.'://'.$hostname;
 2662:     }
 2663:     return $firsturl;
 2664: }
 2665: 
 2666: # --------------------------------------------------- Assign a key to a student
 2667: 
 2668: sub assign_access_key {
 2669: #
 2670: # a valid key looks like uname:udom#comments
 2671: # comments are being appended
 2672: #
 2673:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2674:     $kdom=
 2675:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2676:     $knum=
 2677:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2678:     $cdom=
 2679:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2680:     $cnum=
 2681:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2682:     $udom=$env{'user.name'} unless (defined($udom));
 2683:     $uname=$env{'user.domain'} unless (defined($uname));
 2684:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2685:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2686:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2687:                                                   # assigned to this person
 2688:                                                   # - this should not happen,
 2689:                                                   # unless something went wrong
 2690:                                                   # the first time around
 2691: # ready to assign
 2692:         $logentry=$1.'; '.$logentry;
 2693:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2694:                                                  $kdom,$knum) eq 'ok') {
 2695: # key now belongs to user
 2696: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2697:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2698:                 &appenv({'environment.'.$envkey => $ckey});
 2699:                 return 'ok';
 2700:             } else {
 2701:                 return 
 2702:   'error: Count not permanently assign key, will need to be re-entered later.';
 2703: 	    }
 2704:         } else {
 2705:             return 'error: Could not assign key, try again later.';
 2706:         }
 2707:     } elsif (!$existing{$ckey}) {
 2708: # the key does not exist
 2709: 	return 'error: The key does not exist';
 2710:     } else {
 2711: # the key is somebody else's
 2712: 	return 'error: The key is already in use';
 2713:     }
 2714: }
 2715: 
 2716: # ------------------------------------------ put an additional comment on a key
 2717: 
 2718: sub comment_access_key {
 2719: #
 2720: # a valid key looks like uname:udom#comments
 2721: # comments are being appended
 2722: #
 2723:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2724:     $cdom=
 2725:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2726:     $cnum=
 2727:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2728:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2729:     if ($existing{$ckey}) {
 2730:         $existing{$ckey}.='; '.$logentry;
 2731: # ready to assign
 2732:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2733:                                                  $cdom,$cnum) eq 'ok') {
 2734: 	    return 'ok';
 2735:         } else {
 2736: 	    return 'error: Count not store comment.';
 2737:         }
 2738:     } else {
 2739: # the key does not exist
 2740: 	return 'error: The key does not exist';
 2741:     }
 2742: }
 2743: 
 2744: # ------------------------------------------------------ Generate a set of keys
 2745: 
 2746: sub generate_access_keys {
 2747:     my ($number,$cdom,$cnum,$logentry)=@_;
 2748:     $cdom=
 2749:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2750:     $cnum=
 2751:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2752:     unless (&allowed('mky',$cdom)) { return 0; }
 2753:     unless (($cdom) && ($cnum)) { return 0; }
 2754:     if ($number>10000) { return 0; }
 2755:     sleep(2); # make sure don't get same seed twice
 2756:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2757:     my $total=0;
 2758:     for (my $i=1;$i<=$number;$i++) {
 2759:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2760:                   sprintf("%lx",int(100000*rand)).'-'.
 2761:                   sprintf("%lx",int(100000*rand));
 2762:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2763:        $newkey=~s/0/h/g; # and also 0 and O
 2764:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2765:        if ($existing{$newkey}) {
 2766:            $i--;
 2767:        } else {
 2768: 	  if (&put('accesskeys',
 2769:               { $newkey => '# generated '.localtime().
 2770:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2771:                            '; '.$logentry },
 2772: 		   $cdom,$cnum) eq 'ok') {
 2773:               $total++;
 2774: 	  }
 2775:        }
 2776:     }
 2777:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2778:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2779:     return $total;
 2780: }
 2781: 
 2782: # ------------------------------------------------------- Validate an accesskey
 2783: 
 2784: sub validate_access_key {
 2785:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2786:     $cdom=
 2787:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2788:     $cnum=
 2789:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2790:     $udom=$env{'user.domain'} unless (defined($udom));
 2791:     $uname=$env{'user.name'} unless (defined($uname));
 2792:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2793:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2794: }
 2795: 
 2796: # ------------------------------------- Find the section of student in a course
 2797: sub devalidate_getsection_cache {
 2798:     my ($udom,$unam,$courseid)=@_;
 2799:     my $hashid="$udom:$unam:$courseid";
 2800:     &devalidate_cache_new('getsection',$hashid);
 2801: }
 2802: 
 2803: sub courseid_to_courseurl {
 2804:     my ($courseid) = @_;
 2805:     #already url style courseid
 2806:     return $courseid if ($courseid =~ m{^/});
 2807: 
 2808:     if (exists($env{'course.'.$courseid.'.num'})) {
 2809: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2810: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2811: 	return "/$cdom/$cnum";
 2812:     }
 2813: 
 2814:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2815:     if (exists($courseinfo{'num'})) {
 2816: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2817:     }
 2818: 
 2819:     return undef;
 2820: }
 2821: 
 2822: sub getsection {
 2823:     my ($udom,$unam,$courseid)=@_;
 2824:     my $cachetime=1800;
 2825: 
 2826:     my $hashid="$udom:$unam:$courseid";
 2827:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2828:     if (defined($cached)) { return $result; }
 2829: 
 2830:     my %Pending; 
 2831:     my %Expired;
 2832:     #
 2833:     # Each role can either have not started yet (pending), be active, 
 2834:     #    or have expired.
 2835:     #
 2836:     # If there is an active role, we are done.
 2837:     #
 2838:     # If there is more than one role which has not started yet, 
 2839:     #     choose the one which will start sooner
 2840:     # If there is one role which has not started yet, return it.
 2841:     #
 2842:     # If there is more than one expired role, choose the one which ended last.
 2843:     # If there is a role which has expired, return it.
 2844:     #
 2845:     $courseid = &courseid_to_courseurl($courseid);
 2846:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2847:     foreach my $key (keys(%roleshash)) {
 2848:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2849:         my $section=$1;
 2850:         if ($key eq $courseid.'_st') { $section=''; }
 2851:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2852:         my $now=time;
 2853:         if (defined($end) && $end && ($now > $end)) {
 2854:             $Expired{$end}=$section;
 2855:             next;
 2856:         }
 2857:         if (defined($start) && $start && ($now < $start)) {
 2858:             $Pending{$start}=$section;
 2859:             next;
 2860:         }
 2861:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2862:     }
 2863:     #
 2864:     # Presumedly there will be few matching roles from the above
 2865:     # loop and the sorting time will be negligible.
 2866:     if (scalar(keys(%Pending))) {
 2867:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2868:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2869:     } 
 2870:     if (scalar(keys(%Expired))) {
 2871:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2872:         my $time = pop(@sorted);
 2873:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2874:     }
 2875:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2876: }
 2877: 
 2878: sub save_cache {
 2879:     &purge_remembered();
 2880:     #&Apache::loncommon::validate_page();
 2881:     undef(%env);
 2882:     undef($env_loaded);
 2883: }
 2884: 
 2885: my $to_remember=-1;
 2886: my %remembered;
 2887: my %accessed;
 2888: my $kicks=0;
 2889: my $hits=0;
 2890: sub make_key {
 2891:     my ($name,$id) = @_;
 2892:     if (length($id) > 65 
 2893: 	&& length(&escape($id)) > 200) {
 2894: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2895:     }
 2896:     return &escape($name.':'.$id);
 2897: }
 2898: 
 2899: sub devalidate_cache_new {
 2900:     my ($name,$id,$debug) = @_;
 2901:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2902:     my $remembered_id=$name.':'.$id;
 2903:     $id=&make_key($name,$id);
 2904:     $memcache->delete($id);
 2905:     delete($remembered{$remembered_id});
 2906:     delete($accessed{$remembered_id});
 2907: }
 2908: 
 2909: sub is_cached_new {
 2910:     my ($name,$id,$debug) = @_;
 2911:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2912:     if (exists($remembered{$remembered_id})) {
 2913: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2914: 	$accessed{$remembered_id}=[&gettimeofday()];
 2915: 	$hits++;
 2916: 	return ($remembered{$remembered_id},1);
 2917:     }
 2918:     $id=&make_key($name,$id);
 2919:     my $value = $memcache->get($id);
 2920:     if (!(defined($value))) {
 2921: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2922: 	return (undef,undef);
 2923:     }
 2924:     if ($value eq '__undef__') {
 2925: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2926: 	$value=undef;
 2927:     }
 2928:     &make_room($remembered_id,$value,$debug);
 2929:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2930:     return ($value,1);
 2931: }
 2932: 
 2933: sub do_cache_new {
 2934:     my ($name,$id,$value,$time,$debug) = @_;
 2935:     my $remembered_id=$name.':'.$id;
 2936:     $id=&make_key($name,$id);
 2937:     my $setvalue=$value;
 2938:     if (!defined($setvalue)) {
 2939: 	$setvalue='__undef__';
 2940:     }
 2941:     if (!defined($time) ) {
 2942: 	$time=600;
 2943:     }
 2944:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2945:     my $result = $memcache->set($id,$setvalue,$time);
 2946:     if (! $result) {
 2947: 	&logthis("caching of id -> $id  failed");
 2948: 	$memcache->disconnect_all();
 2949:     }
 2950:     # need to make a copy of $value
 2951:     &make_room($remembered_id,$value,$debug);
 2952:     return $value;
 2953: }
 2954: 
 2955: sub make_room {
 2956:     my ($remembered_id,$value,$debug)=@_;
 2957: 
 2958:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2959:                                     : $value;
 2960:     if ($to_remember<0) { return; }
 2961:     $accessed{$remembered_id}=[&gettimeofday()];
 2962:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2963:     my $to_kick;
 2964:     my $max_time=0;
 2965:     foreach my $other (keys(%accessed)) {
 2966: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2967: 	    $to_kick=$other;
 2968: 	    $max_time=&tv_interval($accessed{$other});
 2969: 	}
 2970:     }
 2971:     delete($remembered{$to_kick});
 2972:     delete($accessed{$to_kick});
 2973:     $kicks++;
 2974:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2975:     return;
 2976: }
 2977: 
 2978: sub purge_remembered {
 2979:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2980:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2981:     undef(%remembered);
 2982:     undef(%accessed);
 2983: }
 2984: # ------------------------------------- Read an entry from a user's environment
 2985: 
 2986: sub userenvironment {
 2987:     my ($udom,$unam,@what)=@_;
 2988:     my $items;
 2989:     foreach my $item (@what) {
 2990:         $items.=&escape($item).'&';
 2991:     }
 2992:     $items=~s/\&$//;
 2993:     my %returnhash=();
 2994:     my $uhome = &homeserver($unam,$udom);
 2995:     unless ($uhome eq 'no_host') {
 2996:         my @answer=split(/\&/, 
 2997:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2998:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2999:             return %returnhash;
 3000:         }
 3001:         my $i;
 3002:         for ($i=0;$i<=$#what;$i++) {
 3003: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3004:         }
 3005:     }
 3006:     return %returnhash;
 3007: }
 3008: 
 3009: # ---------------------------------------------------------- Get a studentphoto
 3010: sub studentphoto {
 3011:     my ($udom,$unam,$ext) = @_;
 3012:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3013:     if (defined($env{'request.course.id'})) {
 3014:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3015:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3016:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3017:             } else {
 3018:                 my ($result,$perm_reqd)=
 3019: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3020:                 if ($result eq 'ok') {
 3021:                     if (!($perm_reqd eq 'yes')) {
 3022:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3023:                     }
 3024:                 }
 3025:             }
 3026:         }
 3027:     } else {
 3028:         my ($result,$perm_reqd) = 
 3029: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 3030:         if ($result eq 'ok') {
 3031:             if (!($perm_reqd eq 'yes')) {
 3032:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3033:             }
 3034:         }
 3035:     }
 3036:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3037: }
 3038: 
 3039: sub retrievestudentphoto {
 3040:     my ($udom,$unam,$ext,$type) = @_;
 3041:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 3042:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3043:     if ($ret eq 'ok') {
 3044:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3045:         if ($type eq 'thumbnail') {
 3046:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3047:         }
 3048:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 3049:         return $tokenurl;
 3050:     } else {
 3051:         if ($type eq 'thumbnail') {
 3052:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3053:         } else { 
 3054:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3055:         }
 3056:     }
 3057: }
 3058: 
 3059: # -------------------------------------------------------------------- New chat
 3060: 
 3061: sub chatsend {
 3062:     my ($newentry,$anon,$group)=@_;
 3063:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3064:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3065:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3066:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3067: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3068: 		   &escape($newentry)).':'.$group,$chome);
 3069: }
 3070: 
 3071: # ------------------------------------------ Find current version of a resource
 3072: 
 3073: sub getversion {
 3074:     my $fname=&clutter(shift);
 3075:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3076:     return &currentversion(&filelocation('',$fname));
 3077: }
 3078: 
 3079: sub currentversion {
 3080:     my $fname=shift;
 3081:     my $author=$fname;
 3082:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3083:     my ($udom,$uname)=split(/\//,$author);
 3084:     my $home=&homeserver($uname,$udom);
 3085:     if ($home eq 'no_host') { 
 3086:         return -1; 
 3087:     }
 3088:     my $answer=&reply("currentversion:$fname",$home);
 3089:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3090: 	return -1;
 3091:     }
 3092:     return $answer;
 3093: }
 3094: 
 3095: #
 3096: # Return special version number of resource if set by override, empty otherwise
 3097: #
 3098: sub usedversion {
 3099:     my $fname=shift;
 3100:     unless ($fname) { $fname=$env{'request.uri'}; }
 3101:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3102:     if ($urlversion) { return $urlversion; }
 3103:     return '';
 3104: }
 3105: 
 3106: # ----------------------------- Subscribe to a resource, return URL if possible
 3107: 
 3108: sub subscribe {
 3109:     my $fname=shift;
 3110:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3111:     $fname=~s/[\n\r]//g;
 3112:     my $author=$fname;
 3113:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3114:     my ($udom,$uname)=split(/\//,$author);
 3115:     my $home=homeserver($uname,$udom);
 3116:     if ($home eq 'no_host') {
 3117:         return 'not_found';
 3118:     }
 3119:     my $answer=reply("sub:$fname",$home);
 3120:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3121: 	$answer.=' by '.$home;
 3122:     }
 3123:     return $answer;
 3124: }
 3125:     
 3126: # -------------------------------------------------------------- Replicate file
 3127: 
 3128: sub repcopy {
 3129:     my $filename=shift;
 3130:     $filename=~s/\/+/\//g;
 3131:     my $londocroot = $perlvar{'lonDocRoot'};
 3132:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3133:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3134:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3135: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3136: 	return &repcopy_userfile($filename);
 3137:     }
 3138:     $filename=~s/[\n\r]//g;
 3139:     my $transname="$filename.in.transfer";
 3140: # FIXME: this should flock
 3141:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3142:     my $remoteurl=subscribe($filename);
 3143:     if ($remoteurl =~ /^con_lost by/) {
 3144: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3145:            return 'unavailable';
 3146:     } elsif ($remoteurl eq 'not_found') {
 3147: 	   #&logthis("Subscribe returned not_found: $filename");
 3148: 	   return 'not_found';
 3149:     } elsif ($remoteurl =~ /^rejected by/) {
 3150: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3151:            return 'forbidden';
 3152:     } elsif ($remoteurl eq 'directory') {
 3153:            return 'ok';
 3154:     } else {
 3155:         my $author=$filename;
 3156:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3157:         my ($udom,$uname)=split(/\//,$author);
 3158:         my $home=homeserver($uname,$udom);
 3159:         unless ($home eq $perlvar{'lonHostID'}) {
 3160:            my @parts=split(/\//,$filename);
 3161:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3162:            if ($path ne "$londocroot/res") {
 3163:                &logthis("Malconfiguration for replication: $filename");
 3164: 	       return 'bad_request';
 3165:            }
 3166:            my $count;
 3167:            for ($count=5;$count<$#parts;$count++) {
 3168:                $path.="/$parts[$count]";
 3169:                if ((-e $path)!=1) {
 3170: 		   mkdir($path,0777);
 3171:                }
 3172:            }
 3173:            my $request=new HTTP::Request('GET',"$remoteurl");
 3174:            my $response;
 3175:            if ($remoteurl =~ m{/raw/}) {
 3176:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3177:            } else {
 3178:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3179:            }
 3180:            if ($response->is_error()) {
 3181: 	       unlink($transname);
 3182:                my $message=$response->status_line;
 3183:                &logthis("<font color=\"blue\">WARNING:"
 3184:                        ." LWP get: $message: $filename</font>");
 3185:                return 'unavailable';
 3186:            } else {
 3187: 	       if ($remoteurl!~/\.meta$/) {
 3188:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3189:                   my $mresponse;
 3190:                   if ($remoteurl =~ m{/raw/}) {
 3191:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3192:                   } else {
 3193:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3194:                   }
 3195:                   if ($mresponse->is_error()) {
 3196: 		      unlink($filename.'.meta');
 3197:                       &logthis(
 3198:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3199:                   }
 3200: 	       }
 3201:                rename($transname,$filename);
 3202:                return 'ok';
 3203:            }
 3204:        }
 3205:     }
 3206: }
 3207: 
 3208: # ------------------------------------------------ Get server side include body
 3209: sub ssi_body {
 3210:     my ($filelink,%form)=@_;
 3211:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3212:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3213:     }
 3214:     my $output='';
 3215:     my $response;
 3216:     if ($filelink=~/^https?\:/) {
 3217:        ($output,$response)=&externalssi($filelink);
 3218:     } else {
 3219:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3220:        $filelink .= 'inhibitmenu=yes';
 3221:        ($output,$response)=&ssi($filelink,%form);
 3222:     }
 3223:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3224:     $output=~s/^.*?\<body[^\>]*\>//si;
 3225:     $output=~s/\<\/body\s*\>.*?$//si;
 3226:     if (wantarray) {
 3227:         return ($output, $response);
 3228:     } else {
 3229:         return $output;
 3230:     }
 3231: }
 3232: 
 3233: # --------------------------------------------------------- Server Side Include
 3234: 
 3235: sub absolute_url {
 3236:     my ($host_name) = @_;
 3237:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3238:     if ($host_name eq '') {
 3239: 	$host_name = $ENV{'SERVER_NAME'};
 3240:     }
 3241:     return $protocol.$host_name;
 3242: }
 3243: 
 3244: #
 3245: #   Server side include.
 3246: # Parameters:
 3247: #  fn     Possibly encrypted resource name/id.
 3248: #  form   Hash that describes how the rendering should be done
 3249: #         and other things.
 3250: # Returns:
 3251: #   Scalar context: The content of the response.
 3252: #   Array context:  2 element list of the content and the full response object.
 3253: #     
 3254: sub ssi {
 3255: 
 3256:     my ($fn,%form)=@_;
 3257:     my $request;
 3258: 
 3259:     $form{'no_update_last_known'}=1;
 3260:     &Apache::lonenc::check_encrypt(\$fn);
 3261:     if (%form) {
 3262:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3263:       $request->content(join('&',map { 
 3264:             my $name = escape($_);
 3265:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3266:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3267:             : &escape($form{$_}) );    
 3268:         } keys(%form)));
 3269:     } else {
 3270:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3271:     }
 3272: 
 3273:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3274:     my $lonhost = $perlvar{'lonHostID'};
 3275:     my $islocal;
 3276:     if (($env{'request.course.id'}) &&
 3277:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3278:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3279:         ($form{'grade_symb'} ne '') &&
 3280:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3281:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3282:         $islocal = 1;
 3283:     }
 3284:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3285:                                                 '','','',$islocal);
 3286: 
 3287:     if (wantarray) {
 3288: 	return ($response->content, $response);
 3289:     } else {
 3290: 	return $response->content;
 3291:     }
 3292: }
 3293: 
 3294: sub externalssi {
 3295:     my ($url)=@_;
 3296:     my $request=new HTTP::Request('GET',$url);
 3297:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3298:     if (wantarray) {
 3299:         return ($response->content, $response);
 3300:     } else {
 3301:         return $response->content;
 3302:     }
 3303: }
 3304: 
 3305: 
 3306: # If the local copy of a replicated resource is outdated, trigger a  
 3307: # connection from the homeserver to flush the delayed queue. If no update 
 3308: # happens, remove local copies of outdated resource (and corresponding
 3309: # metadata file).
 3310: 
 3311: sub remove_stale_resfile {
 3312:     my ($url) = @_;
 3313:     my $removed;
 3314:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3315:         my $audom = $1;
 3316:         my $auname = $2;
 3317:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3318:             my $homeserver = &homeserver($auname,$audom);
 3319:             unless (($homeserver eq 'no_host') ||
 3320:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3321:                 my $fname = &filelocation('',$url);
 3322:                 if (-e $fname) {
 3323:                     my $protocol = $protocol{$homeserver};
 3324:                     $protocol = 'http' if ($protocol ne 'https');
 3325:                     my $hostname = &hostname($homeserver);
 3326:                     if ($hostname) {
 3327:                         my $uri = &declutter($url);
 3328:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3329:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3330:                         if ($response->is_success()) {
 3331:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3332:                             my $locmodtime = (stat($fname))[9];
 3333:                             if ($locmodtime < $remmodtime) {
 3334:                                 my $stale;
 3335:                                 my $answer = &reply('pong',$homeserver);
 3336:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3337:                                     sleep(0.2);
 3338:                                     $locmodtime = (stat($fname))[9];
 3339:                                     if ($locmodtime < $remmodtime) {
 3340:                                         my $posstransfer = $fname.'.in.transfer';
 3341:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3342:                                             $removed = 1;
 3343:                                         } else {
 3344:                                             $stale = 1;
 3345:                                         }
 3346:                                     } else {
 3347:                                         $removed = 1;
 3348:                                     }
 3349:                                 } else {
 3350:                                     $stale = 1;
 3351:                                 }
 3352:                                 if ($stale) {
 3353:                                     unlink($fname);
 3354:                                     if ($uri!~/\.meta$/) {
 3355:                                         unlink($fname.'.meta');
 3356:                                     }
 3357:                                     &reply("unsub:$fname",$homeserver);
 3358:                                     $removed = 1;
 3359:                                 }
 3360:                             }
 3361:                         }
 3362:                     }
 3363:                 }
 3364:             }
 3365:         }
 3366:     }
 3367:     return $removed;
 3368: }
 3369: 
 3370: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3371: 
 3372: sub allowuploaded {
 3373:     my ($srcurl,$url)=@_;
 3374:     $url=&clutter(&declutter($url));
 3375:     my $dir=$url;
 3376:     $dir=~s/\/[^\/]+$//;
 3377:     my %httpref=();
 3378:     my $httpurl=&hreflocation('',$url);
 3379:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3380:     &Apache::lonnet::appenv(\%httpref);
 3381: }
 3382: 
 3383: #
 3384: # Determine if the current user should be able to edit a particular resource,
 3385: # when viewing in course context.
 3386: # (a) When viewing resource used to determine if "Edit" item is included in 
 3387: #     Functions.
 3388: # (b) When displaying folder contents in course editor, used to determine if
 3389: #     "Edit" link will be displayed alongside resource.
 3390: #
 3391: #  input: six args -- filename (decluttered), course number, course domain,
 3392: #                   url, symb (if registered) and group (if this is a group
 3393: #                   item -- e.g., bulletin board, group page etc.).
 3394: #  output: array of five scalars -- 
 3395: #          $cfile -- url for file editing if editable on current server
 3396: #          $home -- homeserver of resource (i.e., for author if published,
 3397: #                                           or course if uploaded.).
 3398: #          $switchserver --  1 if server switch will be needed.
 3399: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3400: #          $forceview -- 1 if icon/link should be to go to view mode
 3401: #
 3402: 
 3403: sub can_edit_resource {
 3404:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3405:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3406: #
 3407: # For aboutme pages user can only edit his/her own.
 3408: #
 3409:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3410:         my ($sdom,$sname) = ($1,$2);
 3411:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3412:             $home = $env{'user.home'};
 3413:             $cfile = $resurl;
 3414:             if ($env{'form.forceedit'}) {
 3415:                 $forceview = 1;
 3416:             } else {
 3417:                 $forceedit = 1;
 3418:             }
 3419:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3420:         } else {
 3421:             return;
 3422:         }
 3423:     }
 3424: 
 3425:     if ($env{'request.course.id'}) {
 3426:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3427:         if ($group ne '') {
 3428: # if this is a group homepage or group bulletin board, check group privs
 3429:             my $allowed = 0;
 3430:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3431:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3432:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3433:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3434:                     $allowed = 1;
 3435:                 }
 3436:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3437:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3438:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3439:                     $allowed = 1;
 3440:                 }
 3441:             }
 3442:             if ($allowed) {
 3443:                 $home=&homeserver($cnum,$cdom);
 3444:                 if ($env{'form.forceedit'}) {
 3445:                     $forceview = 1;
 3446:                 } else {
 3447:                     $forceedit = 1;
 3448:                 }
 3449:                 $cfile = $resurl;
 3450:             } else {
 3451:                 return;
 3452:             }
 3453:         } else {
 3454:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3455:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3456:                     return;
 3457:                 }
 3458:             } elsif (!$crsedit) {
 3459: #
 3460: # No edit allowed where CC has switched to student role.
 3461: #
 3462:                 return;
 3463:             }
 3464:         }
 3465:     }
 3466: 
 3467:     if ($file ne '') {
 3468:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3469:             if (&is_course_upload($file,$cnum,$cdom)) {
 3470:                 $uploaded = 1;
 3471:                 $incourse = 1;
 3472:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3473:                     $cfile = &hreflocation('',$file);
 3474:                     if ($env{'form.forceedit'}) {
 3475:                         $forceview = 1;
 3476:                     } else {
 3477:                         $forceedit = 1;
 3478:                     }
 3479:                 }
 3480:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3481:                 $incourse = 1;
 3482:                 if ($env{'form.forceedit'}) {
 3483:                     $forceview = 1;
 3484:                 } else {
 3485:                     $forceedit = 1;
 3486:                 }
 3487:                 $cfile = $resurl;
 3488:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3489:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3490:                     $incourse = 1;
 3491:                     if ($env{'form.forceedit'}) {
 3492:                         $forceview = 1;
 3493:                     } else {
 3494:                         $forceedit = 1;
 3495:                     }
 3496:                     $cfile = $resurl;
 3497:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3498:                     $incourse = 1;
 3499:                     $cfile = $resurl.'/smpedit';
 3500:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3501:                     $incourse = 1;
 3502:                     if ($env{'form.forceedit'}) {
 3503:                         $forceview = 1;
 3504:                     } else {
 3505:                         $forceedit = 1;
 3506:                     }
 3507:                     $cfile = $resurl;
 3508:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3509:                     $incourse = 1;
 3510:                     if ($env{'form.forceedit'}) {
 3511:                         $forceview = 1;
 3512:                     } else {
 3513:                         $forceedit = 1;
 3514:                     }
 3515:                     $cfile = $resurl;
 3516:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3517:                     $incourse = 1;
 3518:                     if ($env{'form.forceedit'}) {
 3519:                         $forceview = 1;
 3520:                     } else {
 3521:                         $forceedit = 1;
 3522:                     }
 3523:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3524:                 }
 3525:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3526:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3527:                 if (&is_on_map($template)) { 
 3528:                     $incourse = 1;
 3529:                     $forceview = 1;
 3530:                     $cfile = $template;
 3531:                 }
 3532:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3533:                     $incourse = 1;
 3534:                     if ($env{'form.forceedit'}) {
 3535:                         $forceview = 1;
 3536:                     } else {
 3537:                         $forceedit = 1;
 3538:                     }
 3539:                     $cfile = $resurl;
 3540:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3541:                 $incourse = 1;
 3542:                 if ($env{'form.forceedit'}) {
 3543:                     $forceview = 1;
 3544:                 } else {
 3545:                     $forceedit = 1;
 3546:                 }
 3547:                 $cfile = $resurl;
 3548:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3549:                 $incourse = 1;
 3550:                 $forceview = 1;
 3551:                 if ($symb) {
 3552:                     my ($map,$id,$res)=&decode_symb($symb);
 3553:                     $env{'request.symb'} = $symb;
 3554:                     $cfile = &clutter($res);
 3555:                 } else {
 3556:                     $cfile = $env{'form.suppurl'};
 3557:                     my $escfile = &unescape($cfile);
 3558:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3559:                         $cfile = '/adm/wrapper'.$escfile;
 3560:                     } else {
 3561:                         $escfile =~ s{^http://}{};
 3562:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3563:                     }
 3564:                 }
 3565:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3566:                 if ($env{'form.forceedit'}) {
 3567:                     $forceview = 1;
 3568:                 } else {
 3569:                     $forceedit = 1;
 3570:                 }
 3571:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3572:             }
 3573:         }
 3574:         if ($uploaded || $incourse) {
 3575:             $home=&homeserver($cnum,$cdom);
 3576:         } elsif ($file !~ m{/$}) {
 3577:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3578:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3579:             # Check that the user has permission to edit this resource
 3580:             my $setpriv = 1;
 3581:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3582:             if (defined($cfudom)) {
 3583:                 $home=&homeserver($cfuname,$cfudom);
 3584:                 $cfile=$file;
 3585:             }
 3586:         }
 3587:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3588:             (($home ne '') && ($home ne 'no_host'))) {
 3589:             my @ids=&current_machine_ids();
 3590:             unless (grep(/^\Q$home\E$/,@ids)) {
 3591:                 $switchserver=1;
 3592:             }
 3593:         }
 3594:     }
 3595:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3596: }
 3597: 
 3598: sub is_course_upload {
 3599:     my ($file,$cnum,$cdom) = @_;
 3600:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3601:     $uploadpath =~ s{^\/}{};
 3602:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3603:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3604:         return 1;
 3605:     }
 3606:     return;
 3607: }
 3608: 
 3609: sub in_course {
 3610:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3611:     if ($hideprivileged) {
 3612:         my $skipuser;
 3613:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3614:         my @possdoms = ($cdom);  
 3615:         if ($coursehash{'checkforpriv'}) { 
 3616:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3617:         }
 3618:         if (&privileged($uname,$udom,\@possdoms)) {
 3619:             $skipuser = 1;
 3620:             if ($coursehash{'nothideprivileged'}) {
 3621:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3622:                     my $user;
 3623:                     if ($item =~ /:/) {
 3624:                         $user = $item;
 3625:                     } else {
 3626:                         $user = join(':',split(/[\@]/,$item));
 3627:                     }
 3628:                     if ($user eq $uname.':'.$udom) {
 3629:                         undef($skipuser);
 3630:                         last;
 3631:                     }
 3632:                 }
 3633:             }
 3634:             if ($skipuser) {
 3635:                 return 0;
 3636:             }
 3637:         }
 3638:     }
 3639:     $type ||= 'any';
 3640:     if (!defined($cdom) || !defined($cnum)) {
 3641:         my $cid  = $env{'request.course.id'};
 3642:         $cdom = $env{'course.'.$cid.'.domain'};
 3643:         $cnum = $env{'course.'.$cid.'.num'};
 3644:     }
 3645:     my $typesref;
 3646:     if (($type eq 'any') || ($type eq 'all')) {
 3647:         $typesref = ['active','previous','future'];
 3648:     } elsif ($type eq 'previous' || $type eq 'future') {
 3649:         $typesref = [$type];
 3650:     }
 3651:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3652:                               $typesref,undef,[$cdom]);
 3653:     my ($tmp) = keys(%roles);
 3654:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3655:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3656:     if (@course_roles > 0) {
 3657:         return 1;
 3658:     }
 3659:     return 0;
 3660: }
 3661: 
 3662: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3663: # input: action, courseID, current domain, intended
 3664: #        path to file, source of file, instruction to parse file for objects,
 3665: #        ref to hash for embedded objects,
 3666: #        ref to hash for codebase of java objects.
 3667: #        reference to scalar to accommodate mime type determined
 3668: #          from File::MMagic if $parser = parse.
 3669: #
 3670: # output: url to file (if action was uploaddoc), 
 3671: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3672: #
 3673: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3674: # course.
 3675: #
 3676: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3677: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3678: #          course's home server.
 3679: #
 3680: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3681: #          be copied from $source (current location) to 
 3682: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3683: #         and will then be copied to
 3684: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3685: #         course's home server.
 3686: #
 3687: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3688: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3689: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3690: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3691: #         in course's home server.
 3692: #
 3693: 
 3694: sub process_coursefile {
 3695:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3696:         $mimetype)=@_;
 3697:     my $fetchresult;
 3698:     my $home=&homeserver($docuname,$docudom);
 3699:     if ($action eq 'propagate') {
 3700:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3701: 			     $home);
 3702:     } else {
 3703:         my $fpath = '';
 3704:         my $fname = $file;
 3705:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3706:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3707:         my $filepath = &build_filepath($fpath);
 3708:         if ($action eq 'copy') {
 3709:             if ($source eq '') {
 3710:                 $fetchresult = 'no source file';
 3711:                 return $fetchresult;
 3712:             } else {
 3713:                 my $destination = $filepath.'/'.$fname;
 3714:                 rename($source,$destination);
 3715:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3716:                                  $home);
 3717:             }
 3718:         } elsif ($action eq 'uploaddoc') {
 3719:             open(my $fh,'>',$filepath.'/'.$fname);
 3720:             print $fh $env{'form.'.$source};
 3721:             close($fh);
 3722:             if ($parser eq 'parse') {
 3723:                 my $mm = new File::MMagic;
 3724:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3725:                 if ($type eq 'text/html') {
 3726:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3727:                     unless ($parse_result eq 'ok') {
 3728:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3729:                     }
 3730:                 }
 3731:                 if (ref($mimetype)) {
 3732:                     $$mimetype = $type;
 3733:                 } 
 3734:             }
 3735:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3736:                                  $home);
 3737:             if ($fetchresult eq 'ok') {
 3738:                 return '/uploaded/'.$fpath.'/'.$fname;
 3739:             } else {
 3740:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3741:                         ' to host '.$home.': '.$fetchresult);
 3742:                 return '/adm/notfound.html';
 3743:             }
 3744:         }
 3745:     }
 3746:     unless ( $fetchresult eq 'ok') {
 3747:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3748:              ' to host '.$home.': '.$fetchresult);
 3749:     }
 3750:     return $fetchresult;
 3751: }
 3752: 
 3753: sub build_filepath {
 3754:     my ($fpath) = @_;
 3755:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3756:     unless ($fpath eq '') {
 3757:         my @parts=split('/',$fpath);
 3758:         foreach my $part (@parts) {
 3759:             $filepath.= '/'.$part;
 3760:             if ((-e $filepath)!=1) {
 3761:                 mkdir($filepath,0777);
 3762:             }
 3763:         }
 3764:     }
 3765:     return $filepath;
 3766: }
 3767: 
 3768: sub store_edited_file {
 3769:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3770:     my $file = $primary_url;
 3771:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3772:     my $fpath = '';
 3773:     my $fname = $file;
 3774:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3775:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3776:     my $filepath = &build_filepath($fpath);
 3777:     open(my $fh,'>',$filepath.'/'.$fname);
 3778:     print $fh $content;
 3779:     close($fh);
 3780:     my $home=&homeserver($docuname,$docudom);
 3781:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3782: 			  $home);
 3783:     if ($$fetchresult eq 'ok') {
 3784:         return '/uploaded/'.$fpath.'/'.$fname;
 3785:     } else {
 3786:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3787: 		 ' to host '.$home.': '.$$fetchresult);
 3788:         return '/adm/notfound.html';
 3789:     }
 3790: }
 3791: 
 3792: sub clean_filename {
 3793:     my ($fname,$args)=@_;
 3794: # Replace Windows backslashes by forward slashes
 3795:     $fname=~s/\\/\//g;
 3796:     if (!$args->{'keep_path'}) {
 3797:         # Get rid of everything but the actual filename
 3798: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3799:     }
 3800: # Replace spaces by underscores
 3801:     $fname=~s/\s+/\_/g;
 3802: # Replace all other weird characters by nothing
 3803:     $fname=~s{[^/\w\.\-]}{}g;
 3804: # Replace all .\d. sequences with _\d. so they no longer look like version
 3805: # numbers
 3806:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3807:     return $fname;
 3808: }
 3809: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3810: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3811: # image with the same aspect ratio as the original, but with dimensions which do 
 3812: # not exceed $resizewidth and $resizeheight.
 3813:  
 3814: sub resizeImage {
 3815:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3816:     my $ima = Image::Magick->new;
 3817:     my $resized;
 3818:     if (-e $img_path) {
 3819:         $ima->Read($img_path);
 3820:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3821:             my $width = $ima->Get('width');
 3822:             my $height = $ima->Get('height');
 3823:             if ($width > $resizewidth) {
 3824: 	        my $factor = $width/$resizewidth;
 3825:                 my $newheight = $height/$factor;
 3826:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3827:                 $resized = 1;
 3828:             }
 3829:         }
 3830:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3831:             my $width = $ima->Get('width');
 3832:             my $height = $ima->Get('height');
 3833:             if ($height > $resizeheight) {
 3834:                 my $factor = $height/$resizeheight;
 3835:                 my $newwidth = $width/$factor;
 3836:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3837:                 $resized = 1;
 3838:             }
 3839:         }
 3840:         if ($resized) {
 3841:             $ima->Write($img_path);
 3842:         }
 3843:     }
 3844:     return;
 3845: }
 3846: 
 3847: # --------------- Take an uploaded file and put it into the userfiles directory
 3848: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3849: #                    the desired filename is in $env{"form.$formname.filename"}
 3850: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3851: #                                    canceloverwrite, or ''. 
 3852: #                   if 'coursedoc': upload to the current course
 3853: #                   if 'existingfile': write file to tmp/overwrites directory 
 3854: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3855: #                   $context is passed as argument to &finishuserfileupload
 3856: #        $subdir - directory in userfile to store the file into
 3857: #        $parser - instruction to parse file for objects ($parser = parse)    
 3858: #        $allfiles - reference to hash for embedded objects
 3859: #        $codebase - reference to hash for codebase of java objects
 3860: #        $desuname - username for permanent storage of uploaded file
 3861: #        $dsetudom - domain for permanaent storage of uploaded file
 3862: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3863: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3864: #        $resizewidth - width (pixels) to which to resize uploaded image
 3865: #        $resizeheight - height (pixels) to which to resize uploaded image
 3866: #        $mimetype - reference to scalar to accommodate mime type determined
 3867: #                    from File::MMagic.
 3868: # 
 3869: # output: url of file in userspace, or error: <message> 
 3870: #             or /adm/notfound.html if failure to upload occurse
 3871: 
 3872: sub userfileupload {
 3873:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3874:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3875:     if (!defined($subdir)) { $subdir='unknown'; }
 3876:     my $fname=$env{'form.'.$formname.'.filename'};
 3877:     $fname=&clean_filename($fname);
 3878:     # See if there is anything left
 3879:     unless ($fname) { return 'error: no uploaded file'; }
 3880:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3881:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3882:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3883:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3884:         my $now = time;
 3885:         my $filepath;
 3886:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3887:              $filepath = 'tmp/helprequests/'.$now;
 3888:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3889:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3890:                          '_'.$env{'user.domain'}.'/pending';
 3891:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3892:             my ($docuname,$docudom);
 3893:             if ($destudom =~ /^$match_domain$/) {
 3894:                 $docudom = $destudom;
 3895:             } else {
 3896:                 $docudom = $env{'user.domain'};
 3897:             }
 3898:             if ($destuname =~ /^$match_username$/) {
 3899:                 $docuname = $destuname;
 3900:             } else {
 3901:                 $docuname = $env{'user.name'};
 3902:             }
 3903:             if (exists($env{'form.group'})) {
 3904:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3905:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3906:             }
 3907:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3908:             if ($context eq 'canceloverwrite') {
 3909:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3910:                 if (-e  $tempfile) {
 3911:                     my @info = stat($tempfile);
 3912:                     if ($info[9] eq $env{'form.timestamp'}) {
 3913:                         unlink($tempfile);
 3914:                     }
 3915:                 }
 3916:                 return;
 3917:             }
 3918:         }
 3919:         # Create the directory if not present
 3920:         my @parts=split(/\//,$filepath);
 3921:         my $fullpath = $perlvar{'lonDaemons'};
 3922:         for (my $i=0;$i<@parts;$i++) {
 3923:             $fullpath .= '/'.$parts[$i];
 3924:             if ((-e $fullpath)!=1) {
 3925:                 mkdir($fullpath,0777);
 3926:             }
 3927:         }
 3928:         open(my $fh,'>',$fullpath.'/'.$fname);
 3929:         print $fh $env{'form.'.$formname};
 3930:         close($fh);
 3931:         if ($context eq 'existingfile') {
 3932:             my @info = stat($fullpath.'/'.$fname);
 3933:             return ($fullpath.'/'.$fname,$info[9]);
 3934:         } else {
 3935:             return $fullpath.'/'.$fname;
 3936:         }
 3937:     }
 3938:     if ($subdir eq 'scantron') {
 3939:         $fname = 'scantron_orig_'.$fname;
 3940:     } else {
 3941:         $fname="$subdir/$fname";
 3942:     }
 3943:     if ($context eq 'coursedoc') {
 3944: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3945: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3946:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3947:             return &finishuserfileupload($docuname,$docudom,
 3948: 					 $formname,$fname,$parser,$allfiles,
 3949: 					 $codebase,$thumbwidth,$thumbheight,
 3950:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3951:         } else {
 3952:             if ($env{'form.folder'}) {
 3953:                 $fname=$env{'form.folder'}.'/'.$fname;
 3954:             }
 3955:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3956: 				       $fname,$formname,$parser,
 3957: 				       $allfiles,$codebase,$mimetype);
 3958:         }
 3959:     } elsif (defined($destuname)) {
 3960:         my $docuname=$destuname;
 3961:         my $docudom=$destudom;
 3962: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3963: 				     $parser,$allfiles,$codebase,
 3964:                                      $thumbwidth,$thumbheight,
 3965:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3966:     } else {
 3967:         my $docuname=$env{'user.name'};
 3968:         my $docudom=$env{'user.domain'};
 3969:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3970:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3971:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3972:         }
 3973: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3974: 				     $parser,$allfiles,$codebase,
 3975:                                      $thumbwidth,$thumbheight,
 3976:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3977:     }
 3978: }
 3979: 
 3980: sub finishuserfileupload {
 3981:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3982:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3983:     my $path=$docudom.'/'.$docuname.'/';
 3984:     my $filepath=$perlvar{'lonDocRoot'};
 3985:   
 3986:     my ($fnamepath,$file,$fetchthumb);
 3987:     $file=$fname;
 3988:     if ($fname=~m|/|) {
 3989:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3990: 	$path.=$fnamepath.'/';
 3991:     }
 3992:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3993:     my $count;
 3994:     for ($count=4;$count<=$#parts;$count++) {
 3995:         $filepath.="/$parts[$count]";
 3996:         if ((-e $filepath)!=1) {
 3997: 	    mkdir($filepath,0777);
 3998:         }
 3999:     }
 4000: 
 4001: # Save the file
 4002:     {
 4003: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4004: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4005: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4006: 	    return '/adm/notfound.html';
 4007: 	}
 4008:         if ($context eq 'overwrite') {
 4009:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4010:             my $target = $filepath.'/'.$file;
 4011:             if (-e $source) {
 4012:                 my @info = stat($source);
 4013:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4014:                     unless (&File::Copy::move($source,$target)) {
 4015:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4016:                         return "Moving from $source failed";
 4017:                     }
 4018:                 } else {
 4019:                     return "Temporary file: $source had unexpected date/time for last modification";
 4020:                 }
 4021:             } else {
 4022:                 return "Temporary file: $source missing";
 4023:             }
 4024:         } elsif (!print FH ($env{'form.'.$formname})) {
 4025: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4026: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4027: 	    return '/adm/notfound.html';
 4028: 	}
 4029: 	close(FH);
 4030:         if ($resizewidth && $resizeheight) {
 4031:             my $mm = new File::MMagic;
 4032:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4033:             if ($mime_type =~ m{^image/}) {
 4034: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4035:             }  
 4036: 	}
 4037:     }
 4038:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4039:         if (ref($mimetype)) {
 4040:             if ($$mimetype eq '') {
 4041:                 my $mm = new File::MMagic;
 4042:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4043:                 $$mimetype = $type;
 4044:             }
 4045:         }
 4046:     }
 4047:     if ($parser eq 'parse') {
 4048:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4049:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4050:                                                        $allfiles,$codebase);
 4051:             unless ($parse_result eq 'ok') {
 4052:                 &logthis('Failed to parse '.$filepath.$file.
 4053: 	   	         ' for embedded media: '.$parse_result); 
 4054:             }
 4055:         }
 4056:     }
 4057:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4058:         my $input = $filepath.'/'.$file;
 4059:         my $output = $filepath.'/'.'tn-'.$file;
 4060:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4061:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4062:         system({$args[0]} @args);
 4063:         if (-e $filepath.'/'.'tn-'.$file) {
 4064:             $fetchthumb  = 1; 
 4065:         }
 4066:     }
 4067:  
 4068: # Notify homeserver to grep it
 4069: #
 4070:     my $docuhome=&homeserver($docuname,$docudom);	
 4071:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4072:     if ($fetchresult eq 'ok') {
 4073:         if ($fetchthumb) {
 4074:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4075:             if ($thumbresult ne 'ok') {
 4076:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4077:                          $docuhome.': '.$thumbresult);
 4078:             }
 4079:         }
 4080: #
 4081: # Return the URL to it
 4082:         return '/uploaded/'.$path.$file;
 4083:     } else {
 4084:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4085: 		 ': '.$fetchresult);
 4086:         return '/adm/notfound.html';
 4087:     }
 4088: }
 4089: 
 4090: sub extract_embedded_items {
 4091:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4092:     my @state = ();
 4093:     my (%lastids,%related,%shockwave,%flashvars);
 4094:     my %javafiles = (
 4095:                       codebase => '',
 4096:                       code => '',
 4097:                       archive => ''
 4098:                     );
 4099:     my %mediafiles = (
 4100:                       src => '',
 4101:                       movie => '',
 4102:                      );
 4103:     my $p;
 4104:     if ($content) {
 4105:         $p = HTML::LCParser->new($content);
 4106:     } else {
 4107:         $p = HTML::LCParser->new($fullpath);
 4108:     }
 4109:     while (my $t=$p->get_token()) {
 4110: 	if ($t->[0] eq 'S') {
 4111: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4112: 	    push(@state, $tagname);
 4113:             if (lc($tagname) eq 'allow') {
 4114:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4115:             }
 4116: 	    if (lc($tagname) eq 'img') {
 4117: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4118: 	    }
 4119: 	    if (lc($tagname) eq 'a') {
 4120:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4121:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4122:                 }
 4123: 	    }
 4124:             if (lc($tagname) eq 'script') {
 4125:                 my $src;
 4126:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4127:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4128:                 } else {
 4129:                     if ($attr->{'src'} ne '') {
 4130:                         $src = $attr->{'src'};
 4131:                         &add_filetype($allfiles,$src,'src');
 4132:                     }
 4133:                 }
 4134:                 my $text = $p->get_trimmed_text();
 4135:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4136:                     my @swfargs = split(/,/,$1);
 4137:                     foreach my $item (@swfargs) {
 4138:                         $item =~ s/["']//g;
 4139:                         $item =~ s/^\s+//;
 4140:                         $item =~ s/\s+$//;
 4141:                     }
 4142:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4143:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4144:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4145:                         } else {
 4146:                             $related{$swfargs[0]} = [$swfargs[2]];
 4147:                         }
 4148:                     }
 4149:                 }
 4150:             }
 4151:             if (lc($tagname) eq 'link') {
 4152:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4153:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4154:                 }
 4155:             }
 4156: 	    if (lc($tagname) eq 'object' ||
 4157: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4158: 		foreach my $item (keys(%javafiles)) {
 4159: 		    $javafiles{$item} = '';
 4160: 		}
 4161:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4162:                     $lastids{lc($tagname)} = $attr->{'id'};
 4163:                 }
 4164: 	    }
 4165: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4166: 		my $name = lc($attr->{'name'});
 4167: 		foreach my $item (keys(%javafiles)) {
 4168: 		    if ($name eq $item) {
 4169: 			$javafiles{$item} = $attr->{'value'};
 4170: 			last;
 4171: 		    }
 4172: 		}
 4173:                 my $pathfrom;
 4174: 		foreach my $item (keys(%mediafiles)) {
 4175: 		    if ($name eq $item) {
 4176:                         $pathfrom = $attr->{'value'};
 4177:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4178: 			&add_filetype($allfiles,$pathfrom,$name);
 4179: 			last;
 4180: 		    }
 4181: 		}
 4182:                 if ($name eq 'flashvars') {
 4183:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4184:                 }
 4185:                 if ($pathfrom ne '') {
 4186:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4187:                                          $pathfrom);
 4188:                 }
 4189: 	    }
 4190: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4191: 		foreach my $item (keys(%javafiles)) {
 4192: 		    if ($attr->{$item}) {
 4193: 			$javafiles{$item} = $attr->{$item};
 4194: 			last;
 4195: 		    }
 4196: 		}
 4197: 		foreach my $item (keys(%mediafiles)) {
 4198: 		    if ($attr->{$item}) {
 4199: 			&add_filetype($allfiles,$attr->{$item},$item);
 4200: 			last;
 4201: 		    }
 4202: 		}
 4203:                 if (lc($tagname) eq 'embed') {
 4204:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4205:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4206:                                              $attr->{'src'});
 4207:                     }
 4208:                 }
 4209: 	    }
 4210:             if (lc($tagname) eq 'iframe') {
 4211:                 my $src = $attr->{'src'} ;
 4212:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4213:                     &add_filetype($allfiles,$src,'src');
 4214:                 } elsif ($src =~ m{^/}) {
 4215:                     if ($env{'request.course.id'}) {
 4216:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4217:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4218:                         my $url = &hreflocation('',$fullpath);
 4219:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4220:                             my $relpath = $1;
 4221:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4222:                                 &add_filetype($allfiles,$1,'src');
 4223:                             }
 4224:                         }
 4225:                     }
 4226:                 }
 4227:             }
 4228:             if ($t->[4] =~ m{/>$}) {
 4229:                 pop(@state);
 4230:             }
 4231: 	} elsif ($t->[0] eq 'E') {
 4232: 	    my ($tagname) = ($t->[1]);
 4233: 	    if ($javafiles{'codebase'} ne '') {
 4234: 		$javafiles{'codebase'} .= '/';
 4235: 	    }  
 4236: 	    if (lc($tagname) eq 'applet' ||
 4237: 		lc($tagname) eq 'object' ||
 4238: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4239: 		) {
 4240: 		foreach my $item (keys(%javafiles)) {
 4241: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4242: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4243: 			&add_filetype($allfiles,$file,$item);
 4244: 		    }
 4245: 		}
 4246: 	    } 
 4247: 	    pop @state;
 4248: 	}
 4249:     }
 4250:     foreach my $id (sort(keys(%flashvars))) {
 4251:         if ($shockwave{$id} ne '') {
 4252:             my @pairs = split(/\&/,$flashvars{$id});
 4253:             foreach my $pair (@pairs) {
 4254:                 my ($key,$value) = split(/\=/,$pair);
 4255:                 if ($key eq 'thumb') {
 4256:                     &add_filetype($allfiles,$value,$key);
 4257:                 } elsif ($key eq 'content') {
 4258:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4259:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4260:                     if ($ext ne '') {
 4261:                         &add_filetype($allfiles,$path.$value,$ext);
 4262:                     }
 4263:                 }
 4264:             }
 4265:         }
 4266:     }
 4267:     return 'ok';
 4268: }
 4269: 
 4270: sub add_filetype {
 4271:     my ($allfiles,$file,$type)=@_;
 4272:     if (exists($allfiles->{$file})) {
 4273: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4274: 	    push(@{$allfiles->{$file}}, &escape($type));
 4275: 	}
 4276:     } else {
 4277: 	@{$allfiles->{$file}} = (&escape($type));
 4278:     }
 4279: }
 4280: 
 4281: sub embedded_dependency {
 4282:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4283:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4284:         if (($identifier ne '') &&
 4285:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4286:             ($pathfrom ne '')) {
 4287:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4288:             foreach my $dep (@{$related->{$identifier}}) {
 4289:                 &add_filetype($allfiles,$path.$dep,'object');
 4290:             }
 4291:         }
 4292:     }
 4293:     return;
 4294: }
 4295: 
 4296: sub removeuploadedurl {
 4297:     my ($url)=@_;	
 4298:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4299:     return &removeuserfile($uname,$udom,$fname);
 4300: }
 4301: 
 4302: sub removeuserfile {
 4303:     my ($docuname,$docudom,$fname)=@_;
 4304:     my $home=&homeserver($docuname,$docudom);    
 4305:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4306:     if ($result eq 'ok') {	
 4307:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4308:             my $metafile = $fname.'.meta';
 4309:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4310: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4311:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4312:             my $sqlresult = 
 4313:                 &update_portfolio_table($docuname,$docudom,$file,
 4314:                                         'portfolio_metadata',$group,
 4315:                                         'delete');
 4316:         }
 4317:     }
 4318:     return $result;
 4319: }
 4320: 
 4321: sub mkdiruserfile {
 4322:     my ($docuname,$docudom,$dir)=@_;
 4323:     my $home=&homeserver($docuname,$docudom);
 4324:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4325: }
 4326: 
 4327: sub renameuserfile {
 4328:     my ($docuname,$docudom,$old,$new)=@_;
 4329:     my $home=&homeserver($docuname,$docudom);
 4330:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4331:                         &escape("$old").':'.&escape("$new"),$home);
 4332:     if ($result eq 'ok') {
 4333:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4334:             my $oldmeta = $old.'.meta';
 4335:             my $newmeta = $new.'.meta';
 4336:             my $metaresult = 
 4337:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4338: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4339:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4340:             my $sqlresult = 
 4341:                 &update_portfolio_table($docuname,$docudom,$file,
 4342:                                         'portfolio_metadata',$group,
 4343:                                         'delete');
 4344:         }
 4345:     }
 4346:     return $result;
 4347: }
 4348: 
 4349: # ------------------------------------------------------------------------- Log
 4350: 
 4351: sub log {
 4352:     my ($dom,$nam,$hom,$what)=@_;
 4353:     return critical("log:$dom:$nam:$what",$hom);
 4354: }
 4355: 
 4356: # ------------------------------------------------------------------ Course Log
 4357: #
 4358: # This routine flushes several buffers of non-mission-critical nature
 4359: #
 4360: 
 4361: sub flushcourselogs {
 4362:     &logthis('Flushing log buffers');
 4363: #
 4364: # course logs
 4365: # This is a log of all transactions in a course, which can be used
 4366: # for data mining purposes
 4367: #
 4368: # It also collects the courseid database, which lists last transaction
 4369: # times and course titles for all courseids
 4370: #
 4371:     my %courseidbuffer=();
 4372:     foreach my $crsid (keys(%courselogs)) {
 4373:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4374: 		          &escape($courselogs{$crsid}),
 4375: 		          $coursehombuf{$crsid}) eq 'ok') {
 4376: 	    delete $courselogs{$crsid};
 4377:         } else {
 4378:             &logthis('Failed to flush log buffer for '.$crsid);
 4379:             if (length($courselogs{$crsid})>40000) {
 4380:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4381:                         " exceeded maximum size, deleting.</font>");
 4382:                delete $courselogs{$crsid};
 4383:             }
 4384:         }
 4385:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4386:             'description' => $coursedescrbuf{$crsid},
 4387:             'inst_code'    => $courseinstcodebuf{$crsid},
 4388:             'type'        => $coursetypebuf{$crsid},
 4389:             'owner'       => $courseownerbuf{$crsid},
 4390:         };
 4391:     }
 4392: #
 4393: # Write course id database (reverse lookup) to homeserver of courses 
 4394: # Is used in pickcourse
 4395: #
 4396:     foreach my $crs_home (keys(%courseidbuffer)) {
 4397:         my $response = &courseidput(&host_domain($crs_home),
 4398:                                     $courseidbuffer{$crs_home},
 4399:                                     $crs_home,'timeonly');
 4400:     }
 4401: #
 4402: # File accesses
 4403: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4404: #
 4405:     foreach my $entry (keys(%accesshash)) {
 4406:         if ($entry =~ /___count$/) {
 4407:             my ($dom,$name);
 4408:             ($dom,$name,undef)=
 4409: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4410:             if (! defined($dom) || $dom eq '' || 
 4411:                 ! defined($name) || $name eq '') {
 4412:                 my $cid = $env{'request.course.id'};
 4413:                 $dom  = $env{'request.'.$cid.'.domain'};
 4414:                 $name = $env{'request.'.$cid.'.num'};
 4415:             }
 4416:             my $value = $accesshash{$entry};
 4417:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4418:             my %temphash=($url => $value);
 4419:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4420:             if ($result eq 'ok') {
 4421:                 delete $accesshash{$entry};
 4422:             }
 4423:         } else {
 4424:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4425:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4426:             my %temphash=($entry => $accesshash{$entry});
 4427:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4428:                 delete $accesshash{$entry};
 4429:             }
 4430:         }
 4431:     }
 4432: #
 4433: # Roles
 4434: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4435: #
 4436:     foreach my $entry (keys(%userrolehash)) {
 4437:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4438: 	    split(/\:/,$entry);
 4439:         if (&Apache::lonnet::put('nohist_userroles',
 4440:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4441:                 $rudom,$runame) eq 'ok') {
 4442: 	    delete $userrolehash{$entry};
 4443:         }
 4444:     }
 4445: #
 4446: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4447: #
 4448:     my %domrolebuffer = ();
 4449:     foreach my $entry (keys(%domainrolehash)) {
 4450:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4451:         if ($domrolebuffer{$rudom}) {
 4452:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4453:                       '='.&escape($domainrolehash{$entry});
 4454:         } else {
 4455:             $domrolebuffer{$rudom}.=&escape($entry).
 4456:                       '='.&escape($domainrolehash{$entry});
 4457:         }
 4458:         delete $domainrolehash{$entry};
 4459:     }
 4460:     foreach my $dom (keys(%domrolebuffer)) {
 4461: 	my %servers;
 4462: 	if (defined(&domain($dom,'primary'))) {
 4463: 	    my $primary=&domain($dom,'primary');
 4464: 	    my $hostname=&hostname($primary);
 4465: 	    $servers{$primary} = $hostname;
 4466: 	} else { 
 4467: 	    %servers = &get_servers($dom,'library');
 4468: 	}
 4469: 	foreach my $tryserver (keys(%servers)) {
 4470: 	    if (&reply('domroleput:'.$dom.':'.
 4471: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4472: 		last;
 4473: 	    } else {  
 4474: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4475: 	    }
 4476:         }
 4477:     }
 4478:     $dumpcount++;
 4479: }
 4480: 
 4481: sub courselog {
 4482:     my $what=shift;
 4483:     $what=time.':'.$what;
 4484:     unless ($env{'request.course.id'}) { return ''; }
 4485:     $coursedombuf{$env{'request.course.id'}}=
 4486:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4487:     $coursenumbuf{$env{'request.course.id'}}=
 4488:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4489:     $coursehombuf{$env{'request.course.id'}}=
 4490:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4491:     $coursedescrbuf{$env{'request.course.id'}}=
 4492:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4493:     $courseinstcodebuf{$env{'request.course.id'}}=
 4494:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4495:     $courseownerbuf{$env{'request.course.id'}}=
 4496:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4497:     $coursetypebuf{$env{'request.course.id'}}=
 4498:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4499:     if (defined $courselogs{$env{'request.course.id'}}) {
 4500: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4501:     } else {
 4502: 	$courselogs{$env{'request.course.id'}}.=$what;
 4503:     }
 4504:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4505: 	&flushcourselogs();
 4506:     }
 4507: }
 4508: 
 4509: sub courseacclog {
 4510:     my $fnsymb=shift;
 4511:     unless ($env{'request.course.id'}) { return ''; }
 4512:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4513:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4514:         $what.=':POST';
 4515:         # FIXME: Probably ought to escape things....
 4516: 	foreach my $key (keys(%env)) {
 4517:             if ($key=~/^form\.(.*)/) {
 4518:                 my $formitem = $1;
 4519:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4520:                     $what.=':'.$formitem.'='.$env{$key};
 4521:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4522:                     $what.=':'.$formitem.'='.$env{$key};
 4523:                 }
 4524:             }
 4525:         }
 4526:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4527:         # FIXME: We should not be depending on a form parameter that someone
 4528:         # editing lonsearchcat.pm might change in the future.
 4529:         if ($env{'form.phase'} eq 'course_search') {
 4530:             $what.= ':POST';
 4531:             # FIXME: Probably ought to escape things....
 4532:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4533:                                  'crsdiscuss') {
 4534:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4535:             }
 4536:         }
 4537:     }
 4538:     &courselog($what);
 4539: }
 4540: 
 4541: sub countacc {
 4542:     my $url=&declutter(shift);
 4543:     return if (! defined($url) || $url eq '');
 4544:     unless ($env{'request.course.id'}) { return ''; }
 4545: #
 4546: # Mark that this url was used in this course
 4547: #
 4548:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4549: #
 4550: # Increase the access count for this resource in this child process
 4551: #
 4552:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4553:     $accesshash{$key}++;
 4554: }
 4555: 
 4556: sub linklog {
 4557:     my ($from,$to)=@_;
 4558:     $from=&declutter($from);
 4559:     $to=&declutter($to);
 4560:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4561:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4562: }
 4563: 
 4564: sub statslog {
 4565:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4566:     if ($users<2) { return; }
 4567:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4568:             'course'       => $env{'request.course.id'},
 4569:             'sections'     => '"all"',
 4570:             'num_students' => $users,
 4571:             'part'         => $part,
 4572:             'symb'         => $symb,
 4573:             'mean_tries'   => $av_attempts,
 4574:             'deg_of_diff'  => $degdiff});
 4575:     foreach my $key (keys(%dynstore)) {
 4576:         $accesshash{$key}=$dynstore{$key};
 4577:     }
 4578: }
 4579:   
 4580: sub userrolelog {
 4581:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4582:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4583:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4584:        $userrolehash
 4585:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4586:                     =$tend.':'.$tstart;
 4587:     }
 4588:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4589:        $userrolehash
 4590:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4591:                     =$tend.':'.$tstart;
 4592:     }
 4593:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4594:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4595:        $domainrolehash
 4596:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4597:                     = $tend.':'.$tstart;
 4598:     }
 4599: }
 4600: 
 4601: sub courserolelog {
 4602:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4603:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4604:         my $cdom = $1;
 4605:         my $cnum = $2;
 4606:         my $sec = $3;
 4607:         my $namespace = 'rolelog';
 4608:         my %storehash = (
 4609:                            role    => $trole,
 4610:                            start   => $tstart,
 4611:                            end     => $tend,
 4612:                            selfenroll => $selfenroll,
 4613:                            context    => $context,
 4614:                         );
 4615:         if ($trole eq 'gr') {
 4616:             $namespace = 'groupslog';
 4617:             $storehash{'group'} = $sec;
 4618:         } else {
 4619:             $storehash{'section'} = $sec;
 4620:         }
 4621:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4622:                    $domain,$cnum,$cdom);
 4623:         if (($trole ne 'st') || ($sec ne '')) {
 4624:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4625:         }
 4626:     }
 4627:     return;
 4628: }
 4629: 
 4630: sub domainrolelog {
 4631:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4632:     if ($area =~ m{^/($match_domain)/$}) {
 4633:         my $cdom = $1;
 4634:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4635:         my $namespace = 'rolelog';
 4636:         my %storehash = (
 4637:                            role    => $trole,
 4638:                            start   => $tstart,
 4639:                            end     => $tend,
 4640:                            context => $context,
 4641:                         );
 4642:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4643:                    $domain,$domconfiguser,$cdom);
 4644:     }
 4645:     return;
 4646: 
 4647: }
 4648: 
 4649: sub coauthorrolelog {
 4650:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4651:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4652:         my $audom = $1;
 4653:         my $auname = $2;
 4654:         my $namespace = 'rolelog';
 4655:         my %storehash = (
 4656:                            role    => $trole,
 4657:                            start   => $tstart,
 4658:                            end     => $tend,
 4659:                            context => $context,
 4660:                         );
 4661:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4662:                    $domain,$auname,$audom);
 4663:     }
 4664:     return;
 4665: }
 4666: 
 4667: sub get_course_adv_roles {
 4668:     my ($cid,$codes) = @_;
 4669:     $cid=$env{'request.course.id'} unless (defined($cid));
 4670:     my %coursehash=&coursedescription($cid);
 4671:     my $crstype = &Apache::loncommon::course_type($cid);
 4672:     my %nothide=();
 4673:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4674:         if ($user !~ /:/) {
 4675: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4676:         } else {
 4677:             $nothide{$user}=1;
 4678:         }
 4679:     }
 4680:     my @possdoms = ($coursehash{'domain'});
 4681:     if ($coursehash{'checkforpriv'}) {
 4682:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4683:     }
 4684:     my %returnhash=();
 4685:     my %dumphash=
 4686:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4687:     my $now=time;
 4688:     my %privileged;
 4689:     foreach my $entry (keys(%dumphash)) {
 4690: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4691:         if (($tstart) && ($tstart<0)) { next; }
 4692:         if (($tend) && ($tend<$now)) { next; }
 4693:         if (($tstart) && ($now<$tstart)) { next; }
 4694:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4695: 	if ($username eq '' || $domain eq '') { next; }
 4696:         if ((&privileged($username,$domain,\@possdoms)) &&
 4697:             (!$nothide{$username.':'.$domain})) { next; }
 4698: 	if ($role eq 'cr') { next; }
 4699:         if ($codes) {
 4700:             if ($section) { $role .= ':'.$section; }
 4701:             if ($returnhash{$role}) {
 4702:                 $returnhash{$role}.=','.$username.':'.$domain;
 4703:             } else {
 4704:                 $returnhash{$role}=$username.':'.$domain;
 4705:             }
 4706:         } else {
 4707:             my $key=&plaintext($role,$crstype);
 4708:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4709:             if ($returnhash{$key}) {
 4710: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4711:             } else {
 4712:                 $returnhash{$key}=$username.':'.$domain;
 4713:             }
 4714:         }
 4715:     }
 4716:     return %returnhash;
 4717: }
 4718: 
 4719: sub get_my_roles {
 4720:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4721:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4722:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4723:     my (%dumphash,%nothide);
 4724:     if ($context eq 'userroles') {
 4725:         %dumphash = &dump('roles',$udom,$uname);
 4726:     } else {
 4727:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4728:         if ($hidepriv) {
 4729:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4730:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4731:                 if ($user !~ /:/) {
 4732:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4733:                 } else {
 4734:                     $nothide{$user} = 1;
 4735:                 }
 4736:             }
 4737:         }
 4738:     }
 4739:     my %returnhash=();
 4740:     my $now=time;
 4741:     my %privileged;
 4742:     foreach my $entry (keys(%dumphash)) {
 4743:         my ($role,$tend,$tstart);
 4744:         if ($context eq 'userroles') {
 4745:             next if ($entry =~ /^rolesdef/);
 4746: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4747:         } else {
 4748:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4749:         }
 4750:         if (($tstart) && ($tstart<0)) { next; }
 4751:         my $status = 'active';
 4752:         if (($tend) && ($tend<=$now)) {
 4753:             $status = 'previous';
 4754:         } 
 4755:         if (($tstart) && ($now<$tstart)) {
 4756:             $status = 'future';
 4757:         }
 4758:         if (ref($types) eq 'ARRAY') {
 4759:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4760:                 next;
 4761:             } 
 4762:         } else {
 4763:             if ($status ne 'active') {
 4764:                 next;
 4765:             }
 4766:         }
 4767:         my ($rolecode,$username,$domain,$section,$area);
 4768:         if ($context eq 'userroles') {
 4769:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4770:             (undef,$domain,$username,$section) = split(/\//,$area);
 4771:         } else {
 4772:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4773:         }
 4774:         if (ref($roledoms) eq 'ARRAY') {
 4775:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4776:                 next;
 4777:             }
 4778:         }
 4779:         if (ref($roles) eq 'ARRAY') {
 4780:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4781:                 if ($role =~ /^cr\//) {
 4782:                     if (!grep(/^cr$/,@{$roles})) {
 4783:                         next;
 4784:                     }
 4785:                 } elsif ($role =~ /^gr\//) {
 4786:                     if (!grep(/^gr$/,@{$roles})) {
 4787:                         next;
 4788:                     }
 4789:                 } else {
 4790:                     next;
 4791:                 }
 4792:             }
 4793:         }
 4794:         if ($hidepriv) {
 4795:             my @privroles = ('dc','su');
 4796:             if ($context eq 'userroles') {
 4797:                 next if (grep(/^\Q$role\E$/,@privroles));
 4798:             } else {
 4799:                 my $possdoms = [$domain];
 4800:                 if (ref($roledoms) eq 'ARRAY') {
 4801:                    push(@{$possdoms},@{$roledoms}); 
 4802:                 }
 4803:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4804:                     if (!$nothide{$username.':'.$domain}) {
 4805:                         next;
 4806:                     }
 4807:                 }
 4808:             }
 4809:         }
 4810:         if ($withsec) {
 4811:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4812:                 $tstart.':'.$tend;
 4813:         } else {
 4814:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4815:         }
 4816:     }
 4817:     return %returnhash;
 4818: }
 4819: 
 4820: sub get_all_adhocroles {
 4821:     my ($dom) = @_;
 4822:     my @roles_by_num = ();
 4823:     my %domdefaults = &get_domain_defaults($dom);
 4824:     my (%description,%access_in_dom,%access_info);
 4825:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4826:         my $count = 0;
 4827:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4828:         my %ordered;
 4829:         foreach my $role (sort(keys(%domcurrent))) {
 4830:             my ($order,$desc,$access_in_dom);
 4831:             if (ref($domcurrent{$role}) eq 'HASH') {
 4832:                 $order = $domcurrent{$role}{'order'};
 4833:                 $desc = $domcurrent{$role}{'desc'};
 4834:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4835:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4836:             }
 4837:             if ($order eq '') {
 4838:                 $order = $count;
 4839:             }
 4840:             $ordered{$order} = $role;
 4841:             if ($desc ne '') {
 4842:                 $description{$role} = $desc;
 4843:             } else {
 4844:                 $description{$role}= $role;
 4845:             }
 4846:             $count++;
 4847:         }
 4848:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4849:             push(@roles_by_num,$ordered{$item});
 4850:         }
 4851:     }
 4852:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4853: }
 4854: 
 4855: sub get_my_adhocroles {
 4856:     my ($cid,$checkreg) = @_;
 4857:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4858:     if ($env{'request.course.id'} eq $cid) {
 4859:         $cdom = $env{'course.'.$cid.'.domain'};
 4860:         $cnum = $env{'course.'.$cid.'.num'};
 4861:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4862:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4863:         $cdom = $1;
 4864:         $cnum = $2;
 4865:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4866:                                      $cdom,$cnum);
 4867:     }
 4868:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4869:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4870:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4871:         if ($rosterhash{$user} ne '') {
 4872:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4873:             return ([],{}) if ($type eq 'auto');
 4874:         }
 4875:     }
 4876:     if (($cdom ne '') && ($cnum ne ''))  {
 4877:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4878:             my $then=$env{'user.login.time'};
 4879:             my $update=$env{'user.update.time'};
 4880:             if (!$update) {
 4881:                 $update = $then;
 4882:             }
 4883:             my @liveroles;
 4884:             foreach my $role ('dh','da') {
 4885:                 if ($env{"user.role.$role./$cdom/"}) {
 4886:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4887:                     my $limit = $update;
 4888:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4889:                         $limit = $then;
 4890:                     }
 4891:                     my $activerole = 1;
 4892:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4893:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4894:                     if ($activerole) {
 4895:                         push(@liveroles,$role);
 4896:                     }
 4897:                 }
 4898:             }
 4899:             if (@liveroles) {
 4900:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4901:                     my ($accessref,$accessinfo,%access_in_dom);
 4902:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4903:                     if (ref($roles_by_num) eq 'ARRAY') {
 4904:                         if (@{$roles_by_num}) {
 4905:                             my %settings;
 4906:                             if ($env{'request.course.id'} eq $cid) {
 4907:                                 foreach my $envkey (keys(%env)) {
 4908:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4909:                                         $settings{$1} = $env{$envkey};
 4910:                                     }
 4911:                                 }
 4912:                             } else {
 4913:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4914:                             }
 4915:                             my %setincrs;
 4916:                             if ($settings{'internal.adhocaccess'}) {
 4917:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4918:                             }
 4919:                             my @statuses;
 4920:                             if ($env{'environment.inststatus'}) {
 4921:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4922:                             }
 4923:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4924:                             if (ref($accessref) eq 'HASH') {
 4925:                                 %access_in_dom = %{$accessref};
 4926:                             }
 4927:                             foreach my $role (@{$roles_by_num}) {
 4928:                                 my ($curraccess,@okstatus,@personnel);
 4929:                                 if ($setincrs{$role}) {
 4930:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4931:                                     if ($curraccess eq 'status') {
 4932:                                         @okstatus = split(/\&/,$rest);
 4933:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4934:                                         @personnel = split(/\&/,$rest);
 4935:                                     }
 4936:                                 } else {
 4937:                                     $curraccess = $access_in_dom{$role};
 4938:                                     if (ref($accessinfo) eq 'HASH') {
 4939:                                         if ($curraccess eq 'status') {
 4940:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4941:                                                 @okstatus = @{$accessinfo->{$role}};
 4942:                                             }
 4943:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4944:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4945:                                                 @personnel = @{$accessinfo->{$role}};
 4946:                                             }
 4947:                                         }
 4948:                                     }
 4949:                                 }
 4950:                                 if ($curraccess eq 'none') {
 4951:                                     next;
 4952:                                 } elsif ($curraccess eq 'all') {
 4953:                                     push(@possroles,$role);
 4954:                                 } elsif ($curraccess eq 'dh') {
 4955:                                     if (grep(/^dh$/,@liveroles)) {
 4956:                                         push(@possroles,$role);
 4957:                                     } else {
 4958:                                         next;
 4959:                                     }
 4960:                                 } elsif ($curraccess eq 'da') {
 4961:                                     if (grep(/^da$/,@liveroles)) {
 4962:                                         push(@possroles,$role);
 4963:                                     } else {
 4964:                                         next;
 4965:                                     }
 4966:                                 } elsif ($curraccess eq 'status') {
 4967:                                     if (@okstatus) {
 4968:                                         if (!@statuses) {
 4969:                                             if (grep(/^default$/,@okstatus)) {
 4970:                                                 push(@possroles,$role);
 4971:                                             }
 4972:                                         } else {
 4973:                                             foreach my $status (@okstatus) {
 4974:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4975:                                                     push(@possroles,$role);
 4976:                                                     last;
 4977:                                                 }
 4978:                                             }
 4979:                                         }
 4980:                                     }
 4981:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4982:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4983:                                         if ($curraccess eq 'exc') {
 4984:                                             push(@possroles,$role);
 4985:                                         }
 4986:                                     } elsif ($curraccess eq 'inc') {
 4987:                                         push(@possroles,$role);
 4988:                                     }
 4989:                                 }
 4990:                             }
 4991:                         }
 4992:                     }
 4993:                 }
 4994:             }
 4995:         }
 4996:     }
 4997:     unless (ref($description) eq 'HASH') {
 4998:         if (ref($roles_by_num) eq 'ARRAY') {
 4999:             my %desc;
 5000:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5001:             $description = \%desc;
 5002:         } else {
 5003:             $description = {};
 5004:         }
 5005:     }
 5006:     return (\@possroles,$description);
 5007: }
 5008: 
 5009: # ----------------------------------------------------- Frontpage Announcements
 5010: #
 5011: #
 5012: 
 5013: sub postannounce {
 5014:     my ($server,$text)=@_;
 5015:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5016:     unless ($text=~/\w/) { $text=''; }
 5017:     return &reply('setannounce:'.&escape($text),$server);
 5018: }
 5019: 
 5020: sub getannounce {
 5021: 
 5022:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5023: 	my $announcement='';
 5024: 	while (my $line = <$fh>) { $announcement .= $line; }
 5025: 	close($fh);
 5026: 	if ($announcement=~/\w/) { 
 5027: 	    return 
 5028:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5029:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5030: 	} else {
 5031: 	    return '';
 5032: 	}
 5033:     } else {
 5034: 	return '';
 5035:     }
 5036: }
 5037: 
 5038: # ---------------------------------------------------------- Course ID routines
 5039: # Deal with domain's nohist_courseid.db files
 5040: #
 5041: 
 5042: sub courseidput {
 5043:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5044:     return unless (ref($storehash) eq 'HASH');
 5045:     my $outcome;
 5046:     if ($caller eq 'timeonly') {
 5047:         my $cids = '';
 5048:         foreach my $item (keys(%$storehash)) {
 5049:             $cids.=&escape($item).'&';
 5050:         }
 5051:         $cids=~s/\&$//;
 5052:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5053:                           $coursehome);       
 5054:     } else {
 5055:         my $items = '';
 5056:         foreach my $item (keys(%$storehash)) {
 5057:             $items.= &escape($item).'='.
 5058:                      &freeze_escape($$storehash{$item}).'&';
 5059:         }
 5060:         $items=~s/\&$//;
 5061:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5062:                           $coursehome);
 5063:     }
 5064:     if ($outcome eq 'unknown_cmd') {
 5065:         my $what;
 5066:         foreach my $cid (keys(%$storehash)) {
 5067:             $what .= &escape($cid).'=';
 5068:             foreach my $item ('description','inst_code','owner','type') {
 5069:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5070:             }
 5071:             $what =~ s/\:$/&/;
 5072:         }
 5073:         $what =~ s/\&$//;  
 5074:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5075:     } else {
 5076:         return $outcome;
 5077:     }
 5078: }
 5079: 
 5080: sub courseiddump {
 5081:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5082:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5083:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5084:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5085:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5086:     my $as_hash = 1;
 5087:     my %returnhash;
 5088:     if (!$domfilter) { $domfilter=''; }
 5089:     my %libserv = &all_library();
 5090:     foreach my $tryserver (keys(%libserv)) {
 5091:         if ( (  $hostidflag == 1 
 5092: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5093: 	     || (!defined($hostidflag)) ) {
 5094: 
 5095: 	    if (($domfilter eq '') ||
 5096: 		(&host_domain($tryserver) eq $domfilter)) {
 5097:                 my $rep;
 5098:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5099:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5100:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5101:                                 &escape($descfilter), &escape($instcodefilter), 
 5102:                                 &escape($ownerfilter), &escape($coursefilter),
 5103:                                 &escape($typefilter), &escape($regexp_ok), 
 5104:                                 $as_hash, &escape($selfenrollonly), 
 5105:                                 &escape($catfilter), $showhidden, $caller, 
 5106:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5107:                                 &escape($createdbefore), &escape($createdafter), 
 5108:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5109:                                 $reqcrsdom,&escape($reqinstcode))));
 5110:                 } else {
 5111:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5112:                              $sincefilter.':'.&escape($descfilter).':'.
 5113:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5114:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5115:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5116:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5117:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5118:                              &escape($cc_clone).':'.$cloneonly.':'.
 5119:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5120:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5121:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5122:                 }
 5123:                      
 5124:                 my @pairs=split(/\&/,$rep);
 5125:                 foreach my $item (@pairs) {
 5126:                     my ($key,$value)=split(/\=/,$item,2);
 5127:                     $key = &unescape($key);
 5128:                     next if ($key =~ /^error: 2 /);
 5129:                     my $result = &thaw_unescape($value);
 5130:                     if (ref($result) eq 'HASH') {
 5131:                         $returnhash{$key}=$result;
 5132:                     } else {
 5133:                         my @responses = split(/:/,$value);
 5134:                         my @items = ('description','inst_code','owner','type');
 5135:                         for (my $i=0; $i<@responses; $i++) {
 5136:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5137:                         }
 5138:                     }
 5139:                 }
 5140:             }
 5141:         }
 5142:     }
 5143:     return %returnhash;
 5144: }
 5145: 
 5146: sub courselastaccess {
 5147:     my ($cdom,$cnum,$hostidref) = @_;
 5148:     my %returnhash;
 5149:     if ($cdom && $cnum) {
 5150:         my $chome = &homeserver($cnum,$cdom);
 5151:         if ($chome ne 'no_host') {
 5152:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5153:             &extract_lastaccess(\%returnhash,$rep);
 5154:         }
 5155:     } else {
 5156:         if (!$cdom) { $cdom=''; }
 5157:         my %libserv = &all_library();
 5158:         foreach my $tryserver (keys(%libserv)) {
 5159:             if (ref($hostidref) eq 'ARRAY') {
 5160:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5161:             } 
 5162:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5163:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5164:                 &extract_lastaccess(\%returnhash,$rep);
 5165:             }
 5166:         }
 5167:     }
 5168:     return %returnhash;
 5169: }
 5170: 
 5171: sub extract_lastaccess {
 5172:     my ($returnhash,$rep) = @_;
 5173:     if (ref($returnhash) eq 'HASH') {
 5174:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5175:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5176:                  $rep eq '') {
 5177:             my @pairs=split(/\&/,$rep);
 5178:             foreach my $item (@pairs) {
 5179:                 my ($key,$value)=split(/\=/,$item,2);
 5180:                 $key = &unescape($key);
 5181:                 next if ($key =~ /^error: 2 /);
 5182:                 $returnhash->{$key} = &thaw_unescape($value);
 5183:             }
 5184:         }
 5185:     }
 5186:     return;
 5187: }
 5188: 
 5189: # ---------------------------------------------------------- DC e-mail
 5190: 
 5191: sub dcmailput {
 5192:     my ($domain,$msgid,$message,$server)=@_;
 5193:     my $status = &Apache::lonnet::critical(
 5194:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5195:        &escape($message),$server);
 5196:     return $status;
 5197: }
 5198: 
 5199: sub dcmaildump {
 5200:     my ($dom,$startdate,$enddate,$senders) = @_;
 5201:     my %returnhash=();
 5202: 
 5203:     if (defined(&domain($dom,'primary'))) {
 5204:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5205:                                                          &escape($enddate).':';
 5206: 	my @esc_senders=map { &escape($_)} @$senders;
 5207: 	$cmd.=&escape(join('&',@esc_senders));
 5208: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5209:             my ($key,$value) = split(/\=/,$line,2);
 5210:             if (($key) && ($value)) {
 5211:                 $returnhash{&unescape($key)} = &unescape($value);
 5212:             }
 5213:         }
 5214:     }
 5215:     return %returnhash;
 5216: }
 5217: # ---------------------------------------------------------- Domain roles
 5218: 
 5219: sub get_domain_roles {
 5220:     my ($dom,$roles,$startdate,$enddate)=@_;
 5221:     if ((!defined($startdate)) || ($startdate eq '')) {
 5222:         $startdate = '.';
 5223:     }
 5224:     if ((!defined($enddate)) || ($enddate eq '')) {
 5225:         $enddate = '.';
 5226:     }
 5227:     my $rolelist;
 5228:     if (ref($roles) eq 'ARRAY') {
 5229:         $rolelist = join('&',@{$roles});
 5230:     }
 5231:     my %personnel = ();
 5232: 
 5233:     my %servers = &get_servers($dom,'library');
 5234:     foreach my $tryserver (keys(%servers)) {
 5235: 	%{$personnel{$tryserver}}=();
 5236: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5237: 					    &escape($startdate).':'.
 5238: 					    &escape($enddate).':'.
 5239: 					    &escape($rolelist), $tryserver))) {
 5240: 	    my ($key,$value) = split(/\=/,$line,2);
 5241: 	    if (($key) && ($value)) {
 5242: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5243: 	    }
 5244: 	}
 5245:     }
 5246:     return %personnel;
 5247: }
 5248: 
 5249: sub get_active_domroles {
 5250:     my ($dom,$roles) = @_;
 5251:     return () unless (ref($roles) eq 'ARRAY');
 5252:     my $now = time;
 5253:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5254:     my %domroles;
 5255:     foreach my $server (keys(%dompersonnel)) {
 5256:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5257:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5258:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5259:         }
 5260:     }
 5261:     return %domroles;
 5262: }
 5263: 
 5264: # ----------------------------------------------------------- Interval timing 
 5265: 
 5266: {
 5267: # Caches needed for speedup of navmaps
 5268: # We don't want to cache this for very long at all (5 seconds at most)
 5269: # 
 5270: # The user for whom we cache
 5271: my $cachedkey='';
 5272: # The cached times for this user
 5273: my %cachedtimes=();
 5274: # When this was last done
 5275: my $cachedtime='';
 5276: 
 5277: sub load_all_first_access {
 5278:     my ($uname,$udom,$ignorecache)=@_;
 5279:     if (($cachedkey eq $uname.':'.$udom) &&
 5280:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5281:         (!$ignorecache)) {
 5282:         return;
 5283:     }
 5284:     $cachedtime=time;
 5285:     $cachedkey=$uname.':'.$udom;
 5286:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5287: }
 5288: 
 5289: sub get_first_access {
 5290:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5291:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5292:     if ($argsymb) { $symb=$argsymb; }
 5293:     my ($map,$id,$res)=&decode_symb($symb);
 5294:     if ($argmap) { $map = $argmap; }
 5295:     if ($type eq 'course') {
 5296: 	$res='course';
 5297:     } elsif ($type eq 'map') {
 5298: 	$res=&symbread($map);
 5299:     } else {
 5300: 	$res=$symb;
 5301:     }
 5302:     &load_all_first_access($uname,$udom,$ignorecache);
 5303:     return $cachedtimes{"$courseid\0$res"};
 5304: }
 5305: 
 5306: sub set_first_access {
 5307:     my ($type,$interval)=@_;
 5308:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5309:     my ($map,$id,$res)=&decode_symb($symb);
 5310:     if ($type eq 'course') {
 5311: 	$res='course';
 5312:     } elsif ($type eq 'map') {
 5313: 	$res=&symbread($map);
 5314:     } else {
 5315: 	$res=$symb;
 5316:     }
 5317:     $cachedkey='';
 5318:     my $firstaccess=&get_first_access($type,$symb,$map);
 5319:     if ($firstaccess) {
 5320:         &logthis("First access time already set ($firstaccess) when attempting ".
 5321:                  "to set new value (type: $type, extent: $res) for $uname:$udom ". 
 5322:                  "in $courseid"); 
 5323:         return 'already_set';
 5324:     } else {
 5325:         my $start = time;
 5326: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5327:                           $udom,$uname);
 5328:         if ($putres eq 'ok') {
 5329:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5330:                  $udom,$uname); 
 5331:             &appenv(
 5332:                      {
 5333:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5334:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5335:                      }
 5336:                   );
 5337:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5338:                 $cachedtimes{"$courseid\0$res"} = $start;
 5339:             }
 5340:         } elsif ($putres ne 'refused') {
 5341:             &logthis("Result: $putres when attempting to set first access time ".
 5342:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5343:         }
 5344:         return $putres;
 5345:     }
 5346:     return 'already_set';
 5347: }
 5348: }
 5349: 
 5350: # --------------------------------------------- Set Expire Date for Spreadsheet
 5351: 
 5352: sub expirespread {
 5353:     my ($uname,$udom,$stype,$usymb)=@_;
 5354:     my $cid=$env{'request.course.id'}; 
 5355:     if ($cid) {
 5356:        my $now=time;
 5357:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5358:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5359:                             $env{'course.'.$cid.'.num'}.
 5360: 	        	    ':nohist_expirationdates:'.
 5361:                             &escape($key).'='.$now,
 5362:                             $env{'course.'.$cid.'.home'})
 5363:     }
 5364:     return 'ok';
 5365: }
 5366: 
 5367: # ----------------------------------------------------- Devalidate Spreadsheets
 5368: 
 5369: sub devalidate {
 5370:     my ($symb,$uname,$udom)=@_;
 5371:     my $cid=$env{'request.course.id'}; 
 5372:     if ($cid) {
 5373:         # delete the stored spreadsheets for
 5374:         # - the student level sheet of this user in course's homespace
 5375:         # - the assessment level sheet for this resource 
 5376:         #   for this user in user's homespace
 5377: 	# - current conditional state info
 5378: 	my $key=$uname.':'.$udom.':';
 5379:         my $status=
 5380: 	    &del('nohist_calculatedsheets',
 5381: 		 [$key.'studentcalc:'],
 5382: 		 $env{'course.'.$cid.'.domain'},
 5383: 		 $env{'course.'.$cid.'.num'})
 5384: 		.' '.
 5385: 	    &del('nohist_calculatedsheets_'.$cid,
 5386: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5387:         unless ($status eq 'ok ok') {
 5388:            &logthis('Could not devalidate spreadsheet '.
 5389:                     $uname.' at '.$udom.' for '.
 5390: 		    $symb.': '.$status);
 5391:         }
 5392: 	&delenv('user.state.'.$cid);
 5393:     }
 5394: }
 5395: 
 5396: sub get_scalar {
 5397:     my ($string,$end) = @_;
 5398:     my $value;
 5399:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5400: 	$value = $1;
 5401:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5402: 	$value = $1;
 5403:     }
 5404:     return &unescape($value);
 5405: }
 5406: 
 5407: sub array2str {
 5408:   my (@array) = @_;
 5409:   my $result=&arrayref2str(\@array);
 5410:   $result=~s/^__ARRAY_REF__//;
 5411:   $result=~s/__END_ARRAY_REF__$//;
 5412:   return $result;
 5413: }
 5414: 
 5415: sub arrayref2str {
 5416:   my ($arrayref) = @_;
 5417:   my $result='__ARRAY_REF__';
 5418:   foreach my $elem (@$arrayref) {
 5419:     if(ref($elem) eq 'ARRAY') {
 5420:       $result.=&arrayref2str($elem).'&';
 5421:     } elsif(ref($elem) eq 'HASH') {
 5422:       $result.=&hashref2str($elem).'&';
 5423:     } elsif(ref($elem)) {
 5424:       #print("Got a ref of ".(ref($elem))." skipping.");
 5425:     } else {
 5426:       $result.=&escape($elem).'&';
 5427:     }
 5428:   }
 5429:   $result=~s/\&$//;
 5430:   $result .= '__END_ARRAY_REF__';
 5431:   return $result;
 5432: }
 5433: 
 5434: sub hash2str {
 5435:   my (%hash) = @_;
 5436:   my $result=&hashref2str(\%hash);
 5437:   $result=~s/^__HASH_REF__//;
 5438:   $result=~s/__END_HASH_REF__$//;
 5439:   return $result;
 5440: }
 5441: 
 5442: sub hashref2str {
 5443:   my ($hashref)=@_;
 5444:   my $result='__HASH_REF__';
 5445:   foreach my $key (sort(keys(%$hashref))) {
 5446:     if (ref($key) eq 'ARRAY') {
 5447:       $result.=&arrayref2str($key).'=';
 5448:     } elsif (ref($key) eq 'HASH') {
 5449:       $result.=&hashref2str($key).'=';
 5450:     } elsif (ref($key)) {
 5451:       $result.='=';
 5452:       #print("Got a ref of ".(ref($key))." skipping.");
 5453:     } else {
 5454: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5455:     }
 5456: 
 5457:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5458:       $result.=&arrayref2str($hashref->{$key}).'&';
 5459:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5460:       $result.=&hashref2str($hashref->{$key}).'&';
 5461:     } elsif(ref($hashref->{$key})) {
 5462:        $result.='&';
 5463:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5464:     } else {
 5465:       $result.=&escape($hashref->{$key}).'&';
 5466:     }
 5467:   }
 5468:   $result=~s/\&$//;
 5469:   $result .= '__END_HASH_REF__';
 5470:   return $result;
 5471: }
 5472: 
 5473: sub str2hash {
 5474:     my ($string)=@_;
 5475:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5476:     return %$hash;
 5477: }
 5478: 
 5479: sub str2hashref {
 5480:   my ($string) = @_;
 5481: 
 5482:   my %hash;
 5483: 
 5484:   if($string !~ /^__HASH_REF__/) {
 5485:       if (! ($string eq '' || !defined($string))) {
 5486: 	  $hash{'error'}='Not hash reference';
 5487:       }
 5488:       return (\%hash, $string);
 5489:   }
 5490: 
 5491:   $string =~ s/^__HASH_REF__//;
 5492: 
 5493:   while($string !~ /^__END_HASH_REF__/) {
 5494:       #key
 5495:       my $key='';
 5496:       if($string =~ /^__HASH_REF__/) {
 5497:           ($key, $string)=&str2hashref($string);
 5498:           if(defined($key->{'error'})) {
 5499:               $hash{'error'}='Bad data';
 5500:               return (\%hash, $string);
 5501:           }
 5502:       } elsif($string =~ /^__ARRAY_REF__/) {
 5503:           ($key, $string)=&str2arrayref($string);
 5504:           if($key->[0] eq 'Array reference error') {
 5505:               $hash{'error'}='Bad data';
 5506:               return (\%hash, $string);
 5507:           }
 5508:       } else {
 5509:           $string =~ s/^(.*?)=//;
 5510: 	  $key=&unescape($1);
 5511:       }
 5512:       $string =~ s/^=//;
 5513: 
 5514:       #value
 5515:       my $value='';
 5516:       if($string =~ /^__HASH_REF__/) {
 5517:           ($value, $string)=&str2hashref($string);
 5518:           if(defined($value->{'error'})) {
 5519:               $hash{'error'}='Bad data';
 5520:               return (\%hash, $string);
 5521:           }
 5522:       } elsif($string =~ /^__ARRAY_REF__/) {
 5523:           ($value, $string)=&str2arrayref($string);
 5524:           if($value->[0] eq 'Array reference error') {
 5525:               $hash{'error'}='Bad data';
 5526:               return (\%hash, $string);
 5527:           }
 5528:       } else {
 5529: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5530:       }
 5531:       $string =~ s/^&//;
 5532: 
 5533:       $hash{$key}=$value;
 5534:   }
 5535: 
 5536:   $string =~ s/^__END_HASH_REF__//;
 5537: 
 5538:   return (\%hash, $string);
 5539: }
 5540: 
 5541: sub str2array {
 5542:     my ($string)=@_;
 5543:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5544:     return @$array;
 5545: }
 5546: 
 5547: sub str2arrayref {
 5548:   my ($string) = @_;
 5549:   my @array;
 5550: 
 5551:   if($string !~ /^__ARRAY_REF__/) {
 5552:       if (! ($string eq '' || !defined($string))) {
 5553: 	  $array[0]='Array reference error';
 5554:       }
 5555:       return (\@array, $string);
 5556:   }
 5557: 
 5558:   $string =~ s/^__ARRAY_REF__//;
 5559: 
 5560:   while($string !~ /^__END_ARRAY_REF__/) {
 5561:       my $value='';
 5562:       if($string =~ /^__HASH_REF__/) {
 5563:           ($value, $string)=&str2hashref($string);
 5564:           if(defined($value->{'error'})) {
 5565:               $array[0] ='Array reference error';
 5566:               return (\@array, $string);
 5567:           }
 5568:       } elsif($string =~ /^__ARRAY_REF__/) {
 5569:           ($value, $string)=&str2arrayref($string);
 5570:           if($value->[0] eq 'Array reference error') {
 5571:               $array[0] ='Array reference error';
 5572:               return (\@array, $string);
 5573:           }
 5574:       } else {
 5575: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5576:       }
 5577:       $string =~ s/^&//;
 5578: 
 5579:       push(@array, $value);
 5580:   }
 5581: 
 5582:   $string =~ s/^__END_ARRAY_REF__//;
 5583: 
 5584:   return (\@array, $string);
 5585: }
 5586: 
 5587: # -------------------------------------------------------------------Temp Store
 5588: 
 5589: sub tmpreset {
 5590:   my ($symb,$namespace,$domain,$stuname) = @_;
 5591:   if (!$symb) {
 5592:     $symb=&symbread();
 5593:     if (!$symb) { $symb= $env{'request.url'}; }
 5594:   }
 5595:   $symb=escape($symb);
 5596: 
 5597:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5598:   $namespace=~s/\//\_/g;
 5599:   $namespace=~s/\W//g;
 5600: 
 5601:   if (!$domain) { $domain=$env{'user.domain'}; }
 5602:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5603:   if ($domain eq 'public' && $stuname eq 'public') {
 5604:       $stuname=$ENV{'REMOTE_ADDR'};
 5605:   }
 5606:   my $path=LONCAPA::tempdir();
 5607:   my %hash;
 5608:   if (tie(%hash,'GDBM_File',
 5609: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5610: 	  &GDBM_WRCREAT(),0640)) {
 5611:     foreach my $key (keys(%hash)) {
 5612:       if ($key=~ /:$symb/) {
 5613: 	delete($hash{$key});
 5614:       }
 5615:     }
 5616:   }
 5617: }
 5618: 
 5619: sub tmpstore {
 5620:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5621: 
 5622:   if (!$symb) {
 5623:     $symb=&symbread();
 5624:     if (!$symb) { $symb= $env{'request.url'}; }
 5625:   }
 5626:   $symb=escape($symb);
 5627: 
 5628:   if (!$namespace) {
 5629:     # I don't think we would ever want to store this for a course.
 5630:     # it seems this will only be used if we don't have a course.
 5631:     #$namespace=$env{'request.course.id'};
 5632:     #if (!$namespace) {
 5633:       $namespace=$env{'request.state'};
 5634:     #}
 5635:   }
 5636:   $namespace=~s/\//\_/g;
 5637:   $namespace=~s/\W//g;
 5638:   if (!$domain) { $domain=$env{'user.domain'}; }
 5639:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5640:   if ($domain eq 'public' && $stuname eq 'public') {
 5641:       $stuname=$ENV{'REMOTE_ADDR'};
 5642:   }
 5643:   my $now=time;
 5644:   my %hash;
 5645:   my $path=LONCAPA::tempdir();
 5646:   if (tie(%hash,'GDBM_File',
 5647: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5648: 	  &GDBM_WRCREAT(),0640)) {
 5649:     $hash{"version:$symb"}++;
 5650:     my $version=$hash{"version:$symb"};
 5651:     my $allkeys=''; 
 5652:     foreach my $key (keys(%$storehash)) {
 5653:       $allkeys.=$key.':';
 5654:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5655:     }
 5656:     $hash{"$version:$symb:timestamp"}=$now;
 5657:     $allkeys.='timestamp';
 5658:     $hash{"$version:keys:$symb"}=$allkeys;
 5659:     if (untie(%hash)) {
 5660:       return 'ok';
 5661:     } else {
 5662:       return "error:$!";
 5663:     }
 5664:   } else {
 5665:     return "error:$!";
 5666:   }
 5667: }
 5668: 
 5669: # -----------------------------------------------------------------Temp Restore
 5670: 
 5671: sub tmprestore {
 5672:   my ($symb,$namespace,$domain,$stuname) = @_;
 5673: 
 5674:   if (!$symb) {
 5675:     $symb=&symbread();
 5676:     if (!$symb) { $symb= $env{'request.url'}; }
 5677:   }
 5678:   $symb=escape($symb);
 5679: 
 5680:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5681: 
 5682:   if (!$domain) { $domain=$env{'user.domain'}; }
 5683:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5684:   if ($domain eq 'public' && $stuname eq 'public') {
 5685:       $stuname=$ENV{'REMOTE_ADDR'};
 5686:   }
 5687:   my %returnhash;
 5688:   $namespace=~s/\//\_/g;
 5689:   $namespace=~s/\W//g;
 5690:   my %hash;
 5691:   my $path=LONCAPA::tempdir();
 5692:   if (tie(%hash,'GDBM_File',
 5693: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5694: 	  &GDBM_READER(),0640)) {
 5695:     my $version=$hash{"version:$symb"};
 5696:     $returnhash{'version'}=$version;
 5697:     my $scope;
 5698:     for ($scope=1;$scope<=$version;$scope++) {
 5699:       my $vkeys=$hash{"$scope:keys:$symb"};
 5700:       my @keys=split(/:/,$vkeys);
 5701:       my $key;
 5702:       $returnhash{"$scope:keys"}=$vkeys;
 5703:       foreach $key (@keys) {
 5704: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5705: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5706:       }
 5707:     }
 5708:     if (!(untie(%hash))) {
 5709:       return "error:$!";
 5710:     }
 5711:   } else {
 5712:     return "error:$!";
 5713:   }
 5714:   return %returnhash;
 5715: }
 5716: 
 5717: # ----------------------------------------------------------------------- Store
 5718: 
 5719: sub store {
 5720:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5721:     my $home='';
 5722: 
 5723:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5724: 
 5725:     $symb=&symbclean($symb);
 5726:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5727: 
 5728:     if (!$domain) { $domain=$env{'user.domain'}; }
 5729:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5730: 
 5731:     &devalidate($symb,$stuname,$domain);
 5732: 
 5733:     $symb=escape($symb);
 5734:     if (!$namespace) { 
 5735:        unless ($namespace=$env{'request.course.id'}) { 
 5736:           return ''; 
 5737:        } 
 5738:     }
 5739:     if (!$home) { $home=$env{'user.home'}; }
 5740: 
 5741:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5742:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5743: 
 5744:     my $namevalue='';
 5745:     foreach my $key (keys(%$storehash)) {
 5746:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5747:     }
 5748:     $namevalue=~s/\&$//;
 5749:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5750:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5751: }
 5752: 
 5753: # -------------------------------------------------------------- Critical Store
 5754: 
 5755: sub cstore {
 5756:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5757:     my $home='';
 5758: 
 5759:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5760: 
 5761:     $symb=&symbclean($symb);
 5762:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5763: 
 5764:     if (!$domain) { $domain=$env{'user.domain'}; }
 5765:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5766: 
 5767:     &devalidate($symb,$stuname,$domain);
 5768: 
 5769:     $symb=escape($symb);
 5770:     if (!$namespace) { 
 5771:        unless ($namespace=$env{'request.course.id'}) { 
 5772:           return ''; 
 5773:        } 
 5774:     }
 5775:     if (!$home) { $home=$env{'user.home'}; }
 5776: 
 5777:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5778:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5779: 
 5780:     my $namevalue='';
 5781:     foreach my $key (keys(%$storehash)) {
 5782:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5783:     }
 5784:     $namevalue=~s/\&$//;
 5785:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5786:     return critical
 5787:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5788: }
 5789: 
 5790: # --------------------------------------------------------------------- Restore
 5791: 
 5792: sub restore {
 5793:     my ($symb,$namespace,$domain,$stuname) = @_;
 5794:     my $home='';
 5795: 
 5796:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5797: 
 5798:     if (!$symb) {
 5799:         return if ($namespace eq 'courserequests');
 5800:         unless ($symb=escape(&symbread())) { return ''; }
 5801:     } else {
 5802:         unless ($namespace eq 'courserequests') {
 5803:             $symb=&escape(&symbclean($symb));
 5804:         }
 5805:     }
 5806:     if (!$namespace) { 
 5807:        unless ($namespace=$env{'request.course.id'}) { 
 5808:           return ''; 
 5809:        } 
 5810:     }
 5811:     if (!$domain) { $domain=$env{'user.domain'}; }
 5812:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5813:     if (!$home) { $home=$env{'user.home'}; }
 5814:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5815: 
 5816:     my %returnhash=();
 5817:     foreach my $line (split(/\&/,$answer)) {
 5818: 	my ($name,$value)=split(/\=/,$line);
 5819:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5820:     }
 5821:     my $version;
 5822:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5823:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5824:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5825:        }
 5826:     }
 5827:     return %returnhash;
 5828: }
 5829: 
 5830: # ---------------------------------------------------------- Course Description
 5831: #
 5832: #  
 5833: 
 5834: sub coursedescription {
 5835:     my ($courseid,$args)=@_;
 5836:     $courseid=~s/^\///;
 5837:     $courseid=~s/\_/\//g;
 5838:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5839:     my $chome=&homeserver($cnum,$cdomain);
 5840:     my $normalid=$cdomain.'_'.$cnum;
 5841:     # need to always cache even if we get errors otherwise we keep 
 5842:     # trying and trying and trying to get the course description.
 5843:     my %envhash=();
 5844:     my %returnhash=();
 5845:     
 5846:     my $expiretime=600;
 5847:     if ($env{'request.course.id'} eq $normalid) {
 5848: 	$expiretime=120;
 5849:     }
 5850: 
 5851:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5852:     if (!$args->{'freshen_cache'}
 5853: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5854: 	foreach my $key (keys(%env)) {
 5855: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5856: 	    my ($setting) = $1;
 5857: 	    $returnhash{$setting} = $env{$key};
 5858: 	}
 5859: 	return %returnhash;
 5860:     }
 5861: 
 5862:     # get the data again
 5863: 
 5864:     if (!$args->{'one_time'}) {
 5865: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5866:     }
 5867: 
 5868:     if ($chome ne 'no_host') {
 5869:        %returnhash=&dump('environment',$cdomain,$cnum);
 5870:        if (!exists($returnhash{'con_lost'})) {
 5871: 	   my $username = $env{'user.name'}; # Defult username
 5872: 	   if(defined $args->{'user'}) {
 5873: 	       $username = $args->{'user'};
 5874: 	   }
 5875:            $returnhash{'home'}= $chome;
 5876: 	   $returnhash{'domain'} = $cdomain;
 5877: 	   $returnhash{'num'} = $cnum;
 5878:            if (!defined($returnhash{'type'})) {
 5879:                $returnhash{'type'} = 'Course';
 5880:            }
 5881:            while (my ($name,$value) = each %returnhash) {
 5882:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5883:            }
 5884:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5885:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5886: 	       $username.'_'.$cdomain.'_'.$cnum;
 5887:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5888:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5889:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5890:        }
 5891:     }
 5892:     if (!$args->{'one_time'}) {
 5893: 	&appenv(\%envhash);
 5894:     }
 5895:     return %returnhash;
 5896: }
 5897: 
 5898: sub update_released_required {
 5899:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5900:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5901:         $cid = $env{'request.course.id'};
 5902:         $cdom = $env{'course.'.$cid.'.domain'};
 5903:         $cnum = $env{'course.'.$cid.'.num'};
 5904:         $chome = $env{'course.'.$cid.'.home'};
 5905:     }
 5906:     if ($needsrelease) {
 5907:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5908:         my $needsupdate;
 5909:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5910:             $needsupdate = 1;
 5911:         } else {
 5912:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5913:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5914:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5915:                 $needsupdate = 1;
 5916:             }
 5917:         }
 5918:         if ($needsupdate) {
 5919:             my %needshash = (
 5920:                              'internal.releaserequired' => $needsrelease,
 5921:                             );
 5922:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5923:             if ($putresult eq 'ok') {
 5924:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5925:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5926:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5927:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5928:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5929:                 }
 5930:             }
 5931:         }
 5932:     }
 5933:     return;
 5934: }
 5935: 
 5936: # -------------------------------------------------See if a user is privileged
 5937: 
 5938: sub privileged {
 5939:     my ($username,$domain,$possdomains,$possroles)=@_;
 5940:     my $now = time;
 5941:     my $roles;
 5942:     if (ref($possroles) eq 'ARRAY') {
 5943:         $roles = $possroles; 
 5944:     } else {
 5945:         $roles = ['dc','su'];
 5946:     }
 5947:     if (ref($possdomains) eq 'ARRAY') {
 5948:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5949:         foreach my $dom (@{$possdomains}) {
 5950:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5951:                 (ref($privileged{$dom}) eq 'HASH')) {
 5952:                 foreach my $role (@{$roles}) {
 5953:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5954:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5955:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5956:                             return 1 unless (($end && $end < $now) ||
 5957:                                              ($start && $start > $now));
 5958:                         }
 5959:                     }
 5960:                 }
 5961:             }
 5962:         }
 5963:     } else {
 5964:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5965:         my $now = time;
 5966: 
 5967:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5968:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5969:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5970:                 return 1 unless ($tend && $tend < $now) 
 5971:                         or ($tstart && $tstart > $now);
 5972:             }
 5973:         }
 5974:     }
 5975:     return 0;
 5976: }
 5977: 
 5978: sub privileged_by_domain {
 5979:     my ($domains,$roles) = @_;
 5980:     my %privileged = ();
 5981:     my $cachetime = 60*60*24;
 5982:     my $now = time;
 5983:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5984:         return %privileged;
 5985:     }
 5986:     foreach my $dom (@{$domains}) {
 5987:         next if (ref($privileged{$dom}) eq 'HASH');
 5988:         my $needroles;
 5989:         foreach my $role (@{$roles}) {
 5990:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5991:             if (defined($cached)) {
 5992:                 if (ref($result) eq 'HASH') {
 5993:                     $privileged{$dom}{$role} = $result;
 5994:                 }
 5995:             } else {
 5996:                 $needroles = 1;
 5997:             }
 5998:         }
 5999:         if ($needroles) {
 6000:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6001:             $privileged{$dom} = {};
 6002:             foreach my $server (keys(%dompersonnel)) {
 6003:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6004:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6005:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6006:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6007:                         next if ($end && $end < $now);
 6008:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6009:                             $dompersonnel{$server}{$item};
 6010:                     }
 6011:                 }
 6012:             }
 6013:             if (ref($privileged{$dom}) eq 'HASH') {
 6014:                 foreach my $role (@{$roles}) {
 6015:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6016:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6017:                     } else {
 6018:                         my %hash = ();
 6019:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6020:                     }
 6021:                 }
 6022:             }
 6023:         }
 6024:     }
 6025:     return %privileged;
 6026: }
 6027: 
 6028: # -------------------------------------------------------- Get user privileges
 6029: 
 6030: sub rolesinit {
 6031:     my ($domain, $username) = @_;
 6032:     my %userroles = ('user.login.time' => time);
 6033:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6034: 
 6035:     # firstaccess and timerinterval are related to timed maps/resources. 
 6036:     # also, blocking can be triggered by an activating timer
 6037:     # it's saved in the user's %env.
 6038:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6039:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6040:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6041:         %timerintchk, %timerintenv);
 6042: 
 6043:     foreach my $key (keys(%firstaccess)) {
 6044:         my ($cid, $rest) = split(/\0/, $key);
 6045:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6046:     }
 6047: 
 6048:     foreach my $key (keys(%timerinterval)) {
 6049:         my ($cid,$rest) = split(/\0/,$key);
 6050:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6051:     }
 6052: 
 6053:     my %allroles=();
 6054:     my %allgroups=();
 6055: 
 6056:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6057:         my $role = $rolesdump{$area};
 6058:         $area =~ s/\_\w\w$//;
 6059: 
 6060:         my ($trole, $tend, $tstart, $group_privs);
 6061: 
 6062:         if ($role =~ /^cr/) {
 6063:         # Custom role, defined by a user 
 6064:         # e.g., user.role.cr/msu/smith/mynewrole
 6065:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6066:                 $trole = $1;
 6067:                 ($tend, $tstart) = split('_', $2);
 6068:             } else {
 6069:                 $trole = $role;
 6070:             }
 6071:         } elsif ($role =~ m|^gr/|) {
 6072:         # Role of member in a group, defined within a course/community
 6073:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6074:             ($trole, $tend, $tstart) = split(/_/, $role);
 6075:             next if $tstart eq '-1';
 6076:             ($trole, $group_privs) = split(/\//, $trole);
 6077:             $group_privs = &unescape($group_privs);
 6078:         } else {
 6079:         # Just a normal role, defined in roles.tab
 6080:             ($trole, $tend, $tstart) = split(/_/,$role);
 6081:         }
 6082: 
 6083:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6084:                  $username);
 6085:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6086: 
 6087:         # role expired or not available yet?
 6088:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6089:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6090: 
 6091:         next if $area eq '' or $trole eq '';
 6092: 
 6093:         my $spec = "$trole.$area";
 6094:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6095: 
 6096:         if ($trole =~ /^cr\//) {
 6097:         # Custom role, defined by a user
 6098:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6099:         } elsif ($trole eq 'gr') {
 6100:         # Role of a member in a group, defined within a course/community
 6101:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6102:             next;
 6103:         } else {
 6104:         # Normal role, defined in roles.tab
 6105:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6106:         }
 6107: 
 6108:         my $cid = $tdomain.'_'.$trest;
 6109:         unless ($firstaccchk{$cid}) {
 6110:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6111:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6112:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6113:                         $coursetimerstarts{$cid}{$item}; 
 6114:                 }
 6115:             }
 6116:             $firstaccchk{$cid} = 1;
 6117:         }
 6118:         unless ($timerintchk{$cid}) {
 6119:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6120:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6121:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6122:                        $coursetimerintervals{$cid}{$item};
 6123:                 }
 6124:             }
 6125:             $timerintchk{$cid} = 1;
 6126:         }
 6127:     }
 6128: 
 6129:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6130:                                                           \%allroles, \%allgroups);
 6131:     $env{'user.adv'} = $userroles{'user.adv'};
 6132:     $env{'user.rar'} = $userroles{'user.rar'};
 6133: 
 6134:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6135: }
 6136: 
 6137: sub set_arearole {
 6138:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6139:     unless ($nolog) {
 6140: # log the associated role with the area
 6141:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6142:     }
 6143:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6144: }
 6145: 
 6146: sub custom_roleprivs {
 6147:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6148:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6149:     my $homsvr = &homeserver($rauthor,$rdomain);
 6150:     if (&hostname($homsvr) ne '') {
 6151:         my ($rdummy,$roledef)=
 6152:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6153:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6154:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6155:             if (defined($syspriv)) {
 6156:                 if ($trest =~ /^$match_community$/) {
 6157:                     $syspriv =~ s/bre\&S//; 
 6158:                 }
 6159:                 $$allroles{'cm./'}.=':'.$syspriv;
 6160:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6161:             }
 6162:             if ($tdomain ne '') {
 6163:                 if (defined($dompriv)) {
 6164:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6165:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6166:                 }
 6167:                 if (($trest ne '') && (defined($coursepriv))) {
 6168:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6169:                         my $rolename = $1;
 6170:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6171:                     }
 6172:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6173:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6174:                 }
 6175:             }
 6176:         }
 6177:     }
 6178: }
 6179: 
 6180: sub course_adhocrole_privs {
 6181:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6182:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6183:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6184:         my (%currprivs,%storeprivs);
 6185:         foreach my $item (split(/:/,$coursepriv)) {
 6186:             my ($priv,$restrict) = split(/\&/,$item);
 6187:             $currprivs{$priv} = $restrict;
 6188:         }
 6189:         my (%possadd,%possremove,%full);
 6190:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6191:             my ($priv,$restrict)=split(/\&/,$item);
 6192:             $full{$priv} = $restrict;
 6193:         }
 6194:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6195:              next if ($item eq '');
 6196:              my ($rule,$rest) = split(/=/,$item);
 6197:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6198:              foreach my $priv (split(/:/,$rest)) {
 6199:                  if ($priv ne '') {
 6200:                      if ($rule eq 'off') {
 6201:                          $possremove{$priv} = 1;
 6202:                      } else {
 6203:                          $possadd{$priv} = 1;
 6204:                      }
 6205:                  }
 6206:              }
 6207:          }
 6208:          foreach my $priv (sort(keys(%full))) {
 6209:              if (exists($currprivs{$priv})) {
 6210:                  unless (exists($possremove{$priv})) {
 6211:                      $storeprivs{$priv} = $currprivs{$priv};
 6212:                  }
 6213:              } elsif (exists($possadd{$priv})) {
 6214:                  $storeprivs{$priv} = $full{$priv};
 6215:              }
 6216:          }
 6217:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6218:      }
 6219:      return $coursepriv;
 6220: }
 6221: 
 6222: sub group_roleprivs {
 6223:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6224:     my $access = 1;
 6225:     my $now = time;
 6226:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6227:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6228:     if ($access) {
 6229:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6230:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6231:     }
 6232: }
 6233: 
 6234: sub standard_roleprivs {
 6235:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6236:     if (defined($pr{$trole.':s'})) {
 6237:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6238:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6239:     }
 6240:     if ($tdomain ne '') {
 6241:         if (defined($pr{$trole.':d'})) {
 6242:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6243:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6244:         }
 6245:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6246:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6247:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6248:         }
 6249:     }
 6250: }
 6251: 
 6252: sub set_userprivs {
 6253:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6254:     my $author=0;
 6255:     my $adv=0;
 6256:     my $rar=0;
 6257:     my %grouproles = ();
 6258:     if (keys(%{$allgroups}) > 0) {
 6259:         my @groupkeys; 
 6260:         foreach my $role (keys(%{$allroles})) {
 6261:             push(@groupkeys,$role);
 6262:         }
 6263:         if (ref($groups_roles) eq 'HASH') {
 6264:             foreach my $key (keys(%{$groups_roles})) {
 6265:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6266:                     push(@groupkeys,$key);
 6267:                 }
 6268:             }
 6269:         }
 6270:         if (@groupkeys > 0) {
 6271:             foreach my $role (@groupkeys) {
 6272:                 my ($trole,$area,$sec,$extendedarea);
 6273:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6274:                     $trole = $1;
 6275:                     $area = $2;
 6276:                     $sec = $3;
 6277:                     $extendedarea = $area.$sec;
 6278:                     if (exists($$allgroups{$area})) {
 6279:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6280:                             my $spec = $trole.'.'.$extendedarea;
 6281:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6282:                                                 $$allgroups{$area}{$group};
 6283:                         }
 6284:                     }
 6285:                 }
 6286:             }
 6287:         }
 6288:     }
 6289:     foreach my $group (keys(%grouproles)) {
 6290:         $$allroles{$group} = $grouproles{$group};
 6291:     }
 6292:     foreach my $role (keys(%{$allroles})) {
 6293:         my %thesepriv;
 6294:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6295:         foreach my $item (split(/:/,$$allroles{$role})) {
 6296:             if ($item ne '') {
 6297:                 my ($privilege,$restrictions)=split(/&/,$item);
 6298:                 if ($restrictions eq '') {
 6299:                     $thesepriv{$privilege}='F';
 6300:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6301:                     $thesepriv{$privilege}.=$restrictions;
 6302:                 }
 6303:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6304:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6305:             }
 6306:         }
 6307:         my $thesestr='';
 6308:         foreach my $priv (sort(keys(%thesepriv))) {
 6309: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6310: 	}
 6311:         $userroles->{'user.priv.'.$role} = $thesestr;
 6312:     }
 6313:     return ($author,$adv,$rar);
 6314: }
 6315: 
 6316: sub role_status {
 6317:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6318:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6319:         my ($one,$two) = split(m{\./},$rolekey,2);
 6320:         (undef,undef,$$role) = split(/\./,$one,3);
 6321:         unless (!defined($$role) || $$role eq '') {
 6322:             $$where = '/'.$two;
 6323:             $$trolecode=$$role.'.'.$$where;
 6324:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6325:             $$tstatus='is';
 6326:             if ($$tstart && $$tstart>$update) {
 6327:                 $$tstatus='future';
 6328:                 if ($$tstart<$now) {
 6329:                     if ($$tstart && $$tstart>$refresh) {
 6330:                         if (($$where ne '') && ($$role ne '')) {
 6331:                             my (%allroles,%allgroups,$group_privs,
 6332:                                 %groups_roles,@rolecodes);
 6333:                             my %userroles = (
 6334:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6335:                             );
 6336:                             @rolecodes = ('cm'); 
 6337:                             my $spec=$$role.'.'.$$where;
 6338:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6339:                             if ($$role =~ /^cr\//) {
 6340:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6341:                                 push(@rolecodes,'cr');
 6342:                             } elsif ($$role eq 'gr') {
 6343:                                 push(@rolecodes,$$role);
 6344:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6345:                                                     $env{'user.name'});
 6346:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6347:                                 (undef,my $group_privs) = split(/\//,$trole);
 6348:                                 $group_privs = &unescape($group_privs);
 6349:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6350:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6351:                                 &get_groups_roles($tdomain,$trest,
 6352:                                                   \%course_roles,\@rolecodes,
 6353:                                                   \%groups_roles);
 6354:                             } else {
 6355:                                 push(@rolecodes,$$role);
 6356:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6357:                             }
 6358:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6359:                                                                    \%groups_roles);
 6360:                             &appenv(\%userroles,\@rolecodes);
 6361:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6362:                         }
 6363:                     }
 6364:                     $$tstatus = 'is';
 6365:                 }
 6366:             }
 6367:             if ($$tend) {
 6368:                 if ($$tend<$update) {
 6369:                     $$tstatus='expired';
 6370:                 } elsif ($$tend<$now) {
 6371:                     $$tstatus='will_not';
 6372:                 }
 6373:             }
 6374:         }
 6375:     }
 6376: }
 6377: 
 6378: sub get_groups_roles {
 6379:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6380:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6381:                   (ref($rolecodes) eq 'ARRAY') && 
 6382:                   (ref($groups_roles) eq 'HASH')); 
 6383:     if (keys(%{$cdom_courseroles}) > 0) {
 6384:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6385:         if ($cdom ne '' && $cnum ne '') {
 6386:             foreach my $key (keys(%{$cdom_courseroles})) {
 6387:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6388:                     my $crsrole = $1;
 6389:                     my $crssec = $2;
 6390:                     if ($crsrole =~ /^cr/) {
 6391:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6392:                             push(@{$rolecodes},'cr');
 6393:                         }
 6394:                     } else {
 6395:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6396:                             push(@{$rolecodes},$crsrole);
 6397:                         }
 6398:                     }
 6399:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6400:                     if ($crssec ne '') {
 6401:                         $rolekey .= "/$crssec";
 6402:                     }
 6403:                     $rolekey .= './';
 6404:                     $groups_roles->{$rolekey} = $rolecodes;
 6405:                 }
 6406:             }
 6407:         }
 6408:     }
 6409:     return;
 6410: }
 6411: 
 6412: sub delete_env_groupprivs {
 6413:     my ($where,$courseroles,$possroles) = @_;
 6414:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6415:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6416:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6417:         %{$courseroles->{$udom}} =
 6418:             &get_my_roles('','','userroles',['active'],
 6419:                           $possroles,[$udom],1);
 6420:     }
 6421:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6422:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6423:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6424:             my $area = '/'.$cdom.'/'.$cnum;
 6425:             my $privkey = "user.priv.$crsrole.$area";
 6426:             if ($crssec ne '') {
 6427:                 $privkey .= '/'.$crssec;
 6428:             }
 6429:             $privkey .= ".$area/$group";
 6430:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6431:         }
 6432:     }
 6433:     return;
 6434: }
 6435: 
 6436: sub check_adhoc_privs {
 6437:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6438:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6439:     if ($sec) {
 6440:         $cckey .= '/'.$sec;
 6441:     } 
 6442:     my $setprivs;
 6443:     if ($env{$cckey}) {
 6444:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6445:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6446:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6447:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6448:             $setprivs = 1;
 6449:         }
 6450:     } else {
 6451:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6452:         $setprivs = 1;
 6453:     }
 6454:     return $setprivs;
 6455: }
 6456: 
 6457: sub set_adhoc_privileges {
 6458: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6459:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6460:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6461:     if ($sec ne '') {
 6462:         $area .= '/'.$sec;
 6463:     }
 6464:     my $spec = $role.'.'.$area;
 6465:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6466:                                   $env{'user.name'},1);
 6467:     my %rolehash = ();
 6468:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6469:         my $rolename = $1;
 6470:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6471:         my %domdef = &get_domain_defaults($dcdom);
 6472:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6473:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6474:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6475:             }
 6476:         }
 6477:     } else {
 6478:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6479:     }
 6480:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6481:     &appenv(\%userroles,[$role,'cm']);
 6482:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6483:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6484:         &appenv( {'request.role'        => $spec,
 6485:                   'request.role.domain' => $dcdom,
 6486:                   'request.course.sec'  => $sec,
 6487:                  }
 6488:                );
 6489:         my $tadv=0;
 6490:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6491:         &appenv({'request.role.adv'    => $tadv});
 6492:     }
 6493: }
 6494: 
 6495: # --------------------------------------------------------------- get interface
 6496: 
 6497: sub get {
 6498:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6499:    my $items='';
 6500:    foreach my $item (@$storearr) {
 6501:        $items.=&escape($item).'&';
 6502:    }
 6503:    $items=~s/\&$//;
 6504:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6505:    if (!$uname) { $uname=$env{'user.name'}; }
 6506:    my $uhome=&homeserver($uname,$udomain);
 6507: 
 6508:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6509:    my @pairs=split(/\&/,$rep);
 6510:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6511:      return @pairs;
 6512:    }
 6513:    my %returnhash=();
 6514:    my $i=0;
 6515:    foreach my $item (@$storearr) {
 6516:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6517:       $i++;
 6518:    }
 6519:    return %returnhash;
 6520: }
 6521: 
 6522: # --------------------------------------------------------------- del interface
 6523: 
 6524: sub del {
 6525:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6526:    my $items='';
 6527:    foreach my $item (@$storearr) {
 6528:        $items.=&escape($item).'&';
 6529:    }
 6530: 
 6531:    $items=~s/\&$//;
 6532:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6533:    if (!$uname) { $uname=$env{'user.name'}; }
 6534:    my $uhome=&homeserver($uname,$udomain);
 6535:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6536: }
 6537: 
 6538: # -------------------------------------------------------------- dump interface
 6539: 
 6540: sub unserialize {
 6541:     my ($rep, $escapedkeys) = @_;
 6542: 
 6543:     return {} if $rep =~ /^error/;
 6544: 
 6545:     my %returnhash=();
 6546: 	foreach my $item (split(/\&/,$rep)) {
 6547: 	    my ($key, $value) = split(/=/, $item, 2);
 6548: 	    $key = unescape($key) unless $escapedkeys;
 6549: 	    next if $key =~ /^error: 2 /;
 6550: 	    $returnhash{$key} = &thaw_unescape($value);
 6551: 	}
 6552:     #return %returnhash;
 6553:     return \%returnhash;
 6554: }        
 6555: 
 6556: # see Lond::dump_with_regexp
 6557: # if $escapedkeys hash keys won't get unescaped.
 6558: sub dump {
 6559:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6560:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6561:     if (!$uname) { $uname=$env{'user.name'}; }
 6562:     my $uhome=&homeserver($uname,$udomain);
 6563: 
 6564:     if ($regexp) {
 6565:         $regexp=&escape($regexp);
 6566:     } else {
 6567:         $regexp='.';
 6568:     }
 6569:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6570:         # user is hosted on this machine
 6571:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6572:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6573:         return %{unserialize($reply, $escapedkeys)};
 6574:     }
 6575:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6576:     my @pairs=split(/\&/,$rep);
 6577:     my %returnhash=();
 6578:     if (!($rep =~ /^error/ )) {
 6579: 	foreach my $item (@pairs) {
 6580: 	    my ($key,$value)=split(/=/,$item,2);
 6581:         $key = unescape($key) unless $escapedkeys;
 6582:         #$key = &unescape($key);
 6583: 	    next if ($key =~ /^error: 2 /);
 6584: 	    $returnhash{$key}=&thaw_unescape($value);
 6585: 	}
 6586:     }
 6587:     return %returnhash;
 6588: }
 6589: 
 6590: 
 6591: # --------------------------------------------------------- dumpstore interface
 6592: 
 6593: sub dumpstore {
 6594:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6595:    # same as dump but keys must be escaped. They may contain colon separated
 6596:    # lists of values that may themself contain colons (e.g. symbs).
 6597:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6598: }
 6599: 
 6600: # -------------------------------------------------------------- keys interface
 6601: 
 6602: sub getkeys {
 6603:    my ($namespace,$udomain,$uname)=@_;
 6604:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6605:    if (!$uname) { $uname=$env{'user.name'}; }
 6606:    my $uhome=&homeserver($uname,$udomain);
 6607:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6608:    my @keyarray=();
 6609:    foreach my $key (split(/\&/,$rep)) {
 6610:       next if ($key =~ /^error: 2 /);
 6611:       push(@keyarray,&unescape($key));
 6612:    }
 6613:    return @keyarray;
 6614: }
 6615: 
 6616: # --------------------------------------------------------------- currentdump
 6617: sub currentdump {
 6618:    my ($courseid,$sdom,$sname)=@_;
 6619:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6620:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6621:    $sname    = $env{'user.name'}         if (! defined($sname));
 6622:    my $uhome = &homeserver($sname,$sdom);
 6623:    my $rep;
 6624: 
 6625:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6626:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6627:                    $courseid)));
 6628:    } else {
 6629:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6630:    }
 6631: 
 6632:    return if ($rep =~ /^(error:|no_such_host)/);
 6633:    #
 6634:    my %returnhash=();
 6635:    #
 6636:    if ($rep eq 'unknown_cmd') {
 6637:        # an old lond will not know currentdump
 6638:        # Do a dump and make it look like a currentdump
 6639:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6640:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6641:        my %hash = @tmp;
 6642:        @tmp=();
 6643:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6644:    } else {
 6645:        my @pairs=split(/\&/,$rep);
 6646:        foreach my $pair (@pairs) {
 6647:            my ($key,$value)=split(/=/,$pair,2);
 6648:            my ($symb,$param) = split(/:/,$key);
 6649:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6650:                                                         &thaw_unescape($value);
 6651:        }
 6652:    }
 6653:    return %returnhash;
 6654: }
 6655: 
 6656: sub convert_dump_to_currentdump{
 6657:     my %hash = %{shift()};
 6658:     my %returnhash;
 6659:     # Code ripped from lond, essentially.  The only difference
 6660:     # here is the unescaping done by lonnet::dump().  Conceivably
 6661:     # we might run in to problems with parameter names =~ /^v\./
 6662:     while (my ($key,$value) = each(%hash)) {
 6663:         my ($v,$symb,$param) = split(/:/,$key);
 6664: 	$symb  = &unescape($symb);
 6665: 	$param = &unescape($param);
 6666:         next if ($v eq 'version' || $symb eq 'keys');
 6667:         next if (exists($returnhash{$symb}) &&
 6668:                  exists($returnhash{$symb}->{$param}) &&
 6669:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6670:         $returnhash{$symb}->{$param}=$value;
 6671:         $returnhash{$symb}->{'v.'.$param}=$v;
 6672:     }
 6673:     #
 6674:     # Remove all of the keys in the hashes which keep track of
 6675:     # the version of the parameter.
 6676:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6677:         # use a foreach because we are going to delete from the hash.
 6678:         foreach my $key (keys(%$param_hash)) {
 6679:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6680:         }
 6681:     }
 6682:     return \%returnhash;
 6683: }
 6684: 
 6685: # ------------------------------------------------------ critical inc interface
 6686: 
 6687: sub cinc {
 6688:     return &inc(@_,'critical');
 6689: }
 6690: 
 6691: # --------------------------------------------------------------- inc interface
 6692: 
 6693: sub inc {
 6694:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6695:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6696:     if (!$uname) { $uname=$env{'user.name'}; }
 6697:     my $uhome=&homeserver($uname,$udomain);
 6698:     my $items='';
 6699:     if (! ref($store)) {
 6700:         # got a single value, so use that instead
 6701:         $items = &escape($store).'=&';
 6702:     } elsif (ref($store) eq 'SCALAR') {
 6703:         $items = &escape($$store).'=&';        
 6704:     } elsif (ref($store) eq 'ARRAY') {
 6705:         $items = join('=&',map {&escape($_);} @{$store});
 6706:     } elsif (ref($store) eq 'HASH') {
 6707:         while (my($key,$value) = each(%{$store})) {
 6708:             $items.= &escape($key).'='.&escape($value).'&';
 6709:         }
 6710:     }
 6711:     $items=~s/\&$//;
 6712:     if ($critical) {
 6713: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6714:     } else {
 6715: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6716:     }
 6717: }
 6718: 
 6719: # --------------------------------------------------------------- put interface
 6720: 
 6721: sub put {
 6722:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6723:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6724:    if (!$uname) { $uname=$env{'user.name'}; }
 6725:    my $uhome=&homeserver($uname,$udomain);
 6726:    my $items='';
 6727:    foreach my $item (keys(%$storehash)) {
 6728:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6729:    }
 6730:    $items=~s/\&$//;
 6731:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6732: }
 6733: 
 6734: # ------------------------------------------------------------ newput interface
 6735: 
 6736: sub newput {
 6737:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6738:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6739:    if (!$uname) { $uname=$env{'user.name'}; }
 6740:    my $uhome=&homeserver($uname,$udomain);
 6741:    my $items='';
 6742:    foreach my $key (keys(%$storehash)) {
 6743:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6744:    }
 6745:    $items=~s/\&$//;
 6746:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6747: }
 6748: 
 6749: # ---------------------------------------------------------  putstore interface
 6750: 
 6751: sub putstore {
 6752:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6753:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6754:    if (!$uname) { $uname=$env{'user.name'}; }
 6755:    my $uhome=&homeserver($uname,$udomain);
 6756:    my $items='';
 6757:    foreach my $key (keys(%$storehash)) {
 6758:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6759:    }
 6760:    $items=~s/\&$//;
 6761:    my $esc_symb=&escape($symb);
 6762:    my $esc_v=&escape($version);
 6763:    my $reply =
 6764:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6765: 	      $uhome);
 6766:    if (($tolog) && ($reply eq 'ok')) {
 6767:        my $namevalue='';
 6768:        foreach my $key (keys(%{$storehash})) {
 6769:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6770:        }
 6771:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6772:                      '&host='.&escape($perlvar{'lonHostID'}).
 6773:                      '&version='.$esc_v.
 6774:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6775:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6776:    }
 6777:    if ($reply eq 'unknown_cmd') {
 6778:        # gfall back to way things use to be done
 6779:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6780: 			    $uname);
 6781:    }
 6782:    return $reply;
 6783: }
 6784: 
 6785: sub old_putstore {
 6786:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6787:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6788:     if (!$uname) { $uname=$env{'user.name'}; }
 6789:     my $uhome=&homeserver($uname,$udomain);
 6790:     my %newstorehash;
 6791:     foreach my $item (keys(%$storehash)) {
 6792: 	my $key = $version.':'.&escape($symb).':'.$item;
 6793: 	$newstorehash{$key} = $storehash->{$item};
 6794:     }
 6795:     my $items='';
 6796:     my %allitems = ();
 6797:     foreach my $item (keys(%newstorehash)) {
 6798: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6799: 	    my $key = $1.':keys:'.$2;
 6800: 	    $allitems{$key} .= $3.':';
 6801: 	}
 6802: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6803:     }
 6804:     foreach my $item (keys(%allitems)) {
 6805: 	$allitems{$item} =~ s/\:$//;
 6806: 	$items.= $item.'='.$allitems{$item}.'&';
 6807:     }
 6808:     $items=~s/\&$//;
 6809:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6810: }
 6811: 
 6812: # ------------------------------------------------------ critical put interface
 6813: 
 6814: sub cput {
 6815:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6816:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6817:    if (!$uname) { $uname=$env{'user.name'}; }
 6818:    my $uhome=&homeserver($uname,$udomain);
 6819:    my $items='';
 6820:    foreach my $item (keys(%$storehash)) {
 6821:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6822:    }
 6823:    $items=~s/\&$//;
 6824:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6825: }
 6826: 
 6827: # -------------------------------------------------------------- eget interface
 6828: 
 6829: sub eget {
 6830:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6831:    my $items='';
 6832:    foreach my $item (@$storearr) {
 6833:        $items.=&escape($item).'&';
 6834:    }
 6835:    $items=~s/\&$//;
 6836:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6837:    if (!$uname) { $uname=$env{'user.name'}; }
 6838:    my $uhome=&homeserver($uname,$udomain);
 6839:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6840:    my @pairs=split(/\&/,$rep);
 6841:    my %returnhash=();
 6842:    my $i=0;
 6843:    foreach my $item (@$storearr) {
 6844:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6845:       $i++;
 6846:    }
 6847:    return %returnhash;
 6848: }
 6849: 
 6850: # ------------------------------------------------------------ tmpput interface
 6851: sub tmpput {
 6852:     my ($storehash,$server,$context)=@_;
 6853:     my $items='';
 6854:     foreach my $item (keys(%$storehash)) {
 6855: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6856:     }
 6857:     $items=~s/\&$//;
 6858:     if (defined($context)) {
 6859:         $items .= ':'.&escape($context);
 6860:     }
 6861:     return &reply("tmpput:$items",$server);
 6862: }
 6863: 
 6864: # ------------------------------------------------------------ tmpget interface
 6865: sub tmpget {
 6866:     my ($token,$server)=@_;
 6867:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6868:     my $rep=&reply("tmpget:$token",$server);
 6869:     my %returnhash;
 6870:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6871:         return %returnhash;
 6872:     }
 6873:     foreach my $item (split(/\&/,$rep)) {
 6874: 	my ($key,$value)=split(/=/,$item);
 6875: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6876:     }
 6877:     return %returnhash;
 6878: }
 6879: 
 6880: # ------------------------------------------------------------ tmpdel interface
 6881: sub tmpdel {
 6882:     my ($token,$server)=@_;
 6883:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6884:     return &reply("tmpdel:$token",$server);
 6885: }
 6886: 
 6887: # ------------------------------------------------------------ get_timebased_id 
 6888: 
 6889: sub get_timebased_id {
 6890:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6891:         $maxtries) = @_;
 6892:     my ($newid,$error,$dellock);
 6893:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6894:         return ('','ok','invalid call to get suffix');
 6895:     }
 6896: 
 6897: # set defaults for any optional args for which values were not supplied
 6898:     if ($who eq '') {
 6899:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6900:     }
 6901:     if (!$locktries) {
 6902:         $locktries = 3;
 6903:     }
 6904:     if (!$maxtries) {
 6905:         $maxtries = 10;
 6906:     }
 6907:     
 6908:     if (($cdom eq '') || ($cnum eq '')) {
 6909:         if ($env{'request.course.id'}) {
 6910:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6911:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6912:         }
 6913:         if (($cdom eq '') || ($cnum eq '')) {
 6914:             return ('','ok','call to get suffix not in course context');
 6915:         }
 6916:     }
 6917: 
 6918: # construct locking item
 6919:     my $lockhash = {
 6920:                       $prefix."\0".'locked_'.$keyid => $who,
 6921:                    };
 6922:     my $tries = 0;
 6923: 
 6924: # attempt to get lock on nohist_$namespace file
 6925:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6926:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6927:         $tries ++;
 6928:         sleep 1;
 6929:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6930:     }
 6931: 
 6932: # attempt to get unique identifier, based on current timestamp
 6933:     if ($gotlock eq 'ok') {
 6934:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6935:         my $id = time;
 6936:         $newid = $id;
 6937:         if ($idtype eq 'addcode') {
 6938:             $newid .= &sixnum_code();
 6939:         }
 6940:         my $idtries = 0;
 6941:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6942:             if ($idtype eq 'concat') {
 6943:                 $newid = $id.$idtries;
 6944:             } elsif ($idtype eq 'addcode') {
 6945:                 $newid = $newid.&sixnum_code();
 6946:             } else {
 6947:                 $newid ++;
 6948:             }
 6949:             $idtries ++;
 6950:         }
 6951:         if (!exists($inuse{$prefix."\0".$newid})) {
 6952:             my %new_item =  (
 6953:                               $prefix."\0".$newid => $who,
 6954:                             );
 6955:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6956:                                                  $cdom,$cnum);
 6957:             if ($putresult ne 'ok') {
 6958:                 undef($newid);
 6959:                 $error = 'error saving new item: '.$putresult;
 6960:             }
 6961:         } else {
 6962:              undef($newid);
 6963:              $error = ('error: no unique suffix available for the new item ');
 6964:         }
 6965: #  remove lock
 6966:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6967:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6968:     } else {
 6969:         $error = "error: could not obtain lockfile\n";
 6970:         $dellock = 'ok';
 6971:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6972:             $dellock = 'nolock';
 6973:         }
 6974:     }
 6975:     return ($newid,$dellock,$error);
 6976: }
 6977: 
 6978: sub sixnum_code {
 6979:     my $code;
 6980:     for (0..6) {
 6981:         $code .= int( rand(9) );
 6982:     }
 6983:     return $code;
 6984: }
 6985: 
 6986: # -------------------------------------------------- portfolio access checking
 6987: 
 6988: sub portfolio_access {
 6989:     my ($requrl,$clientip) = @_;
 6990:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6991:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6992:     if ($result) {
 6993:         my %setters;
 6994:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6995:             my ($startblock,$endblock) =
 6996:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6997:             if ($startblock && $endblock) {
 6998:                 return 'B';
 6999:             }
 7000:         } else {
 7001:             my ($startblock,$endblock) =
 7002:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7003:             if ($startblock && $endblock) {
 7004:                 return 'B';
 7005:             }
 7006:         }
 7007:     }
 7008:     if ($result eq 'ok') {
 7009:        return 'F';
 7010:     } elsif ($result =~ /^[^:]+:guest_/) {
 7011:        return 'A';
 7012:     }
 7013:     return '';
 7014: }
 7015: 
 7016: sub get_portfolio_access {
 7017:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7018: 
 7019:     if (!ref($access_hash)) {
 7020: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7021: 	my %access_controls = &get_access_controls($current_perms,$group,
 7022: 						   $file_name);
 7023: 	$access_hash = $access_controls{$file_name};
 7024:     }
 7025: 
 7026:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7027:     my $now = time;
 7028:     if (ref($access_hash) eq 'HASH') {
 7029:         foreach my $key (keys(%{$access_hash})) {
 7030:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7031:             if ($start > $now) {
 7032:                 next;
 7033:             }
 7034:             if ($end && $end<$now) {
 7035:                 next;
 7036:             }
 7037:             if ($scope eq 'public') {
 7038:                 $public = $key;
 7039:                 last;
 7040:             } elsif ($scope eq 'guest') {
 7041:                 $guest = $key;
 7042:             } elsif ($scope eq 'domains') {
 7043:                 push(@domains,$key);
 7044:             } elsif ($scope eq 'users') {
 7045:                 push(@users,$key);
 7046:             } elsif ($scope eq 'course') {
 7047:                 push(@courses,$key);
 7048:             } elsif ($scope eq 'group') {
 7049:                 push(@groups,$key);
 7050:             } elsif ($scope eq 'ip') {
 7051:                 push(@ips,$key);
 7052:             }
 7053:         }
 7054:         if ($public) {
 7055:             return 'ok';
 7056:         } elsif (@ips > 0) {
 7057:             my $allowed;
 7058:             foreach my $ipkey (@ips) {
 7059:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7060:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7061:                         $allowed = 1;
 7062:                         last; 
 7063:                     }
 7064:                 }
 7065:             }
 7066:             if ($allowed) {
 7067:                 return 'ok';
 7068:             }
 7069:         }
 7070:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7071:             if ($guest) {
 7072:                 return $guest;
 7073:             }
 7074:         } else {
 7075:             if (@domains > 0) {
 7076:                 foreach my $domkey (@domains) {
 7077:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7078:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7079:                             return 'ok';
 7080:                         }
 7081:                     }
 7082:                 }
 7083:             }
 7084:             if (@users > 0) {
 7085:                 foreach my $userkey (@users) {
 7086:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7087:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7088:                             if (ref($item) eq 'HASH') {
 7089:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7090:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7091:                                     return 'ok';
 7092:                                 }
 7093:                             }
 7094:                         }
 7095:                     } 
 7096:                 }
 7097:             }
 7098:             my %roleshash;
 7099:             my @courses_and_groups = @courses;
 7100:             push(@courses_and_groups,@groups); 
 7101:             if (@courses_and_groups > 0) {
 7102:                 my (%allgroups,%allroles); 
 7103:                 my ($start,$end,$role,$sec,$group);
 7104:                 foreach my $envkey (%env) {
 7105:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7106:                         my $cid = $2.'_'.$3; 
 7107:                         if ($1 eq 'gr') {
 7108:                             $group = $4;
 7109:                             $allgroups{$cid}{$group} = $env{$envkey};
 7110:                         } else {
 7111:                             if ($4 eq '') {
 7112:                                 $sec = 'none';
 7113:                             } else {
 7114:                                 $sec = $4;
 7115:                             }
 7116:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7117:                         }
 7118:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7119:                         my $cid = $2.'_'.$3;
 7120:                         if ($4 eq '') {
 7121:                             $sec = 'none';
 7122:                         } else {
 7123:                             $sec = $4;
 7124:                         }
 7125:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7126:                     }
 7127:                 }
 7128:                 if (keys(%allroles) == 0) {
 7129:                     return;
 7130:                 }
 7131:                 foreach my $key (@courses_and_groups) {
 7132:                     my %content = %{$$access_hash{$key}};
 7133:                     my $cnum = $content{'number'};
 7134:                     my $cdom = $content{'domain'};
 7135:                     my $cid = $cdom.'_'.$cnum;
 7136:                     if (!exists($allroles{$cid})) {
 7137:                         next;
 7138:                     }    
 7139:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7140:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7141:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7142:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7143:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7144:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7145:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7146:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7147:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7148:                                         if (grep/^all$/,@sections) {
 7149:                                             return 'ok';
 7150:                                         } else {
 7151:                                             if (grep/^$sec$/,@sections) {
 7152:                                                 return 'ok';
 7153:                                             }
 7154:                                         }
 7155:                                     }
 7156:                                 }
 7157:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7158:                                     if (grep/^none$/,@groups) {
 7159:                                         return 'ok';
 7160:                                     }
 7161:                                 } else {
 7162:                                     if (grep/^all$/,@groups) {
 7163:                                         return 'ok';
 7164:                                     } 
 7165:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7166:                                         if (grep/^$group$/,@groups) {
 7167:                                             return 'ok';
 7168:                                         }
 7169:                                     }
 7170:                                 } 
 7171:                             }
 7172:                         }
 7173:                     }
 7174:                 }
 7175:             }
 7176:             if ($guest) {
 7177:                 return $guest;
 7178:             }
 7179:         }
 7180:     }
 7181:     return;
 7182: }
 7183: 
 7184: sub course_group_datechecker {
 7185:     my ($dates,$now,$status) = @_;
 7186:     my ($start,$end) = split(/\./,$dates);
 7187:     if (!$start && !$end) {
 7188:         return 'ok';
 7189:     }
 7190:     if (grep/^active$/,@{$status}) {
 7191:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7192:             return 'ok';
 7193:         }
 7194:     }
 7195:     if (grep/^previous$/,@{$status}) {
 7196:         if ($end > $now ) {
 7197:             return 'ok';
 7198:         }
 7199:     }
 7200:     if (grep/^future$/,@{$status}) {
 7201:         if ($start > $now) {
 7202:             return 'ok';
 7203:         }
 7204:     }
 7205:     return; 
 7206: }
 7207: 
 7208: sub parse_portfolio_url {
 7209:     my ($url) = @_;
 7210: 
 7211:     my ($type,$udom,$unum,$group,$file_name);
 7212:     
 7213:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7214: 	$type = 1;
 7215:         $udom = $1;
 7216:         $unum = $2;
 7217:         $file_name = $3;
 7218:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7219: 	$type = 2;
 7220:         $udom = $1;
 7221:         $unum = $2;
 7222:         $group = $3;
 7223:         $file_name = $3.'/'.$4;
 7224:     }
 7225:     if (wantarray) {
 7226: 	return ($type,$udom,$unum,$file_name,$group);
 7227:     }
 7228:     return $type;
 7229: }
 7230: 
 7231: sub is_portfolio_url {
 7232:     my ($url) = @_;
 7233:     return scalar(&parse_portfolio_url($url));
 7234: }
 7235: 
 7236: sub is_portfolio_file {
 7237:     my ($file) = @_;
 7238:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7239:         return 1;
 7240:     }
 7241:     return;
 7242: }
 7243: 
 7244: sub usertools_access {
 7245:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7246:     my ($access,%tools);
 7247:     if ($context eq '') {
 7248:         $context = 'tools';
 7249:     }
 7250:     if ($context eq 'requestcourses') {
 7251:         %tools = (
 7252:                       official   => 1,
 7253:                       unofficial => 1,
 7254:                       community  => 1,
 7255:                       textbook   => 1,
 7256:                       placement  => 1,
 7257:                       lti        => 1,
 7258:                  );
 7259:     } elsif ($context eq 'requestauthor') {
 7260:         %tools = (
 7261:                       requestauthor => 1,
 7262:                  );
 7263:     } else {
 7264:         %tools = (
 7265:                       aboutme   => 1,
 7266:                       blog      => 1,
 7267:                       webdav    => 1,
 7268:                       portfolio => 1,
 7269:                  );
 7270:     }
 7271:     return if (!defined($tools{$tool}));
 7272: 
 7273:     if (($udom eq '') || ($uname eq '')) {
 7274:         $udom = $env{'user.domain'};
 7275:         $uname = $env{'user.name'};
 7276:     }
 7277: 
 7278:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7279:         if ($action ne 'reload') {
 7280:             if ($context eq 'requestcourses') {
 7281:                 return $env{'environment.canrequest.'.$tool};
 7282:             } elsif ($context eq 'requestauthor') {
 7283:                 return $env{'environment.canrequest.author'};
 7284:             } else {
 7285:                 return $env{'environment.availabletools.'.$tool};
 7286:             }
 7287:         }
 7288:     }
 7289: 
 7290:     my ($toolstatus,$inststatus,$envkey);
 7291:     if ($context eq 'requestauthor') {
 7292:         $envkey = $context; 
 7293:     } else {
 7294:         $envkey = $context.'.'.$tool;
 7295:     }
 7296: 
 7297:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7298:          ($action ne 'reload')) {
 7299:         $toolstatus = $env{'environment.'.$envkey};
 7300:         $inststatus = $env{'environment.inststatus'};
 7301:     } else {
 7302:         if (ref($userenvref) eq 'HASH') {
 7303:             $toolstatus = $userenvref->{$envkey};
 7304:             $inststatus = $userenvref->{'inststatus'};
 7305:         } else {
 7306:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7307:             $toolstatus = $userenv{$envkey};
 7308:             $inststatus = $userenv{'inststatus'};
 7309:         }
 7310:     }
 7311: 
 7312:     if ($toolstatus ne '') {
 7313:         if ($toolstatus) {
 7314:             $access = 1;
 7315:         } else {
 7316:             $access = 0;
 7317:         }
 7318:         return $access;
 7319:     }
 7320: 
 7321:     my ($is_adv,%domdef);
 7322:     if (ref($is_advref) eq 'HASH') {
 7323:         $is_adv = $is_advref->{'is_adv'};
 7324:     } else {
 7325:         $is_adv = &is_advanced_user($udom,$uname);
 7326:     }
 7327:     if (ref($domdefref) eq 'HASH') {
 7328:         %domdef = %{$domdefref};
 7329:     } else {
 7330:         %domdef = &get_domain_defaults($udom);
 7331:     }
 7332:     if (ref($domdef{$tool}) eq 'HASH') {
 7333:         if ($is_adv) {
 7334:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7335:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7336:                     $access = 1;
 7337:                 } else {
 7338:                     $access = 0;
 7339:                 }
 7340:                 return $access;
 7341:             }
 7342:         }
 7343:         if ($inststatus ne '') {
 7344:             my ($hasaccess,$hasnoaccess);
 7345:             foreach my $affiliation (split(/:/,$inststatus)) {
 7346:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7347:                     if ($domdef{$tool}{$affiliation}) {
 7348:                         $hasaccess = 1;
 7349:                     } else {
 7350:                         $hasnoaccess = 1;
 7351:                     }
 7352:                 }
 7353:             }
 7354:             if ($hasaccess || $hasnoaccess) {
 7355:                 if ($hasaccess) {
 7356:                     $access = 1;
 7357:                 } elsif ($hasnoaccess) {
 7358:                     $access = 0; 
 7359:                 }
 7360:                 return $access;
 7361:             }
 7362:         } else {
 7363:             if ($domdef{$tool}{'default'} ne '') {
 7364:                 if ($domdef{$tool}{'default'}) {
 7365:                     $access = 1;
 7366:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7367:                     $access = 0;
 7368:                 }
 7369:                 return $access;
 7370:             }
 7371:         }
 7372:     } else {
 7373:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7374:             $access = 1;
 7375:         } else {
 7376:             $access = 0;
 7377:         }
 7378:         return $access;
 7379:     }
 7380: }
 7381: 
 7382: sub is_course_owner {
 7383:     my ($cdom,$cnum,$udom,$uname) = @_;
 7384:     if (($udom eq '') || ($uname eq '')) {
 7385:         $udom = $env{'user.domain'};
 7386:         $uname = $env{'user.name'};
 7387:     }
 7388:     unless (($udom eq '') || ($uname eq '')) {
 7389:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7390:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7391:                 return 1;
 7392:             } else {
 7393:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7394:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7395:                     return 1;
 7396:                 }
 7397:             }
 7398:         }
 7399:     }
 7400:     return;
 7401: }
 7402: 
 7403: sub is_advanced_user {
 7404:     my ($udom,$uname) = @_;
 7405:     if ($udom ne '' && $uname ne '') {
 7406:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7407:             if (wantarray) {
 7408:                 return ($env{'user.adv'},$env{'user.author'});
 7409:             } else {
 7410:                 return $env{'user.adv'};
 7411:             }
 7412:         }
 7413:     }
 7414:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7415:     my %allroles;
 7416:     my ($is_adv,$is_author);
 7417:     foreach my $role (keys(%roleshash)) {
 7418:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7419:         my $area = '/'.$tdomain.'/'.$trest;
 7420:         if ($sec ne '') {
 7421:             $area .= '/'.$sec;
 7422:         }
 7423:         if (($area ne '') && ($trole ne '')) {
 7424:             my $spec=$trole.'.'.$area;
 7425:             if ($trole =~ /^cr\//) {
 7426:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7427:             } elsif ($trole ne 'gr') {
 7428:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7429:             }
 7430:             if ($trole eq 'au') {
 7431:                 $is_author = 1;
 7432:             }
 7433:         }
 7434:     }
 7435:     foreach my $role (keys(%allroles)) {
 7436:         last if ($is_adv);
 7437:         foreach my $item (split(/:/,$allroles{$role})) {
 7438:             if ($item ne '') {
 7439:                 my ($privilege,$restrictions)=split(/&/,$item);
 7440:                 if ($privilege eq 'adv') {
 7441:                     $is_adv = 1;
 7442:                     last;
 7443:                 }
 7444:             }
 7445:         }
 7446:     }
 7447:     if (wantarray) {
 7448:         return ($is_adv,$is_author);
 7449:     }
 7450:     return $is_adv;
 7451: }
 7452: 
 7453: sub check_can_request {
 7454:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 7455:     my $canreq = 0;
 7456:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7457:         $uname = $env{'user.name'};
 7458:         $udom = $env{'user.domain'};
 7459:     }
 7460:     my ($types,$typename) = &Apache::loncommon::course_types();
 7461:     my @options = ('approval','validate','autolimit');
 7462:     my $optregex = join('|',@options);
 7463:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7464:         foreach my $type (@{$types}) {
 7465:             if (&usertools_access($uname,$udom,$type,undef,
 7466:                                   'requestcourses')) {
 7467:                 $canreq ++;
 7468:                 if (ref($request_domains) eq 'HASH') {
 7469:                     push(@{$request_domains->{$type}},$udom);
 7470:                 }
 7471:                 if ($dom eq $udom) {
 7472:                     $can_request->{$type} = 1;
 7473:                 }
 7474:             }
 7475:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 7476:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 7477:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7478:                 if (@curr > 0) {
 7479:                     foreach my $item (@curr) {
 7480:                         if (ref($request_domains) eq 'HASH') {
 7481:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7482:                             if ($otherdom ne '') {
 7483:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7484:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7485:                                         push(@{$request_domains->{$type}},$otherdom);
 7486:                                     }
 7487:                                 } else {
 7488:                                     push(@{$request_domains->{$type}},$otherdom);
 7489:                                 }
 7490:                             }
 7491:                         }
 7492:                     }
 7493:                     unless ($dom eq $env{'user.domain'}) {
 7494:                         $canreq ++;
 7495:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7496:                             $can_request->{$type} = 1;
 7497:                         }
 7498:                     }
 7499:                 }
 7500:             }
 7501:         }
 7502:     }
 7503:     return $canreq;
 7504: }
 7505: 
 7506: # ---------------------------------------------- Custom access rule evaluation
 7507: 
 7508: sub customaccess {
 7509:     my ($priv,$uri)=@_;
 7510:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7511:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7512:     $udom = &LONCAPA::clean_domain($udom);
 7513:     $ucrs = &LONCAPA::clean_username($ucrs);
 7514:     my $access=0;
 7515:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7516: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7517: 	if ($type eq 'user') {
 7518: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7519: 		my ($tdom,$tuname)=split(m{/},$scope);
 7520: 		if ($tdom) {
 7521: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7522: 		}
 7523: 		if ($tuname) {
 7524: 		    if ($tuname ne $env{'user.name'}) { next; }
 7525: 		}
 7526: 		$access=($effect eq 'allow');
 7527: 		last;
 7528: 	    }
 7529: 	} else {
 7530: 	    if ($role) {
 7531: 		if ($role ne $urole) { next; }
 7532: 	    }
 7533: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7534: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7535: 		if ($tdom) {
 7536: 		    if ($tdom ne $udom) { next; }
 7537: 		}
 7538: 		if ($tcrs) {
 7539: 		    if ($tcrs ne $ucrs) { next; }
 7540: 		}
 7541: 		if ($tsec) {
 7542: 		    if ($tsec ne $usec) { next; }
 7543: 		}
 7544: 		$access=($effect eq 'allow');
 7545: 		last;
 7546: 	    }
 7547: 	    if ($realm eq '' && $role eq '') {
 7548: 		$access=($effect eq 'allow');
 7549: 	    }
 7550: 	}
 7551:     }
 7552:     return $access;
 7553: }
 7554: 
 7555: # ------------------------------------------------- Check for a user privilege
 7556: 
 7557: sub allowed {
 7558:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7559:     my $ver_orguri=$uri;
 7560:     $uri=&deversion($uri);
 7561:     my $orguri=$uri;
 7562:     $uri=&declutter($uri);
 7563: 
 7564:     if ($priv eq 'evb') {
 7565: # Evade communication block restrictions for specified role in a course
 7566:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7567:             return $1;
 7568:         } else {
 7569:             return;
 7570:         }
 7571:     }
 7572: 
 7573:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7574: # Free bre access to adm and meta resources
 7575:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7576: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7577: 	&& ($priv eq 'bre')) {
 7578: 	return 'F';
 7579:     }
 7580: 
 7581: # Free bre access to user's own portfolio contents
 7582:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7583:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7584: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7585:         my %setters;
 7586:         my ($startblock,$endblock) = 
 7587:             &Apache::loncommon::blockcheck(\%setters,'port');
 7588:         if ($startblock && $endblock) {
 7589:             return 'B';
 7590:         } else {
 7591:             return 'F';
 7592:         }
 7593:     }
 7594: 
 7595: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7596:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7597:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7598:         if (exists($env{'request.course.id'})) {
 7599:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7600:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7601:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7602:                 my $courseprivid=$env{'request.course.id'};
 7603:                 $courseprivid=~s/\_/\//;
 7604:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7605:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7606:                     return $1; 
 7607:                 } else {
 7608:                     if ($env{'request.course.sec'}) {
 7609:                         $courseprivid.='/'.$env{'request.course.sec'};
 7610:                     }
 7611:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7612:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7613:                         return $2;
 7614:                     }
 7615:                 }
 7616:             }
 7617:         }
 7618:     }
 7619: 
 7620: # Free bre to public access
 7621: 
 7622:     if ($priv eq 'bre') {
 7623:         my $copyright;
 7624:         unless ($uri =~ /ext\.tool/) {
 7625:             $copyright=&metadata($uri,'copyright');
 7626:         }
 7627: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7628:            return 'F'; 
 7629:         }
 7630:         if ($copyright eq 'priv') {
 7631:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7632: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7633: 		return '';
 7634:             }
 7635:         }
 7636:         if ($copyright eq 'domain') {
 7637:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7638: 	    unless (($env{'user.domain'} eq $1) ||
 7639:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7640: 		return '';
 7641:             }
 7642:         }
 7643:         if ($env{'request.role'}=~ /li\.\//) {
 7644:             # Library role, so allow browsing of resources in this domain.
 7645:             return 'F';
 7646:         }
 7647:         if ($copyright eq 'custom') {
 7648: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7649:         }
 7650:     }
 7651:     # Domain coordinator is trying to create a course
 7652:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7653:         # uri is the requested domain in this case.
 7654:         # comparison to 'request.role.domain' shows if the user has selected
 7655:         # a role of dc for the domain in question.
 7656:         return 'F' if ($uri eq $env{'request.role.domain'});
 7657:     }
 7658: 
 7659:     my $thisallowed='';
 7660:     my $statecond=0;
 7661:     my $courseprivid='';
 7662: 
 7663:     my $ownaccess;
 7664:     # Community Coordinator or Assistant Co-author browsing resource space.
 7665:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7666:         if ($uri eq '') {
 7667:             $ownaccess = 1;
 7668:         } else {
 7669:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7670:                 my $udom = $env{'user.domain'};
 7671:                 my $uname = $env{'user.name'};
 7672:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7673:                     $ownaccess = 1;
 7674:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7675:                     unless ($uri =~ m{\.\./}) {
 7676:                         $ownaccess = 1;
 7677:                     }
 7678:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7679:                     my $now = time;
 7680:                     if ($uri =~ m{^([^/]+)/?$}) {
 7681:                         my $adom = $1;
 7682:                         foreach my $key (keys(%env)) {
 7683:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7684:                                 my ($start,$end) = split('.',$env{$key});
 7685:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7686:                                     $ownaccess = 1;
 7687:                                     last;
 7688:                                 }
 7689:                             }
 7690:                         }
 7691:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7692:                         my $adom = $1;
 7693:                         my $aname = $2;
 7694:                         foreach my $role ('ca','aa') { 
 7695:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7696:                                 my ($start,$end) =
 7697:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7698:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7699:                                     $ownaccess = 1;
 7700:                                     last;
 7701:                                 }
 7702:                             }
 7703:                         }
 7704:                     }
 7705:                 }
 7706:             }
 7707:         }
 7708:     }
 7709: 
 7710: # Course
 7711: 
 7712:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7713:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7714:             $thisallowed.=$1;
 7715:         }
 7716:     }
 7717: 
 7718: # Domain
 7719: 
 7720:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7721:        =~/\Q$priv\E\&([^\:]*)/) {
 7722:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7723:             $thisallowed.=$1;
 7724:         }
 7725:     }
 7726: 
 7727: # User who is not author or co-author might still be able to edit
 7728: # resource of an author in the domain (e.g., if Domain Coordinator).
 7729:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7730:         (&allowed('mdc',$env{'request.course.id'}))) {
 7731:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7732:             $thisallowed.=$1;
 7733:         }
 7734:     }
 7735: 
 7736: # Course: uri itself is a course
 7737:     my $courseuri=$uri;
 7738:     $courseuri=~s/\_(\d)/\/$1/;
 7739:     $courseuri=~s/^([^\/])/\/$1/;
 7740: 
 7741:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7742:        =~/\Q$priv\E\&([^\:]*)/) {
 7743:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7744:             $thisallowed.=$1;
 7745:         }
 7746:     }
 7747: 
 7748: # URI is an uploaded document for this course, default permissions don't matter
 7749: # not allowing 'edit' access (editupload) to uploaded course docs
 7750:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7751: 	$thisallowed='';
 7752:         my ($match)=&is_on_map($uri);
 7753:         if ($match) {
 7754:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7755:                   =~/\Q$priv\E\&([^\:]*)/) {
 7756:                 my $value = $1;
 7757:                 if ($noblockcheck) {
 7758:                     $thisallowed.=$value;
 7759:                 } else {
 7760:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7761:                     if (@blockers > 0) {
 7762:                         $thisallowed = 'B';
 7763:                     } else {
 7764:                         $thisallowed.=$value;
 7765:                     }
 7766:                 }
 7767:             }
 7768:         } else {
 7769:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7770:             if ($refuri) {
 7771:                 if ($refuri =~ m|^/adm/|) {
 7772:                     $thisallowed='F';
 7773:                 } else {
 7774:                     $refuri=&declutter($refuri);
 7775:                     my ($match) = &is_on_map($refuri);
 7776:                     if ($match) {
 7777:                         if ($noblockcheck) {
 7778:                             $thisallowed='F';
 7779:                         } else {
 7780:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7781:                             if (@blockers > 0) {
 7782:                                 $thisallowed = 'B';
 7783:                             } else {
 7784:                                 $thisallowed='F';
 7785:                             }
 7786:                         }
 7787:                     }
 7788:                 }
 7789:             }
 7790:         }
 7791:     }
 7792: 
 7793:     if ($priv eq 'bre'
 7794: 	&& $thisallowed ne 'F' 
 7795: 	&& $thisallowed ne '2'
 7796: 	&& &is_portfolio_url($uri)) {
 7797: 	$thisallowed = &portfolio_access($uri,$clientip);
 7798:     }
 7799: 
 7800: # Full access at system, domain or course-wide level? Exit.
 7801:     if ($thisallowed=~/F/) {
 7802: 	return 'F';
 7803:     }
 7804: 
 7805: # If this is generating or modifying users, exit with special codes
 7806: 
 7807:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7808: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7809: 	    my ($audom,$auname)=split('/',$uri);
 7810: # no author name given, so this just checks on the general right to make a co-author in this domain
 7811: 	    unless ($auname) { return $thisallowed; }
 7812: # an author name is given, so we are about to actually make a co-author for a certain account
 7813: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7814: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7815: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7816: 	}
 7817: 	return $thisallowed;
 7818:     }
 7819: #
 7820: # Gathered so far: system, domain and course wide privileges
 7821: #
 7822: # Course: See if uri or referer is an individual resource that is part of 
 7823: # the course
 7824: 
 7825:     if ($env{'request.course.id'}) {
 7826: 
 7827:        $courseprivid=$env{'request.course.id'};
 7828:        if ($env{'request.course.sec'}) {
 7829:           $courseprivid.='/'.$env{'request.course.sec'};
 7830:        }
 7831:        $courseprivid=~s/\_/\//;
 7832:        my $checkreferer=1;
 7833:        my ($match,$cond)=&is_on_map($uri);
 7834:        if ($match) {
 7835:            $statecond=$cond;
 7836:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7837:                =~/\Q$priv\E\&([^\:]*)/) {
 7838:                my $value = $1;
 7839:                if ($priv eq 'bre') {
 7840:                    if ($noblockcheck) {
 7841:                        $thisallowed.=$value;
 7842:                    } else {
 7843:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7844:                        if (@blockers > 0) {
 7845:                            $thisallowed = 'B';
 7846:                        } else {
 7847:                            $thisallowed.=$value;
 7848:                        }
 7849:                    }
 7850:                } else {
 7851:                    $thisallowed.=$value;
 7852:                }
 7853:                $checkreferer=0;
 7854:            }
 7855:        }
 7856:        
 7857:        if ($checkreferer) {
 7858: 	  my $refuri=$env{'httpref.'.$orguri};
 7859:             unless ($refuri) {
 7860:                 foreach my $key (keys(%env)) {
 7861: 		    if ($key=~/^httpref\..*\*/) {
 7862: 			my $pattern=$key;
 7863:                         $pattern=~s/^httpref\.\/res\///;
 7864:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7865:                         $pattern=~s/\//\\\//g;
 7866:                         if ($orguri=~/$pattern/) {
 7867: 			    $refuri=$env{$key};
 7868:                         }
 7869:                     }
 7870:                 }
 7871:             }
 7872: 
 7873:          if ($refuri) { 
 7874: 	  $refuri=&declutter($refuri);
 7875:           my ($match,$cond)=&is_on_map($refuri);
 7876:             if ($match) {
 7877:               my $refstatecond=$cond;
 7878:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7879:                   =~/\Q$priv\E\&([^\:]*)/) {
 7880:                   my $value = $1;
 7881:                   if ($priv eq 'bre') {
 7882:                       if ($noblockcheck) {
 7883:                           $thisallowed.=$value;
 7884:                       } else {
 7885:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7886:                           if (@blockers > 0) {
 7887:                               $thisallowed = 'B';
 7888:                           } else {
 7889:                               $thisallowed.=$value;
 7890:                           }
 7891:                       }
 7892:                   } else {
 7893:                       $thisallowed.=$value;
 7894:                   }
 7895:                   $uri=$refuri;
 7896:                   $statecond=$refstatecond;
 7897:               }
 7898:           }
 7899:         }
 7900:        }
 7901:    }
 7902: 
 7903: #
 7904: # Gathered now: all privileges that could apply, and condition number
 7905: # 
 7906: #
 7907: # Full or no access?
 7908: #
 7909: 
 7910:     if ($thisallowed=~/F/) {
 7911: 	return 'F';
 7912:     }
 7913: 
 7914:     unless ($thisallowed) {
 7915:         return '';
 7916:     }
 7917: 
 7918: # Restrictions exist, deal with them
 7919: #
 7920: #   C:according to course preferences
 7921: #   R:according to resource settings
 7922: #   L:unless locked
 7923: #   X:according to user session state
 7924: #
 7925: 
 7926: # Possibly locked functionality, check all courses
 7927: # Locks might take effect only after 10 minutes cache expiration for other
 7928: # courses, and 2 minutes for current course
 7929: 
 7930:     my $envkey;
 7931:     if ($thisallowed=~/L/) {
 7932:         foreach $envkey (keys(%env)) {
 7933:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7934:                my $courseid=$2;
 7935:                my $roleid=$1.'.'.$2;
 7936:                $courseid=~s/^\///;
 7937:                my $expiretime=600;
 7938:                if ($env{'request.role'} eq $roleid) {
 7939: 		  $expiretime=120;
 7940:                }
 7941: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7942:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7943:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7944: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7945:                }
 7946:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7947:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7948: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7949:                        &log($env{'user.domain'},$env{'user.name'},
 7950:                             $env{'user.home'},
 7951:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7952:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7953:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7954: 		       return '';
 7955:                    }
 7956:                }
 7957:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7958:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7959: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7960:                        &log($env{'user.domain'},$env{'user.name'},
 7961:                             $env{'user.home'},
 7962:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7963:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7964:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7965: 		       return '';
 7966:                    }
 7967:                }
 7968: 	   }
 7969:        }
 7970:     }
 7971:    
 7972: #
 7973: # Rest of the restrictions depend on selected course
 7974: #
 7975: 
 7976:     unless ($env{'request.course.id'}) {
 7977: 	if ($thisallowed eq 'A') {
 7978: 	    return 'A';
 7979:         } elsif ($thisallowed eq 'B') {
 7980:             return 'B';
 7981: 	} else {
 7982: 	    return '1';
 7983: 	}
 7984:     }
 7985: 
 7986: #
 7987: # Now user is definitely in a course
 7988: #
 7989: 
 7990: 
 7991: # Course preferences
 7992: 
 7993:    if ($thisallowed=~/C/) {
 7994:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7995:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7996:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7997: 	   =~/\Q$rolecode\E/) {
 7998: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7999: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8000: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8001: 			$env{'request.course.id'});
 8002: 	   }
 8003:            return '';
 8004:        }
 8005: 
 8006:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8007: 	   =~/\Q$unamedom\E/) {
 8008: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 8009: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8010: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8011: 			$env{'request.course.id'});
 8012: 	   }
 8013:            return '';
 8014:        }
 8015:    }
 8016: 
 8017: # Resource preferences
 8018: 
 8019:    if ($thisallowed=~/R/) {
 8020:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8021:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8022: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8023: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8024: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8025: 	   }
 8026: 	   return '';
 8027:        }
 8028:    }
 8029: 
 8030: # Restricted by state or randomout?
 8031: 
 8032:    if ($thisallowed=~/X/) {
 8033:       if ($env{'acc.randomout'}) {
 8034: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8035:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8036:             return ''; 
 8037:          }
 8038:       }
 8039:       if (&condval($statecond)) {
 8040: 	 return '2';
 8041:       } else {
 8042:          return '';
 8043:       }
 8044:    }
 8045: 
 8046:     if ($thisallowed eq 'A') {
 8047: 	return 'A';
 8048:     } elsif ($thisallowed eq 'B') {
 8049:         return 'B';
 8050:     }
 8051:    return 'F';
 8052: }
 8053: 
 8054: # ------------------------------------------- Check construction space access
 8055: 
 8056: sub constructaccess {
 8057:     my ($url,$setpriv)=@_;
 8058: 
 8059: # We do not allow editing of previous versions of files
 8060:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8061: 
 8062: # Get username and domain from URL
 8063:     my ($ownername,$ownerdomain,$ownerhome);
 8064: 
 8065:     ($ownerdomain,$ownername) =
 8066:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 8067: 
 8068: # The URL does not really point to any authorspace, forget it
 8069:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8070: 
 8071: # Now we need to see if the user has access to the authorspace of
 8072: # $ownername at $ownerdomain
 8073: 
 8074:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8075: # Real author for this?
 8076:        $ownerhome = $env{'user.home'};
 8077:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8078:           return ($ownername,$ownerdomain,$ownerhome);
 8079:        }
 8080:     } else {
 8081: # Co-author for this?
 8082:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8083:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8084:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8085:             return ($ownername,$ownerdomain,$ownerhome);
 8086:         }
 8087:         if ($env{'request.course.id'}) {
 8088:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 8089:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 8090:                 if (&allowed('mdc',$env{'request.course.id'})) {
 8091:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 8092:                     return ($ownername,$ownerdomain,$ownerhome);
 8093:                 }
 8094:             }
 8095:         }
 8096:     }
 8097: 
 8098: # We don't have any access right now. If we are not possibly going to do anything about this,
 8099: # we might as well leave
 8100:    unless ($setpriv) { return ''; }
 8101: 
 8102: # Backdoor access?
 8103:     my $allowed=&allowed('eco',$ownerdomain);
 8104: # Nope
 8105:     unless ($allowed) { return ''; }
 8106: # Looks like we may have access, but could be locked by the owner of the construction space
 8107:     if ($allowed eq 'U') {
 8108:         my %blocked=&get('environment',['domcoord.author'],
 8109:                          $ownerdomain,$ownername);
 8110: # Is blocked by owner
 8111:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8112:     }
 8113:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8114: # Grant temporary access
 8115:         my $then=$env{'user.login.time'};
 8116:         my $update=$env{'user.update.time'};
 8117:         if (!$update) { $update = $then; }
 8118:         my $refresh=$env{'user.refresh.time'};
 8119:         if (!$refresh) { $refresh = $update; }
 8120:         my $now = time;
 8121:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8122:                            $now,'ca','constructaccess');
 8123:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8124:         return($ownername,$ownerdomain,$ownerhome);
 8125:     }
 8126: # No business here
 8127:     return '';
 8128: }
 8129: 
 8130: # ----------------------------------------------------------- Content Blocking
 8131: 
 8132: {
 8133: # Caches for faster Course Contents display where content blocking
 8134: # is in operation (i.e., interval param set) for timed quiz.
 8135: #
 8136: # User for whom data are being temporarily cached.
 8137: my $cacheduser='';
 8138: # Cached blockers for this user (a hash of blocking items). 
 8139: my %cachedblockers=();
 8140: # When the data were last cached.
 8141: my $cachedlast='';
 8142: 
 8143: sub load_all_blockers {
 8144:     my ($uname,$udom,$blocks)=@_;
 8145:     if (($uname ne '') && ($udom ne '')) { 
 8146:         if (($cacheduser eq $uname.':'.$udom) &&
 8147:             (abs($cachedlast-time)<5)) {
 8148:             return;
 8149:         }
 8150:     }
 8151:     $cachedlast=time;
 8152:     $cacheduser=$uname.':'.$udom;
 8153:     %cachedblockers = &get_commblock_resources($blocks);
 8154: }
 8155: 
 8156: sub get_comm_blocks {
 8157:     my ($cdom,$cnum) = @_;
 8158:     if ($cdom eq '' || $cnum eq '') {
 8159:         return unless ($env{'request.course.id'});
 8160:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8161:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8162:     }
 8163:     my %commblocks;
 8164:     my $hashid=$cdom.'_'.$cnum;
 8165:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8166:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8167:         %commblocks = %{$blocksref};
 8168:     } else {
 8169:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8170:         my $cachetime = 600;
 8171:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8172:     }
 8173:     return %commblocks;
 8174: }
 8175: 
 8176: sub get_commblock_resources {
 8177:     my ($blocks) = @_;
 8178:     my %blockers = ();
 8179:     return %blockers unless ($env{'request.course.id'});
 8180:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8181:     my %commblocks;
 8182:     if (ref($blocks) eq 'HASH') {
 8183:         %commblocks = %{$blocks};
 8184:     } else {
 8185:         %commblocks = &get_comm_blocks();
 8186:     }
 8187:     return %blockers unless (keys(%commblocks) > 0); 
 8188:     my $navmap = Apache::lonnavmaps::navmap->new();
 8189:     return %blockers unless (ref($navmap));
 8190:     my $now = time;
 8191:     foreach my $block (keys(%commblocks)) {
 8192:         if ($block =~ /^(\d+)____(\d+)$/) {
 8193:             my ($start,$end) = ($1,$2);
 8194:             if ($start <= $now && $end >= $now) {
 8195:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8196:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8197:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8198:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8199:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8200:                             }
 8201:                         }
 8202:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8203:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8204:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8205:                             }
 8206:                         }
 8207:                     }
 8208:                 }
 8209:             }
 8210:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8211:             my $item = $1;
 8212:             my @to_test;
 8213:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8214:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8215:                     my @interval;
 8216:                     my $type = 'map';
 8217:                     if ($item eq 'course') {
 8218:                         $type = 'course';
 8219:                         @interval=&EXT("resource.0.interval");
 8220:                     } else {
 8221:                         if ($item =~ /___\d+___/) {
 8222:                             $type = 'resource';
 8223:                             @interval=&EXT("resource.0.interval",$item);
 8224:                             if (ref($navmap)) {                        
 8225:                                 my $res = $navmap->getBySymb($item); 
 8226:                                 push(@to_test,$res);
 8227:                             }
 8228:                         } else {
 8229:                             my $mapsymb = &symbread($item,1);
 8230:                             if ($mapsymb) {
 8231:                                 if (ref($navmap)) {
 8232:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8233:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8234:                                     foreach my $res (@to_test) {
 8235:                                         my $symb = $res->symb();
 8236:                                         next if ($symb eq $mapsymb);
 8237:                                         if ($symb ne '') {
 8238:                                             @interval=&EXT("resource.0.interval",$symb);
 8239:                                             if ($interval[1] eq 'map') {
 8240:                                                 last;
 8241:                                             }
 8242:                                         }
 8243:                                     }
 8244:                                 }
 8245:                             }
 8246:                         }
 8247:                     }
 8248:                     if ($interval[0] =~ /^(\d+)/) {
 8249:                         my $timelimit = $1; 
 8250:                         my $first_access;
 8251:                         if ($type eq 'resource') {
 8252:                             $first_access=&get_first_access($interval[1],$item);
 8253:                         } elsif ($type eq 'map') {
 8254:                             $first_access=&get_first_access($interval[1],undef,$item);
 8255:                         } else {
 8256:                             $first_access=&get_first_access($interval[1]);
 8257:                         }
 8258:                         if ($first_access) {
 8259:                             my $timesup = $first_access+$timelimit;
 8260:                             if ($timesup > $now) {
 8261:                                 my $activeblock;
 8262:                                 foreach my $res (@to_test) {
 8263:                                     if ($res->answerable()) {
 8264:                                         $activeblock = 1;
 8265:                                         last;
 8266:                                     }
 8267:                                 }
 8268:                                 if ($activeblock) {
 8269:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8270:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8271:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8272:                                          }
 8273:                                     }
 8274:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8275:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8276:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8277:                                         }
 8278:                                     }
 8279:                                 }
 8280:                             }
 8281:                         }
 8282:                     }
 8283:                 }
 8284:             }
 8285:         }
 8286:     }
 8287:     return %blockers;
 8288: }
 8289: 
 8290: sub has_comm_blocking {
 8291:     my ($priv,$symb,$uri,$blocks) = @_;
 8292:     my @blockers;
 8293:     return unless ($env{'request.course.id'});
 8294:     return unless ($priv eq 'bre');
 8295:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8296:     return if ($env{'request.state'} eq 'construct');
 8297:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8298:     return unless (keys(%cachedblockers) > 0);
 8299:     my (%possibles,@symbs);
 8300:     if (!$symb) {
 8301:         $symb = &symbread($uri,1,1,1,\%possibles);
 8302:     }
 8303:     if ($symb) {
 8304:         @symbs = ($symb);
 8305:     } elsif (keys(%possibles)) { 
 8306:         @symbs = keys(%possibles);
 8307:     }
 8308:     my $noblock;
 8309:     foreach my $symb (@symbs) {
 8310:         last if ($noblock);
 8311:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8312:         foreach my $block (keys(%cachedblockers)) {
 8313:             if ($block =~ /^firstaccess____(.+)$/) {
 8314:                 my $item = $1;
 8315:                 if (($item eq $map) || ($item eq $symb)) {
 8316:                     $noblock = 1;
 8317:                     last;
 8318:                 }
 8319:             }
 8320:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8321:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8322:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8323:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8324:                             push(@blockers,$block);
 8325:                         }
 8326:                     }
 8327:                 }
 8328:             }
 8329:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8330:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8331:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8332:                         push(@blockers,$block);
 8333:                     }
 8334:                 }
 8335:             }
 8336:         }
 8337:     }
 8338:     return if ($noblock);
 8339:     return @blockers;
 8340: }
 8341: }
 8342: 
 8343: # -------------------------------- Deversion and split uri into path an filename   
 8344: 
 8345: #
 8346: #   Removes the version from a URI and
 8347: #   splits it in to its filename and path to the filename.
 8348: #   Seems like File::Basename could have done this more clearly.
 8349: #   Parameters:
 8350: #      $uri   - input URI
 8351: #   Returns:
 8352: #     Two element list consisting of 
 8353: #     $pathname  - the URI up to and excluding the trailing /
 8354: #     $filename  - The part of the URI following the last /
 8355: #  NOTE:
 8356: #    Another realization of this is simply:
 8357: #    use File::Basename;
 8358: #    ...
 8359: #    $uri = shift;
 8360: #    $filename = basename($uri);
 8361: #    $path     = dirname($uri);
 8362: #    return ($filename, $path);
 8363: #
 8364: #     The implementation below is probably faster however.
 8365: #
 8366: sub split_uri_for_cond {
 8367:     my $uri=&deversion(&declutter(shift));
 8368:     my @uriparts=split(/\//,$uri);
 8369:     my $filename=pop(@uriparts);
 8370:     my $pathname=join('/',@uriparts);
 8371:     return ($pathname,$filename);
 8372: }
 8373: # --------------------------------------------------- Is a resource on the map?
 8374: 
 8375: sub is_on_map {
 8376:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8377:     #Trying to find the conditional for the file
 8378:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8379: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8380:     if ($match) {
 8381: 	return (1,$1);
 8382:     } else {
 8383: 	return (0,0);
 8384:     }
 8385: }
 8386: 
 8387: # --------------------------------------------------------- Get symb from alias
 8388: 
 8389: sub get_symb_from_alias {
 8390:     my $symb=shift;
 8391:     my ($map,$resid,$url)=&decode_symb($symb);
 8392: # Already is a symb
 8393:     if ($url) { return $symb; }
 8394: # Must be an alias
 8395:     my $aliassymb='';
 8396:     my %bighash;
 8397:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8398:                             &GDBM_READER(),0640)) {
 8399:         my $rid=$bighash{'mapalias_'.$symb};
 8400: 	if ($rid) {
 8401: 	    my ($mapid,$resid)=split(/\./,$rid);
 8402: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8403: 				    $resid,$bighash{'src_'.$rid});
 8404: 	}
 8405:         untie %bighash;
 8406:     }
 8407:     return $aliassymb;
 8408: }
 8409: 
 8410: # ----------------------------------------------------------------- Define Role
 8411: 
 8412: sub definerole {
 8413:   if (allowed('mcr','/')) {
 8414:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8415:     foreach my $role (split(':',$sysrole)) {
 8416: 	my ($crole,$cqual)=split(/\&/,$role);
 8417:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8418:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8419: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8420:                return "refused:s:$crole&$cqual"; 
 8421:             }
 8422:         }
 8423:     }
 8424:     foreach my $role (split(':',$domrole)) {
 8425: 	my ($crole,$cqual)=split(/\&/,$role);
 8426:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8427:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8428: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8429:                return "refused:d:$crole&$cqual"; 
 8430:             }
 8431:         }
 8432:     }
 8433:     foreach my $role (split(':',$courole)) {
 8434: 	my ($crole,$cqual)=split(/\&/,$role);
 8435:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8436:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8437: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8438:                return "refused:c:$crole&$cqual"; 
 8439:             }
 8440:         }
 8441:     }
 8442:     my $uhome;
 8443:     if (($uname ne '') && ($udom ne '')) {
 8444:         $uhome = &homeserver($uname,$udom);
 8445:         return $uhome if ($uhome eq 'no_host');
 8446:     } else {
 8447:         $uname = $env{'user.name'};
 8448:         $udom = $env{'user.domain'};
 8449:         $uhome = $env{'user.home'};
 8450:     }
 8451:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8452:                 "$udom:$uname:rolesdef_$rolename=".
 8453:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8454:     return reply($command,$uhome);
 8455:   } else {
 8456:     return 'refused';
 8457:   }
 8458: }
 8459: 
 8460: # ---------------- Make a metadata query against the network of library servers
 8461: 
 8462: sub metadata_query {
 8463:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8464:     my %rhash;
 8465:     my %libserv = &all_library();
 8466:     my @server_list = (defined($server_array) ? @$server_array
 8467:                                               : keys(%libserv) );
 8468:     for my $server (@server_list) {
 8469:         my $domains = ''; 
 8470:         if (ref($domains_hash) eq 'HASH') {
 8471:             $domains = $domains_hash->{$server}; 
 8472:         }
 8473: 	unless ($custom or $customshow) {
 8474: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8475: 	    $rhash{$server}=$reply;
 8476: 	}
 8477: 	else {
 8478: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8479: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8480: 			     $server);
 8481: 	    $rhash{$server}=$reply;
 8482: 	}
 8483:     }
 8484:     return \%rhash;
 8485: }
 8486: 
 8487: # ----------------------------------------- Send log queries and wait for reply
 8488: 
 8489: sub log_query {
 8490:     my ($uname,$udom,$query,%filters)=@_;
 8491:     my $uhome=&homeserver($uname,$udom);
 8492:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8493:     my $uhost=&hostname($uhome);
 8494:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8495:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8496:                        $uhome);
 8497:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8498:     return get_query_reply($queryid);
 8499: }
 8500: 
 8501: # -------------------------- Update MySQL table for portfolio file
 8502: 
 8503: sub update_portfolio_table {
 8504:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8505:     if ($group ne '') {
 8506:         $file_name =~s /^\Q$group\E//;
 8507:     }
 8508:     my $homeserver = &homeserver($uname,$udom);
 8509:     my $queryid=
 8510:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8511:                ':'.&escape($file_name).':'.$action,$homeserver);
 8512:     my $reply = &get_query_reply($queryid);
 8513:     return $reply;
 8514: }
 8515: 
 8516: # -------------------------- Update MySQL allusers table
 8517: 
 8518: sub update_allusers_table {
 8519:     my ($uname,$udom,$names) = @_;
 8520:     my $homeserver = &homeserver($uname,$udom);
 8521:     my $queryid=
 8522:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8523:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8524:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8525:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8526:                'generation='.&escape($names->{'generation'}).'%%'.
 8527:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8528:                'id='.&escape($names->{'id'}),$homeserver);
 8529:     return;
 8530: }
 8531: 
 8532: # ------- Request retrieval of institutional classlists for course(s)
 8533: 
 8534: sub fetch_enrollment_query {
 8535:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8536:     my ($homeserver,$sleep,$loopmax);
 8537:     my $maxtries = 1;
 8538:     if ($context eq 'automated') {
 8539:         $homeserver = $perlvar{'lonHostID'};
 8540:         $sleep = 2;
 8541:         $loopmax = 100;
 8542:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8543:     } else {
 8544:         $homeserver = &homeserver($cnum,$dom);
 8545:     }
 8546:     my $host=&hostname($homeserver);
 8547:     my $cmd = '';
 8548:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8549:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8550:     }
 8551:     $cmd =~ s/%%$//;
 8552:     $cmd = &escape($cmd);
 8553:     my $query = 'fetchenrollment';
 8554:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8555:     unless ($queryid=~/^\Q$host\E\_/) { 
 8556:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8557:         return 'error: '.$queryid;
 8558:     }
 8559:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8560:     my $tries = 1;
 8561:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8562:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8563:         $tries ++;
 8564:     }
 8565:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8566:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8567:     } else {
 8568:         my @responses = split(/:/,$reply);
 8569:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8570:             foreach my $line (@responses) {
 8571:                 my ($key,$value) = split(/=/,$line,2);
 8572:                 $$replyref{$key} = $value;
 8573:             }
 8574:         } else {
 8575:             my $pathname = LONCAPA::tempdir();
 8576:             foreach my $line (@responses) {
 8577:                 my ($key,$value) = split(/=/,$line);
 8578:                 $$replyref{$key} = $value;
 8579:                 if ($value > 0) {
 8580:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8581:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8582:                         my $destname = $pathname.'/'.$filename;
 8583:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8584:                         if ($xml_classlist =~ /^error/) {
 8585:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8586:                         } else {
 8587:                             if ( open(FILE,">",$destname) ) {
 8588:                                 print FILE &unescape($xml_classlist);
 8589:                                 close(FILE);
 8590:                             } else {
 8591:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8592:                             }
 8593:                         }
 8594:                     }
 8595:                 }
 8596:             }
 8597:         }
 8598:         return 'ok';
 8599:     }
 8600:     return 'error';
 8601: }
 8602: 
 8603: sub get_query_reply {
 8604:     my ($queryid,$sleep,$loopmax) = @_;;
 8605:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8606:         $sleep = 0.2;
 8607:     }
 8608:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8609:         $loopmax = 100;
 8610:     }
 8611:     my $replyfile=LONCAPA::tempdir().$queryid;
 8612:     my $reply='';
 8613:     for (1..$loopmax) {
 8614: 	sleep($sleep);
 8615:         if (-e $replyfile.'.end') {
 8616: 	    if (open(my $fh,"<",$replyfile)) {
 8617: 		$reply = join('',<$fh>);
 8618: 		close($fh);
 8619: 	   } else { return 'error: reply_file_error'; }
 8620:            return &unescape($reply);
 8621: 	}
 8622:     }
 8623:     return 'timeout:'.$queryid;
 8624: }
 8625: 
 8626: sub courselog_query {
 8627: #
 8628: # possible filters:
 8629: # url: url or symb
 8630: # username
 8631: # domain
 8632: # action: view, submit, grade
 8633: # start: timestamp
 8634: # end: timestamp
 8635: #
 8636:     my (%filters)=@_;
 8637:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8638:     if ($filters{'url'}) {
 8639: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8640:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8641:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8642:     }
 8643:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8644:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8645:     return &log_query($cname,$cdom,'courselog',%filters);
 8646: }
 8647: 
 8648: sub userlog_query {
 8649: #
 8650: # possible filters:
 8651: # action: log check role
 8652: # start: timestamp
 8653: # end: timestamp
 8654: #
 8655:     my ($uname,$udom,%filters)=@_;
 8656:     return &log_query($uname,$udom,'userlog',%filters);
 8657: }
 8658: 
 8659: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8660: 
 8661: sub auto_run {
 8662:     my ($cnum,$cdom) = @_;
 8663:     my $response = 0;
 8664:     my $settings;
 8665:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8666:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8667:         $settings = $domconfig{'autoenroll'};
 8668:         if ($settings->{'run'} eq '1') {
 8669:             $response = 1;
 8670:         }
 8671:     } else {
 8672:         my $homeserver;
 8673:         if (&is_course($cdom,$cnum)) {
 8674:             $homeserver = &homeserver($cnum,$cdom);
 8675:         } else {
 8676:             $homeserver = &domain($cdom,'primary');
 8677:         }
 8678:         if ($homeserver ne 'no_host') {
 8679:             $response = &reply('autorun:'.$cdom,$homeserver);
 8680:         }
 8681:     }
 8682:     return $response;
 8683: }
 8684: 
 8685: sub auto_get_sections {
 8686:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8687:     my $homeserver;
 8688:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8689:         $homeserver = &homeserver($cnum,$cdom);
 8690:     }
 8691:     if (!defined($homeserver)) { 
 8692:         if ($cdom =~ /^$match_domain$/) {
 8693:             $homeserver = &domain($cdom,'primary');
 8694:         }
 8695:     }
 8696:     my @secs;
 8697:     if (defined($homeserver)) {
 8698:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8699:         unless ($response eq 'refused') {
 8700:             @secs = split(/:/,$response);
 8701:         }
 8702:     }
 8703:     return @secs;
 8704: }
 8705: 
 8706: sub auto_new_course {
 8707:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8708:     my $homeserver = &homeserver($cnum,$cdom);
 8709:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8710:     return $response;
 8711: }
 8712: 
 8713: sub auto_validate_courseID {
 8714:     my ($cnum,$cdom,$inst_course_id) = @_;
 8715:     my $homeserver = &homeserver($cnum,$cdom);
 8716:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8717:     return $response;
 8718: }
 8719: 
 8720: sub auto_validate_instcode {
 8721:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8722:     my ($homeserver,$response);
 8723:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8724:         $homeserver = &homeserver($cnum,$cdom);
 8725:     }
 8726:     if (!defined($homeserver)) {
 8727:         if ($cdom =~ /^$match_domain$/) {
 8728:             $homeserver = &domain($cdom,'primary');
 8729:         }
 8730:     }
 8731:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8732:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8733:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8734:     return ($outcome,$description,$defaultcredits);
 8735: }
 8736: 
 8737: sub auto_create_password {
 8738:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8739:     my ($homeserver,$response);
 8740:     my $create_passwd = 0;
 8741:     my $authchk = '';
 8742:     if ($udom =~ /^$match_domain$/) {
 8743:         $homeserver = &domain($udom,'primary');
 8744:     }
 8745:     if ($homeserver eq '') {
 8746:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8747:             $homeserver = &homeserver($cnum,$cdom);
 8748:         }
 8749:     }
 8750:     if ($homeserver eq '') {
 8751:         $authchk = 'nodomain';
 8752:     } else {
 8753:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8754:         if ($response eq 'refused') {
 8755:             $authchk = 'refused';
 8756:         } else {
 8757:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8758:         }
 8759:     }
 8760:     return ($authparam,$create_passwd,$authchk);
 8761: }
 8762: 
 8763: sub auto_photo_permission {
 8764:     my ($cnum,$cdom,$students) = @_;
 8765:     my $homeserver = &homeserver($cnum,$cdom);
 8766:     my ($outcome,$perm_reqd,$conditions) = 
 8767: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8768:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8769: 	return (undef,undef);
 8770:     }
 8771:     return ($outcome,$perm_reqd,$conditions);
 8772: }
 8773: 
 8774: sub auto_checkphotos {
 8775:     my ($uname,$udom,$pid) = @_;
 8776:     my $homeserver = &homeserver($uname,$udom);
 8777:     my ($result,$resulttype);
 8778:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8779: 				   &escape($uname).':'.&escape($pid),
 8780: 				   $homeserver));
 8781:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8782: 	return (undef,undef);
 8783:     }
 8784:     if ($outcome) {
 8785:         ($result,$resulttype) = split(/:/,$outcome);
 8786:     } 
 8787:     return ($result,$resulttype);
 8788: }
 8789: 
 8790: sub auto_photochoice {
 8791:     my ($cnum,$cdom) = @_;
 8792:     my $homeserver = &homeserver($cnum,$cdom);
 8793:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8794: 						       &escape($cdom),
 8795: 						       $homeserver)));
 8796:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8797: 	return (undef,undef);
 8798:     }
 8799:     return ($update,$comment);
 8800: }
 8801: 
 8802: sub auto_photoupdate {
 8803:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8804:     my $homeserver = &homeserver($cnum,$dom);
 8805:     my $host=&hostname($homeserver);
 8806:     my $cmd = '';
 8807:     my $maxtries = 1;
 8808:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8809:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8810:     }
 8811:     $cmd =~ s/%%$//;
 8812:     $cmd = &escape($cmd);
 8813:     my $query = 'institutionalphotos';
 8814:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8815:     unless ($queryid=~/^\Q$host\E\_/) {
 8816:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8817:         return 'error: '.$queryid;
 8818:     }
 8819:     my $reply = &get_query_reply($queryid);
 8820:     my $tries = 1;
 8821:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8822:         $reply = &get_query_reply($queryid);
 8823:         $tries ++;
 8824:     }
 8825:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8826:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8827:     } else {
 8828:         my @responses = split(/:/,$reply);
 8829:         my $outcome = shift(@responses); 
 8830:         foreach my $item (@responses) {
 8831:             my ($key,$value) = split(/=/,$item);
 8832:             $$photo{$key} = $value;
 8833:         }
 8834:         return $outcome;
 8835:     }
 8836:     return 'error';
 8837: }
 8838: 
 8839: sub auto_instcode_format {
 8840:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8841: 	$cat_order) = @_;
 8842:     my $courses = '';
 8843:     my @homeservers;
 8844:     if ($caller eq 'global') {
 8845: 	my %servers = &get_servers($codedom,'library');
 8846: 	foreach my $tryserver (keys(%servers)) {
 8847: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8848: 		push(@homeservers,$tryserver);
 8849: 	    }
 8850:         }
 8851:     } elsif ($caller eq 'requests') {
 8852:         if ($codedom =~ /^$match_domain$/) {
 8853:             my $chome = &domain($codedom,'primary');
 8854:             unless ($chome eq 'no_host') {
 8855:                 push(@homeservers,$chome);
 8856:             }
 8857:         }
 8858:     } else {
 8859:         push(@homeservers,&homeserver($caller,$codedom));
 8860:     }
 8861:     foreach my $code (keys(%{$instcodes})) {
 8862:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8863:     }
 8864:     chop($courses);
 8865:     my $ok_response = 0;
 8866:     my $response;
 8867:     while (@homeservers > 0 && $ok_response == 0) {
 8868:         my $server = shift(@homeservers); 
 8869:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8870:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8871:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8872: 		split(/:/,$response);
 8873:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8874:             push(@{$codetitles},&str2array($codetitles_str));
 8875:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8876:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8877:             $ok_response = 1;
 8878:         }
 8879:     }
 8880:     if ($ok_response) {
 8881:         return 'ok';
 8882:     } else {
 8883:         return $response;
 8884:     }
 8885: }
 8886: 
 8887: sub auto_instcode_defaults {
 8888:     my ($domain,$returnhash,$code_order) = @_;
 8889:     my @homeservers;
 8890: 
 8891:     my %servers = &get_servers($domain,'library');
 8892:     foreach my $tryserver (keys(%servers)) {
 8893: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8894: 	    push(@homeservers,$tryserver);
 8895: 	}
 8896:     }
 8897: 
 8898:     my $response;
 8899:     foreach my $server (@homeservers) {
 8900:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8901:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8902: 	
 8903: 	foreach my $pair (split(/\&/,$response)) {
 8904: 	    my ($name,$value)=split(/\=/,$pair);
 8905: 	    if ($name eq 'code_order') {
 8906: 		@{$code_order} = split(/\&/,&unescape($value));
 8907: 	    } else {
 8908: 		$returnhash->{&unescape($name)}=&unescape($value);
 8909: 	    }
 8910: 	}
 8911: 	return 'ok';
 8912:     }
 8913: 
 8914:     return $response;
 8915: }
 8916: 
 8917: sub auto_possible_instcodes {
 8918:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8919:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8920:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8921:         return;
 8922:     }
 8923:     my (@homeservers,$uhome);
 8924:     if (defined(&domain($domain,'primary'))) {
 8925:         $uhome=&domain($domain,'primary');
 8926:         push(@homeservers,&domain($domain,'primary'));
 8927:     } else {
 8928:         my %servers = &get_servers($domain,'library');
 8929:         foreach my $tryserver (keys(%servers)) {
 8930:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8931:                 push(@homeservers,$tryserver);
 8932:             }
 8933:         }
 8934:     }
 8935:     my $response;
 8936:     foreach my $server (@homeservers) {
 8937:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8938:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8939:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8940:             split(':',$response);
 8941:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8942:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8943:         foreach my $item (split('&',$cat_title)) {   
 8944:             my ($name,$value)=split('=',$item);
 8945:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8946:         }
 8947:         foreach my $item (split('&',$cat_order)) {
 8948:             my ($name,$value)=split('=',$item);
 8949:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8950:         }
 8951:         return 'ok';
 8952:     }
 8953:     return $response;
 8954: }
 8955: 
 8956: sub auto_courserequest_checks {
 8957:     my ($dom) = @_;
 8958:     my ($homeserver,%validations);
 8959:     if ($dom =~ /^$match_domain$/) {
 8960:         $homeserver = &domain($dom,'primary');
 8961:     }
 8962:     unless ($homeserver eq 'no_host') {
 8963:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8964:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8965:             my @items = split(/&/,$response);
 8966:             foreach my $item (@items) {
 8967:                 my ($key,$value) = split('=',$item);
 8968:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8969:             }
 8970:         }
 8971:     }
 8972:     return %validations; 
 8973: }
 8974: 
 8975: sub auto_courserequest_validation {
 8976:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8977:     my ($homeserver,$response);
 8978:     if ($dom =~ /^$match_domain$/) {
 8979:         $homeserver = &domain($dom,'primary');
 8980:     }
 8981:     unless ($homeserver eq 'no_host') {
 8982:         my $customdata;
 8983:         if (ref($custominfo) eq 'HASH') {
 8984:             $customdata = &freeze_escape($custominfo);
 8985:         }
 8986:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8987:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8988:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8989:                                     $customdata,$homeserver));
 8990:     }
 8991:     return $response;
 8992: }
 8993: 
 8994: sub auto_validate_class_sec {
 8995:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8996:     my $homeserver = &homeserver($cnum,$cdom);
 8997:     my $ownerlist;
 8998:     if (ref($owners) eq 'ARRAY') {
 8999:         $ownerlist = join(',',@{$owners});
 9000:     } else {
 9001:         $ownerlist = $owners;
 9002:     }
 9003:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9004:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9005:     return $response;
 9006: }
 9007: 
 9008: sub auto_validate_instclasses {
 9009:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9010:     my ($homeserver,%validations);
 9011:     $homeserver = &homeserver($cnum,$cdom);
 9012:     unless ($homeserver eq 'no_host') {
 9013:         my $ownerlist;
 9014:         if (ref($owners) eq 'ARRAY') {
 9015:             $ownerlist = join(',',@{$owners});
 9016:         } else {
 9017:             $ownerlist = $owners;
 9018:         }
 9019:         if (ref($classesref) eq 'HASH') {
 9020:             my $classes = &freeze_escape($classesref);
 9021:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9022:                                 ':'.$cdom.':'.$classes,$homeserver);
 9023:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9024:                 my @items = split(/&/,$response);
 9025:                 foreach my $item (@items) {
 9026:                     my ($key,$value) = split('=',$item);
 9027:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9028:                 }
 9029:             }
 9030:         }
 9031:     }
 9032:     return %validations;
 9033: }
 9034: 
 9035: sub auto_crsreq_update {
 9036:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9037:         $code,$accessstart,$accessend,$inbound) = @_;
 9038:     my ($homeserver,%crsreqresponse);
 9039:     if ($cdom =~ /^$match_domain$/) {
 9040:         $homeserver = &domain($cdom,'primary');
 9041:     }
 9042:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9043:         my $info;
 9044:         if (ref($inbound) eq 'HASH') {
 9045:             $info = &freeze_escape($inbound);
 9046:         }
 9047:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9048:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9049:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9050:                             &escape($title).':'.&escape($code).':'.
 9051:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 9052:                             $homeserver);
 9053:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9054:             my @items = split(/&/,$response);
 9055:             foreach my $item (@items) {
 9056:                 my ($key,$value) = split('=',$item);
 9057:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9058:             }
 9059:         }
 9060:     }
 9061:     return \%crsreqresponse;
 9062: }
 9063: 
 9064: sub auto_export_grades {
 9065:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9066:     my ($homeserver,%exportresponse);
 9067:     if ($cdom =~ /^$match_domain$/) {
 9068:         $homeserver = &domain($cdom,'primary');
 9069:     }
 9070:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9071:         my $info;
 9072:         if (ref($inforef) eq 'HASH') {
 9073:             $info = &freeze_escape($inforef);
 9074:         }
 9075:         if (ref($gradesref) eq 'HASH') {
 9076:             my $grades = &freeze_escape($gradesref);
 9077:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9078:                                 $info.':'.$grades,$homeserver);
 9079:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9080:                 my @items = split(/&/,$response);
 9081:                 foreach my $item (@items) {
 9082:                     my ($key,$value) = split('=',$item);
 9083:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9084:                 }
 9085:             }
 9086:         }
 9087:     }
 9088:     return \%exportresponse;
 9089: }
 9090: 
 9091: sub check_instcode_cloning {
 9092:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9093:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9094:         return;
 9095:     }
 9096:     my $canclone;
 9097:     if (@{$code_order} > 0) {
 9098:         my $instcoderegexp ='^';
 9099:         my @clonecodes = split(/\&/,$cloner);
 9100:         foreach my $item (@{$code_order}) {
 9101:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9102:                 foreach my $pair (@clonecodes) {
 9103:                     my ($key,$val) = split(/\=/,$pair,2);
 9104:                     $val = &unescape($val);
 9105:                     if ($key eq $item) {
 9106:                         $instcoderegexp .= '('.$val.')';
 9107:                         last;
 9108:                     }
 9109:                 }
 9110:             } else {
 9111:                 $instcoderegexp .= $codedefaults->{$item};
 9112:             }
 9113:         }
 9114:         $instcoderegexp .= '$';
 9115:         my (@from,@to);
 9116:         eval {
 9117:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9118:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9119:         };
 9120:         if ((@from > 0) && (@to > 0)) {
 9121:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9122:             if (!@diffs) {
 9123:                 $canclone = 1;
 9124:             }
 9125:         }
 9126:     }
 9127:     return $canclone;
 9128: }
 9129: 
 9130: sub default_instcode_cloning {
 9131:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9132:     my (%codedefaults,@code_order,$canclone);
 9133:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9134:         %codedefaults = %{$codedefaultsref};
 9135:         @code_order = @{$codeorderref};
 9136:     } elsif ($clonedom) {
 9137:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9138:     }
 9139:     if (($domdefclone) && (@code_order)) {
 9140:         my @clonecodes = split(/\+/,$domdefclone);
 9141:         my $instcoderegexp ='^';
 9142:         foreach my $item (@code_order) {
 9143:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9144:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9145:             } else {
 9146:                 $instcoderegexp .= $codedefaults{$item};
 9147:             }
 9148:         }
 9149:         $instcoderegexp .= '$';
 9150:         my (@from,@to);
 9151:         eval {
 9152:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9153:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9154:         };
 9155:         if ((@from > 0) && (@to > 0)) {
 9156:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9157:             if (!@diffs) {
 9158:                 $canclone = 1;
 9159:             }
 9160:         }
 9161:     }
 9162:     return $canclone;
 9163: }
 9164: 
 9165: # ------------------------------------------------------- Course Group routines
 9166: 
 9167: sub get_coursegroups {
 9168:     my ($cdom,$cnum,$group,$namespace) = @_;
 9169:     return(&dump($namespace,$cdom,$cnum,$group));
 9170: }
 9171: 
 9172: sub modify_coursegroup {
 9173:     my ($cdom,$cnum,$groupsettings) = @_;
 9174:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9175: }
 9176: 
 9177: sub toggle_coursegroup_status {
 9178:     my ($cdom,$cnum,$group,$action) = @_;
 9179:     my ($from_namespace,$to_namespace);
 9180:     if ($action eq 'delete') {
 9181:         $from_namespace = 'coursegroups';
 9182:         $to_namespace = 'deleted_groups';
 9183:     } else {
 9184:         $from_namespace = 'deleted_groups';
 9185:         $to_namespace = 'coursegroups';
 9186:     }
 9187:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9188:     if (my $tmp = &error(%curr_group)) {
 9189:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9190:         return ('read error',$tmp);
 9191:     } else {
 9192:         my %savedsettings = %curr_group; 
 9193:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9194:         my $deloutcome;
 9195:         if ($result eq 'ok') {
 9196:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9197:         } else {
 9198:             return ('write error',$result);
 9199:         }
 9200:         if ($deloutcome eq 'ok') {
 9201:             return 'ok';
 9202:         } else {
 9203:             return ('delete error',$deloutcome);
 9204:         }
 9205:     }
 9206: }
 9207: 
 9208: sub modify_group_roles {
 9209:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9210:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9211:     my $role = 'gr/'.&escape($userprivs);
 9212:     my ($uname,$udom) = split(/:/,$user);
 9213:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9214:     if ($result eq 'ok') {
 9215:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9216:     }
 9217:     return $result;
 9218: }
 9219: 
 9220: sub modify_coursegroup_membership {
 9221:     my ($cdom,$cnum,$membership) = @_;
 9222:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9223:     return $result;
 9224: }
 9225: 
 9226: sub get_active_groups {
 9227:     my ($udom,$uname,$cdom,$cnum) = @_;
 9228:     my $now = time;
 9229:     my %groups = ();
 9230:     foreach my $key (keys(%env)) {
 9231:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9232:             my ($start,$end) = split(/\./,$env{$key});
 9233:             if (($end!=0) && ($end<$now)) { next; }
 9234:             if (($start!=0) && ($start>$now)) { next; }
 9235:             if ($1 eq $cdom && $2 eq $cnum) {
 9236:                 $groups{$3} = $env{$key} ;
 9237:             }
 9238:         }
 9239:     }
 9240:     return %groups;
 9241: }
 9242: 
 9243: sub get_group_membership {
 9244:     my ($cdom,$cnum,$group) = @_;
 9245:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9246: }
 9247: 
 9248: sub get_users_groups {
 9249:     my ($udom,$uname,$courseid) = @_;
 9250:     my @usersgroups;
 9251:     my $cachetime=1800;
 9252: 
 9253:     my $hashid="$udom:$uname:$courseid";
 9254:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9255:     if (defined($cached)) {
 9256:         @usersgroups = split(/:/,$grouplist);
 9257:     } else {  
 9258:         $grouplist = '';
 9259:         my $courseurl = &courseid_to_courseurl($courseid);
 9260:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9261:         my $access_end = $env{'course.'.$courseid.
 9262:                               '.default_enrollment_end_date'};
 9263:         my $now = time;
 9264:         foreach my $key (keys(%roleshash)) {
 9265:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9266:                 my $group = $1;
 9267:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9268:                     my $start = $2;
 9269:                     my $end = $1;
 9270:                     if ($start == -1) { next; } # deleted from group
 9271:                     if (($start!=0) && ($start>$now)) { next; }
 9272:                     if (($end!=0) && ($end<$now)) {
 9273:                         if ($access_end && $access_end < $now) {
 9274:                             if ($access_end - $end < 86400) {
 9275:                                 push(@usersgroups,$group);
 9276:                             }
 9277:                         }
 9278:                         next;
 9279:                     }
 9280:                     push(@usersgroups,$group);
 9281:                 }
 9282:             }
 9283:         }
 9284:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9285:         $grouplist = join(':',@usersgroups);
 9286:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9287:     }
 9288:     return @usersgroups;
 9289: }
 9290: 
 9291: sub devalidate_getgroups_cache {
 9292:     my ($udom,$uname,$cdom,$cnum)=@_;
 9293:     my $courseid = $cdom.'_'.$cnum;
 9294: 
 9295:     my $hashid="$udom:$uname:$courseid";
 9296:     &devalidate_cache_new('getgroups',$hashid);
 9297: }
 9298: 
 9299: # ------------------------------------------------------------------ Plain Text
 9300: 
 9301: sub plaintext {
 9302:     my ($short,$type,$cid,$forcedefault) = @_;
 9303:     if ($short =~ m{^cr/}) {
 9304: 	return (split('/',$short))[-1];
 9305:     }
 9306:     if (!defined($cid)) {
 9307:         $cid = $env{'request.course.id'};
 9308:     }
 9309:     my %rolenames = (
 9310:                       Course    => 'std',
 9311:                       Community => 'alt1',
 9312:                       Placement => 'std',
 9313:                     );
 9314:     if ($cid ne '') {
 9315:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9316:             unless ($forcedefault) {
 9317:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9318:                 &Apache::lonlocal::mt_escape(\$roletext);
 9319:                 return &Apache::lonlocal::mt($roletext);
 9320:             }
 9321:         }
 9322:     }
 9323:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9324:         (defined($rolenames{$type})) && 
 9325:         (defined($prp{$short}{$rolenames{$type}}))) {
 9326:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9327:     } elsif ($cid ne '') {
 9328:         my $crstype = $env{'course.'.$cid.'.type'};
 9329:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9330:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9331:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9332:         }
 9333:     }
 9334:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9335: }
 9336: 
 9337: # ----------------------------------------------------------------- Assign Role
 9338: 
 9339: sub assignrole {
 9340:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9341:         $context)=@_;
 9342:     my $mrole;
 9343:     if ($role =~ /^cr\//) {
 9344:         my $cwosec=$url;
 9345:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9346: 	unless (&allowed('ccr',$cwosec)) {
 9347:            my $refused = 1;
 9348:            if ($context eq 'requestcourses') {
 9349:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9350:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9351:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9352:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9353:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9354:                            if ($crsenv{'internal.courseowner'} eq
 9355:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9356:                                $refused = '';
 9357:                            }
 9358:                        }
 9359:                    }
 9360:                }
 9361:            }
 9362:            if ($refused) {
 9363:                &logthis('Refused custom assignrole: '.
 9364:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9365:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9366:                return 'refused';
 9367:            }
 9368:         }
 9369:         $mrole='cr';
 9370:     } elsif ($role =~ /^gr\//) {
 9371:         my $cwogrp=$url;
 9372:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9373:         unless (&allowed('mdg',$cwogrp)) {
 9374:             &logthis('Refused group assignrole: '.
 9375:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9376:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9377:             return 'refused';
 9378:         }
 9379:         $mrole='gr';
 9380:     } else {
 9381:         my $cwosec=$url;
 9382:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9383:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9384:             my $refused;
 9385:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9386:                 if (!(&allowed('c'.$role,$url))) {
 9387:                     $refused = 1;
 9388:                 }
 9389:             } else {
 9390:                 $refused = 1;
 9391:             }
 9392:             if ($refused) {
 9393:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9394:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
 9395:                     my %crsenv;
 9396:                     if ($role eq 'cc' || $role eq 'co') {
 9397:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9398:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9399:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9400:                                 if ($crsenv{'internal.courseowner'} eq 
 9401:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9402:                                     $refused = '';
 9403:                                 }
 9404:                             }
 9405:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9406:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9407:                                 if ($crsenv{'internal.courseowner'} eq 
 9408:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9409:                                     $refused = '';
 9410:                                 }
 9411:                             }
 9412:                         }
 9413:                     }
 9414:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9415:                     if ($role eq 'st') {
 9416:                         $refused = '';
 9417:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
 9418:                         $refused = '';
 9419:                     }
 9420:                 } elsif ($context eq 'requestcourses') {
 9421:                     my @possroles = ('st','ta','ep','in','cc','co');
 9422:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9423:                         my $wrongcc;
 9424:                         if ($cnum =~ /^$match_community$/) {
 9425:                             $wrongcc = 1 if ($role eq 'cc');
 9426:                         } else {
 9427:                             $wrongcc = 1 if ($role eq 'co');
 9428:                         }
 9429:                         unless ($wrongcc) {
 9430:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9431:                             if ($crsenv{'internal.courseowner'} eq 
 9432:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9433:                                 $refused = '';
 9434:                             }
 9435:                         }
 9436:                     }
 9437:                 } elsif ($context eq 'requestauthor') {
 9438:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9439:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9440:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9441:                             $refused = '';
 9442:                         } else {
 9443:                             my %domdefaults = &get_domain_defaults($udom);
 9444:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9445:                                 my $checkbystatus;
 9446:                                 if ($env{'user.adv'}) { 
 9447:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9448:                                     if ($disposition eq 'automatic') {
 9449:                                         $refused = '';
 9450:                                     } elsif ($disposition eq '') {
 9451:                                         $checkbystatus = 1;
 9452:                                     } 
 9453:                                 } else {
 9454:                                     $checkbystatus = 1;
 9455:                                 }
 9456:                                 if ($checkbystatus) {
 9457:                                     if ($env{'environment.inststatus'}) {
 9458:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9459:                                         foreach my $type (@inststatuses) {
 9460:                                             if (($type ne '') &&
 9461:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9462:                                                 $refused = '';
 9463:                                             }
 9464:                                         }
 9465:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9466:                                         $refused = '';
 9467:                                     }
 9468:                                 }
 9469:                             }
 9470:                         }
 9471:                     }
 9472:                 }
 9473:                 if ($refused) {
 9474:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9475:                              ' '.$role.' '.$end.' '.$start.' by '.
 9476: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9477:                     return 'refused';
 9478:                 }
 9479:             }
 9480:         } elsif ($role eq 'au') {
 9481:             if ($url ne '/'.$udom.'/') {
 9482:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9483:                          ' to assign author role for '.$uname.':'.$udom.
 9484:                          ' in domain: '.$url.' refused (wrong domain).');
 9485:                 return 'refused';
 9486:             }
 9487:         }
 9488:         $mrole=$role;
 9489:     }
 9490:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9491:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9492:     if ($end) { $command.='_'.$end; }
 9493:     if ($start) {
 9494: 	if ($end) { 
 9495:            $command.='_'.$start; 
 9496:         } else {
 9497:            $command.='_0_'.$start;
 9498:         }
 9499:     }
 9500:     my $origstart = $start;
 9501:     my $origend = $end;
 9502:     my $delflag;
 9503: # actually delete
 9504:     if ($deleteflag) {
 9505: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9506: # modify command to delete the role
 9507:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9508:                 "$udom:$uname:$url".'_'."$mrole";
 9509: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9510: # set start and finish to negative values for userrolelog
 9511:            $start=-1;
 9512:            $end=-1;
 9513:            $delflag = 1;
 9514:         }
 9515:     }
 9516: # send command
 9517:     my $answer=&reply($command,&homeserver($uname,$udom));
 9518: # log new user role if status is ok
 9519:     if ($answer eq 'ok') {
 9520: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9521:         if (($role eq 'cc') || ($role eq 'in') ||
 9522:             ($role eq 'ep') || ($role eq 'ad') ||
 9523:             ($role eq 'ta') || ($role eq 'st') ||
 9524:             ($role=~/^cr/) || ($role eq 'gr') ||
 9525:             ($role eq 'co')) {
 9526: # for course roles, perform group memberships changes triggered by role change.
 9527:             unless ($role =~ /^gr/) {
 9528:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9529:                                                  $origstart,$selfenroll,$context);
 9530:             }
 9531:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9532:                            $selfenroll,$context);
 9533:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9534:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9535:                  ($role eq 'da')) {
 9536:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9537:                            $context);
 9538:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9539:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9540:                              $context); 
 9541:         }
 9542:         if ($role eq 'cc') {
 9543:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9544:         }
 9545:     }
 9546:     return $answer;
 9547: }
 9548: 
 9549: sub autoupdate_coowners {
 9550:     my ($url,$end,$start,$uname,$udom) = @_;
 9551:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9552:     if (($cdom ne '') && ($cnum ne '')) {
 9553:         my $now = time;
 9554:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9555:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9556:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9557:             my $instcode = $coursehash{'internal.coursecode'};
 9558:             if ($instcode ne '') {
 9559:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9560:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9561:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9562:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9563:                         if ($result eq 'valid') {
 9564:                             if ($coursehash{'internal.co-owners'}) {
 9565:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9566:                                     push(@newcoowners,$coowner);
 9567:                                 }
 9568:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9569:                                     push(@newcoowners,$uname.':'.$udom);
 9570:                                 }
 9571:                                 @newcoowners = sort(@newcoowners);
 9572:                             } else {
 9573:                                 push(@newcoowners,$uname.':'.$udom);
 9574:                             }
 9575:                         } else {
 9576:                             if ($coursehash{'internal.co-owners'}) {
 9577:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9578:                                     unless ($coowner eq $uname.':'.$udom) {
 9579:                                         push(@newcoowners,$coowner);
 9580:                                     }
 9581:                                 }
 9582:                                 unless (@newcoowners > 0) {
 9583:                                     $delcoowners = 1;
 9584:                                     $coowners = '';
 9585:                                 }
 9586:                             }
 9587:                         }
 9588:                         if (@newcoowners || $delcoowners) {
 9589:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9590:                                             $delcoowners,@newcoowners);
 9591:                         }
 9592:                     }
 9593:                 }
 9594:             }
 9595:         }
 9596:     }
 9597: }
 9598: 
 9599: sub store_coowners {
 9600:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9601:     my $cid = $cdom.'_'.$cnum;
 9602:     my ($coowners,$delresult,$putresult);
 9603:     if (@newcoowners) {
 9604:         $coowners = join(',',@newcoowners);
 9605:         my %coownershash = (
 9606:                             'internal.co-owners' => $coowners,
 9607:                            );
 9608:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9609:         if ($putresult eq 'ok') {
 9610:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9611:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9612:             }
 9613:         }
 9614:     }
 9615:     if ($delcoowners) {
 9616:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9617:         if ($delresult eq 'ok') {
 9618:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9619:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9620:             }
 9621:         }
 9622:     }
 9623:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9624:         my %crsinfo =
 9625:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9626:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9627:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9628:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9629:         }
 9630:     }
 9631: }
 9632: 
 9633: # -------------------------------------------------- Modify user authentication
 9634: # Overrides without validation
 9635: 
 9636: sub modifyuserauth {
 9637:     my ($udom,$uname,$umode,$upass)=@_;
 9638:     my $uhome=&homeserver($uname,$udom);
 9639:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9640:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9641:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9642:              ' in domain '.$env{'request.role.domain'});  
 9643:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9644: 		     &escape($upass),$uhome);
 9645:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9646:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9647:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9648:     &log($udom,,$uname,$uhome,
 9649:         'Authentication changed by '.$env{'user.domain'}.', '.
 9650:                                      $env{'user.name'}.', '.$umode.
 9651:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9652:     unless ($reply eq 'ok') {
 9653:         &logthis('Authentication mode error: '.$reply);
 9654: 	return 'error: '.$reply;
 9655:     }   
 9656:     return 'ok';
 9657: }
 9658: 
 9659: # --------------------------------------------------------------- Modify a user
 9660: 
 9661: sub modifyuser {
 9662:     my ($udom,    $uname, $uid,
 9663:         $umode,   $upass, $first,
 9664:         $middle,  $last,  $gene,
 9665:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9666:     $udom= &LONCAPA::clean_domain($udom);
 9667:     $uname=&LONCAPA::clean_username($uname);
 9668:     my $showcandelete = 'none';
 9669:     if (ref($candelete) eq 'ARRAY') {
 9670:         if (@{$candelete} > 0) {
 9671:             $showcandelete = join(', ',@{$candelete});
 9672:         }
 9673:     }
 9674:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9675:              $umode.', '.$first.', '.$middle.', '.
 9676: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9677:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9678:                                      ' desiredhome not specified'). 
 9679:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9680:              ' in domain '.$env{'request.role.domain'});
 9681:     my $uhome=&homeserver($uname,$udom,'true');
 9682:     my $newuser;
 9683:     if ($uhome eq 'no_host') {
 9684:         $newuser = 1;
 9685:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
 9686:                 ($umode eq 'lti')) {
 9687:             return 'error: more information needed to create new user';
 9688:         }
 9689:     }
 9690: # ----------------------------------------------------------------- Create User
 9691:     if (($uhome eq 'no_host') && 
 9692: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
 9693:         my $unhome='';
 9694:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9695:             $unhome = $desiredhome;
 9696: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9697: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9698:         } else { # load balancing routine for determining $unhome
 9699:             my $loadm=10000000;
 9700: 	    my %servers = &get_servers($udom,'library');
 9701: 	    foreach my $tryserver (keys(%servers)) {
 9702: 		my $answer=reply('load',$tryserver);
 9703: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9704: 		    $loadm=$answer;
 9705: 		    $unhome=$tryserver;
 9706: 		}
 9707: 	    }
 9708:         }
 9709:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9710: 	    return 'error: unable to find a home server for '.$uname.
 9711:                    ' in domain '.$udom;
 9712:         }
 9713:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9714:                          &escape($upass),$unhome);
 9715: 	unless ($reply eq 'ok') {
 9716:             return 'error: '.$reply;
 9717:         }   
 9718:         $uhome=&homeserver($uname,$udom,'true');
 9719:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9720: 	    return 'error: unable verify users home machine.';
 9721:         }
 9722:     }   # End of creation of new user
 9723: # ---------------------------------------------------------------------- Add ID
 9724:     if ($uid) {
 9725:        $uid=~tr/A-Z/a-z/;
 9726:        my %uidhash=&idrget($udom,$uname);
 9727:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9728:          && (!$forceid)) {
 9729: 	  unless ($uid eq $uidhash{$uname}) {
 9730: 	      return 'error: user id "'.$uid.'" does not match '.
 9731:                   'current user id "'.$uidhash{$uname}.'".';
 9732:           }
 9733:        } else {
 9734: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9735:        }
 9736:     }
 9737: # -------------------------------------------------------------- Add names, etc
 9738:     my @tmp=&get('environment',
 9739: 		   ['firstname','middlename','lastname','generation','id',
 9740:                     'permanentemail','inststatus'],
 9741: 		   $udom,$uname);
 9742:     my (%names,%oldnames);
 9743:     if ($tmp[0] =~ m/^error:.*/) { 
 9744:         %names=(); 
 9745:     } else {
 9746:         %names = @tmp;
 9747:         %oldnames = %names;
 9748:     }
 9749: #
 9750: # If name, email and/or uid are blank (e.g., because an uploaded file
 9751: # of users did not contain them), do not overwrite existing values
 9752: # unless field is in $candelete array ref.  
 9753: #
 9754: 
 9755:     my @fields = ('firstname','middlename','lastname','generation',
 9756:                   'permanentemail','id');
 9757:     my %newvalues;
 9758:     if (ref($candelete) eq 'ARRAY') {
 9759:         foreach my $field (@fields) {
 9760:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9761:                 if ($field eq 'firstname') {
 9762:                     $names{$field} = $first;
 9763:                 } elsif ($field eq 'middlename') {
 9764:                     $names{$field} = $middle;
 9765:                 } elsif ($field eq 'lastname') {
 9766:                     $names{$field} = $last;
 9767:                 } elsif ($field eq 'generation') { 
 9768:                     $names{$field} = $gene;
 9769:                 } elsif ($field eq 'permanentemail') {
 9770:                     $names{$field} = $email;
 9771:                 } elsif ($field eq 'id') {
 9772:                     $names{$field}  = $uid;
 9773:                 }
 9774:             }
 9775:         }
 9776:     }
 9777:     if ($first)  { $names{'firstname'}  = $first; }
 9778:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9779:     if ($last)   { $names{'lastname'}   = $last; }
 9780:     if (defined($gene))   { $names{'generation'} = $gene; }
 9781:     if ($email) {
 9782:        $email=~s/[^\w\@\.\-\,]//gs;
 9783:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9784:     }
 9785:     if ($uid) { $names{'id'}  = $uid; }
 9786:     if (defined($inststatus)) {
 9787:         $names{'inststatus'} = '';
 9788:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9789:         if (ref($usertypes) eq 'HASH') {
 9790:             my @okstatuses; 
 9791:             foreach my $item (split(/:/,$inststatus)) {
 9792:                 if (defined($usertypes->{$item})) {
 9793:                     push(@okstatuses,$item);  
 9794:                 }
 9795:             }
 9796:             if (@okstatuses) {
 9797:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9798:             }
 9799:         }
 9800:     }
 9801:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9802:                  $umode.', '.$first.', '.$middle.', '.
 9803:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9804:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9805:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9806:     } else {
 9807:         $logmsg .= ' during self creation';
 9808:     }
 9809:     my $changed;
 9810:     if ($newuser) {
 9811:         $changed = 1;
 9812:     } else {
 9813:         foreach my $field (@fields) {
 9814:             if ($names{$field} ne $oldnames{$field}) {
 9815:                 $changed = 1;
 9816:                 last;
 9817:             }
 9818:         }
 9819:     }
 9820:     unless ($changed) {
 9821:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9822:         &logthis($logmsg);
 9823:         return 'ok';
 9824:     }
 9825:     my $reply = &put('environment', \%names, $udom,$uname);
 9826:     if ($reply ne 'ok') { 
 9827:         return 'error: '.$reply;
 9828:     }
 9829:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9830:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9831:     }
 9832:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9833:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9834:     $logmsg = 'Success modifying user '.$logmsg;
 9835:     &logthis($logmsg);
 9836:     return 'ok';
 9837: }
 9838: 
 9839: # -------------------------------------------------------------- Modify student
 9840: 
 9841: sub modifystudent {
 9842:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9843:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9844:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9845:     if (!$cid) {
 9846: 	unless ($cid=$env{'request.course.id'}) {
 9847: 	    return 'not_in_class';
 9848: 	}
 9849:     }
 9850: # --------------------------------------------------------------- Make the user
 9851:     my $reply=&modifyuser
 9852: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9853:          $desiredhome,$email,$inststatus);
 9854:     unless ($reply eq 'ok') { return $reply; }
 9855:     # This will cause &modify_student_enrollment to get the uid from the
 9856:     # student's environment
 9857:     $uid = undef if (!$forceid);
 9858:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9859:                                         $gene,$usec,$end,$start,$type,$locktype,
 9860:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9861:     return $reply;
 9862: }
 9863: 
 9864: sub modify_student_enrollment {
 9865:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9866:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9867:     my ($cdom,$cnum,$chome);
 9868:     if (!$cid) {
 9869: 	unless ($cid=$env{'request.course.id'}) {
 9870: 	    return 'not_in_class';
 9871: 	}
 9872: 	$cdom=$env{'course.'.$cid.'.domain'};
 9873: 	$cnum=$env{'course.'.$cid.'.num'};
 9874:     } else {
 9875: 	($cdom,$cnum)=split(/_/,$cid);
 9876:     }
 9877:     $chome=$env{'course.'.$cid.'.home'};
 9878:     if (!$chome) {
 9879: 	$chome=&homeserver($cnum,$cdom);
 9880:     }
 9881:     if (!$chome) { return 'unknown_course'; }
 9882:     # Make sure the user exists
 9883:     my $uhome=&homeserver($uname,$udom);
 9884:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9885: 	return 'error: no such user';
 9886:     }
 9887:     # Get student data if we were not given enough information
 9888:     if (!defined($first)  || $first  eq '' || 
 9889:         !defined($last)   || $last   eq '' || 
 9890:         !defined($uid)    || $uid    eq '' || 
 9891:         !defined($middle) || $middle eq '' || 
 9892:         !defined($gene)   || $gene   eq '') {
 9893:         # They did not supply us with enough data to enroll the student, so
 9894:         # we need to pick up more information.
 9895:         my %tmp = &get('environment',
 9896:                        ['firstname','middlename','lastname', 'generation','id']
 9897:                        ,$udom,$uname);
 9898: 
 9899:         #foreach my $key (keys(%tmp)) {
 9900:         #    &logthis("key $key = ".$tmp{$key});
 9901:         #}
 9902:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9903:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9904:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9905:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9906:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9907:     }
 9908:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9909:     my $user = "$uname:$udom";
 9910:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9911:     my $reply=cput('classlist',
 9912: 		   {$user => 
 9913: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9914: 		   $cdom,$cnum);
 9915:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9916:         &devalidate_getsection_cache($udom,$uname,$cid);
 9917:     } else { 
 9918: 	return 'error: '.$reply;
 9919:     }
 9920:     # Add student role to user
 9921:     my $uurl='/'.$cid;
 9922:     $uurl=~s/\_/\//g;
 9923:     if ($usec) {
 9924: 	$uurl.='/'.$usec;
 9925:     }
 9926:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9927:                              $selfenroll,$context);
 9928:     if ($result ne 'ok') {
 9929:         if ($old_entry{$user} ne '') {
 9930:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9931:         } else {
 9932:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9933:         }
 9934:     }
 9935:     return $result; 
 9936: }
 9937: 
 9938: sub format_name {
 9939:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9940:     my $name;
 9941:     if ($first ne 'lastname') {
 9942: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9943:     } else {
 9944: 	if ($lastname=~/\S/) {
 9945: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9946: 	    $name=~s/\s+,/,/;
 9947: 	} else {
 9948: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9949: 	}
 9950:     }
 9951:     $name=~s/^\s+//;
 9952:     $name=~s/\s+$//;
 9953:     $name=~s/\s+/ /g;
 9954:     return $name;
 9955: }
 9956: 
 9957: # ------------------------------------------------- Write to course preferences
 9958: 
 9959: sub writecoursepref {
 9960:     my ($courseid,%prefs)=@_;
 9961:     $courseid=~s/^\///;
 9962:     $courseid=~s/\_/\//g;
 9963:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9964:     my $chome=homeserver($cnum,$cdomain);
 9965:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9966: 	return 'error: no such course';
 9967:     }
 9968:     my $cstring='';
 9969:     foreach my $pref (keys(%prefs)) {
 9970: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9971:     }
 9972:     $cstring=~s/\&$//;
 9973:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9974: }
 9975: 
 9976: # ---------------------------------------------------------- Make/modify course
 9977: 
 9978: sub createcourse {
 9979:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9980:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9981:     $url=&declutter($url);
 9982:     my $cid='';
 9983:     if ($context eq 'requestcourses') {
 9984:         my $can_create = 0;
 9985:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9986:         if ($udom eq $ownerdom) {
 9987:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9988:                                   $context)) {
 9989:                 $can_create = 1;
 9990:             }
 9991:         } else {
 9992:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9993:                                            $category);
 9994:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9995:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9996:                 if (@curr > 0) {
 9997:                     my @options = qw(approval validate autolimit);
 9998:                     my $optregex = join('|',@options);
 9999:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10000:                         $can_create = 1;
10001:                     }
10002:                 }
10003:             }
10004:         }
10005:         if ($can_create) {
10006:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10007:                 unless (&allowed('ccc',$udom)) {
10008:                     return 'refused'; 
10009:                 }
10010:             }
10011:         } else {
10012:             return 'refused';
10013:         }
10014:     } elsif (!&allowed('ccc',$udom)) {
10015:         return 'refused';
10016:     }
10017: # --------------------------------------------------------------- Get Unique ID
10018:     my $uname;
10019:     if ($cnum =~ /^$match_courseid$/) {
10020:         my $chome=&homeserver($cnum,$udom,'true');
10021:         if (($chome eq '') || ($chome eq 'no_host')) {
10022:             $uname = $cnum;
10023:         } else {
10024:             $uname = &generate_coursenum($udom,$crstype);
10025:         }
10026:     } else {
10027:         $uname = &generate_coursenum($udom,$crstype);
10028:     }
10029:     return $uname if ($uname =~ /^error/);
10030: # -------------------------------------------------- Check supplied server name
10031:     if (!defined($course_server)) {
10032:         if (defined(&domain($udom,'primary'))) {
10033:             $course_server = &domain($udom,'primary');
10034:         } else {
10035:             $course_server = $env{'user.home'}; 
10036:         }
10037:     }
10038:     my %host_servers =
10039:         &Apache::lonnet::get_servers($udom,'library');
10040:     unless ($host_servers{$course_server}) {
10041:         return 'error: invalid home server for course: '.$course_server;
10042:     }
10043: # ------------------------------------------------------------- Make the course
10044:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10045:                       $course_server);
10046:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10047:     my $uhome=&homeserver($uname,$udom,'true');
10048:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10049: 	return 'error: no such course';
10050:     }
10051: # ----------------------------------------------------------------- Course made
10052: # log existence
10053:     my $now = time;
10054:     my $newcourse = {
10055:                     $udom.'_'.$uname => {
10056:                                      description => $description,
10057:                                      inst_code   => $inst_code,
10058:                                      owner       => $course_owner,
10059:                                      type        => $crstype,
10060:                                      creator     => $env{'user.name'}.':'.
10061:                                                     $env{'user.domain'},
10062:                                      created     => $now,
10063:                                      context     => $context,
10064:                                                 },
10065:                     };
10066:     &courseidput($udom,$newcourse,$uhome,'notime');
10067: # set toplevel url
10068:     my $topurl=$url;
10069:     unless ($nonstandard) {
10070: # ------------------------------------------ For standard courses, make top url
10071:         my $mapurl=&clutter($url);
10072:         if ($mapurl eq '/res/') { $mapurl=''; }
10073:         $env{'form.initmap'}=(<<ENDINITMAP);
10074: <map>
10075: <resource id="1" type="start"></resource>
10076: <resource id="2" src="$mapurl"></resource>
10077: <resource id="3" type="finish"></resource>
10078: <link index="1" from="1" to="2"></link>
10079: <link index="2" from="2" to="3"></link>
10080: </map>
10081: ENDINITMAP
10082:         $topurl=&declutter(
10083:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10084:                           );
10085:     }
10086: # ----------------------------------------------------------- Write preferences
10087:     &writecoursepref($udom.'_'.$uname,
10088:                      ('description'              => $description,
10089:                       'url'                      => $topurl,
10090:                       'internal.creator'         => $env{'user.name'}.':'.
10091:                                                     $env{'user.domain'},
10092:                       'internal.created'         => $now,
10093:                       'internal.creationcontext' => $context)
10094:                     );
10095:     return '/'.$udom.'/'.$uname;
10096: }
10097: 
10098: # ------------------------------------------------------------------- Create ID
10099: sub generate_coursenum {
10100:     my ($udom,$crstype) = @_;
10101:     my $domdesc = &domain($udom);
10102:     return 'error: invalid domain' if ($domdesc eq '');
10103:     my $first;
10104:     if ($crstype eq 'Community') {
10105:         $first = '0';
10106:     } else {
10107:         $first = int(1+rand(9)); 
10108:     } 
10109:     my $uname=$first.
10110:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10111:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10112:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10113: # ----------------------------------------------- Make sure that does not exist
10114:     my $uhome=&homeserver($uname,$udom,'true');
10115:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10116:         if ($crstype eq 'Community') {
10117:             $first = '0';
10118:         } else {
10119:             $first = int(1+rand(9));
10120:         }
10121:         $uname=$first.
10122:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10123:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10124:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10125:         $uhome=&homeserver($uname,$udom,'true');
10126:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10127:             return 'error: unable to generate unique course-ID';
10128:         }
10129:     }
10130:     return $uname;
10131: }
10132: 
10133: sub is_course {
10134:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10135:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10136: 
10137:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10138:     my $uhome=&homeserver($cnum,$cdom);
10139:     my $iscourse;
10140:     if (grep { $_ eq $uhome } current_machine_ids()) {
10141:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10142:     } else {
10143:         my $hashid = $cdom.':'.$cnum;
10144:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10145:         unless (defined($cached)) {
10146:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10147:                                         $cnum,undef,undef,'.');
10148:             $iscourse = 0;
10149:             if (exists($courses{$cdom.'_'.$cnum})) {
10150:                 $iscourse = 1;
10151:             }
10152:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10153:         }
10154:     }
10155:     return unless ($iscourse);
10156:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10157: }
10158: 
10159: sub store_userdata {
10160:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10161:     my $result;
10162:     if ($datakey ne '') {
10163:         if (ref($storehash) eq 'HASH') {
10164:             if ($udom eq '' || $uname eq '') {
10165:                 $udom = $env{'user.domain'};
10166:                 $uname = $env{'user.name'};
10167:             }
10168:             my $uhome=&homeserver($uname,$udom);
10169:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10170:                 $result = 'error: no_host';
10171:             } else {
10172:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10173:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10174: 
10175:                 my $namevalue='';
10176:                 foreach my $key (keys(%{$storehash})) {
10177:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10178:                 }
10179:                 $namevalue=~s/\&$//;
10180:                 unless ($namespace eq 'courserequests') {
10181:                     $datakey = &escape($datakey);
10182:                 }
10183:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10184:                                   $namevalue,$uhome);
10185:             }
10186:         } else {
10187:             $result = 'error: data to store was not a hash reference'; 
10188:         }
10189:     } else {
10190:         $result= 'error: invalid requestkey'; 
10191:     }
10192:     return $result;
10193: }
10194: 
10195: # ---------------------------------------------------------- Assign Custom Role
10196: 
10197: sub assigncustomrole {
10198:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10199:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10200:                        $end,$start,$deleteflag,$selfenroll,$context);
10201: }
10202: 
10203: # ----------------------------------------------------------------- Revoke Role
10204: 
10205: sub revokerole {
10206:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10207:     my $now=time;
10208:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10209: }
10210: 
10211: # ---------------------------------------------------------- Revoke Custom Role
10212: 
10213: sub revokecustomrole {
10214:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10215:     my $now=time;
10216:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10217:            $deleteflag,$selfenroll,$context);
10218: }
10219: 
10220: # ------------------------------------------------------------ Disk usage
10221: sub diskusage {
10222:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10223:     $directorypath =~ s/\/$//;
10224:     my $listing=&reply('du2:'.&escape($directorypath).':'
10225:                        .&escape($getpropath).':'.&escape($uname).':'
10226:                        .&escape($udom),homeserver($uname,$udom));
10227:     if ($listing eq 'unknown_cmd') {
10228:         if ($getpropath) {
10229:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10230:         }
10231:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10232:     }
10233:     return $listing;
10234: }
10235: 
10236: sub is_locked {
10237:     my ($file_name, $domain, $user, $which) = @_;
10238:     my @check;
10239:     my $is_locked;
10240:     push (@check,$file_name);
10241:     my %locked = &get('file_permissions',\@check,
10242: 		      $env{'user.domain'},$env{'user.name'});
10243:     my ($tmp)=keys(%locked);
10244:     if ($tmp=~/^error:/) { undef(%locked); }
10245:     
10246:     if (ref($locked{$file_name}) eq 'ARRAY') {
10247:         $is_locked = 'false';
10248:         foreach my $entry (@{$locked{$file_name}}) {
10249:            if (ref($entry) eq 'ARRAY') {
10250:                $is_locked = 'true';
10251:                if (ref($which) eq 'ARRAY') {
10252:                    push(@{$which},$entry);
10253:                } else {
10254:                    last;
10255:                }
10256:            }
10257:        }
10258:     } else {
10259:         $is_locked = 'false';
10260:     }
10261:     return $is_locked;
10262: }
10263: 
10264: sub declutter_portfile {
10265:     my ($file) = @_;
10266:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10267:     return $file;
10268: }
10269: 
10270: # ------------------------------------------------------------- Mark as Read Only
10271: 
10272: sub mark_as_readonly {
10273:     my ($domain,$user,$files,$what) = @_;
10274:     my %current_permissions = &dump('file_permissions',$domain,$user);
10275:     my ($tmp)=keys(%current_permissions);
10276:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10277:     foreach my $file (@{$files}) {
10278: 	$file = &declutter_portfile($file);
10279:         push(@{$current_permissions{$file}},$what);
10280:     }
10281:     &put('file_permissions',\%current_permissions,$domain,$user);
10282:     return;
10283: }
10284: 
10285: # ------------------------------------------------------------Save Selected Files
10286: 
10287: sub save_selected_files {
10288:     my ($user, $path, @files) = @_;
10289:     my $filename = $user."savedfiles";
10290:     my @other_files = &files_not_in_path($user, $path);
10291:     open (OUT,'>',LONCAPA::tempdir().$filename);
10292:     foreach my $file (@files) {
10293:         print (OUT $env{'form.currentpath'}.$file."\n");
10294:     }
10295:     foreach my $file (@other_files) {
10296:         print (OUT $file."\n");
10297:     }
10298:     close (OUT);
10299:     return 'ok';
10300: }
10301: 
10302: sub clear_selected_files {
10303:     my ($user) = @_;
10304:     my $filename = $user."savedfiles";
10305:     open (OUT,'>',LONCAPA::tempdir().$filename);
10306:     print (OUT undef);
10307:     close (OUT);
10308:     return ("ok");    
10309: }
10310: 
10311: sub files_in_path {
10312:     my ($user, $path) = @_;
10313:     my $filename = $user."savedfiles";
10314:     my %return_files;
10315:     open (IN,'<',LONCAPA::tempdir().$filename);
10316:     while (my $line_in = <IN>) {
10317:         chomp ($line_in);
10318:         my @paths_and_file = split (m!/!, $line_in);
10319:         my $file_part = pop (@paths_and_file);
10320:         my $path_part = join ('/', @paths_and_file);
10321:         $path_part.='/';
10322:         my $path_and_file = $path_part.$file_part;
10323:         if ($path_part eq $path) {
10324:             $return_files{$file_part}= 'selected';
10325:         }
10326:     }
10327:     close (IN);
10328:     return (\%return_files);
10329: }
10330: 
10331: # called in portfolio select mode, to show files selected NOT in current directory
10332: sub files_not_in_path {
10333:     my ($user, $path) = @_;
10334:     my $filename = $user."savedfiles";
10335:     my @return_files;
10336:     my $path_part;
10337:     open(IN, '<',LONCAPA::tempdir().$filename);
10338:     while (my $line = <IN>) {
10339:         #ok, I know it's clunky, but I want it to work
10340:         my @paths_and_file = split(m|/|, $line);
10341:         my $file_part = pop(@paths_and_file);
10342:         chomp($file_part);
10343:         my $path_part = join('/', @paths_and_file);
10344:         $path_part .= '/';
10345:         my $path_and_file = $path_part.$file_part;
10346:         if ($path_part ne $path) {
10347:             push(@return_files, ($path_and_file));
10348:         }
10349:     }
10350:     close(OUT);
10351:     return (@return_files);
10352: }
10353: 
10354: #------------------------------Submitted/Handedback Portfolio Files Versioning
10355:  
10356: sub portfiles_versioning {
10357:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10358:     my $portfolio_root = '/userfiles/portfolio';
10359:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10360:     foreach my $file (@{$portfiles}) {
10361:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10362:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10363:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10364:         my $getpropath = 1;
10365:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10366:                                              $stu_name,$getpropath);
10367:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10368:         my $new_answer = 
10369:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10370:         if ($new_answer ne 'problem getting file') {
10371:             push(@{$versioned_portfiles}, $directory.$new_answer);
10372:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10373:                               [$symb,$env{'request.course.id'},'graded']);
10374:         }
10375:     }
10376: }
10377: 
10378: sub get_next_version {
10379:     my ($answer_name, $answer_ext, $dir_list) = @_;
10380:     my $version;
10381:     if (ref($dir_list) eq 'ARRAY') {
10382:         foreach my $row (@{$dir_list}) {
10383:             my ($file) = split(/\&/,$row,2);
10384:             my ($file_name,$file_version,$file_ext) =
10385:                 &file_name_version_ext($file);
10386:             if (($file_name eq $answer_name) &&
10387:                 ($file_ext eq $answer_ext)) {
10388:                      # gets here if filename and extension match,
10389:                      # regardless of version
10390:                 if ($file_version ne '') {
10391:                     # a versioned file is found  so save it for later
10392:                     if ($file_version > $version) {
10393:                         $version = $file_version;
10394:                     }
10395:                 }
10396:             }
10397:         }
10398:     }
10399:     $version ++;
10400:     return($version);
10401: }
10402: 
10403: sub version_selected_portfile {
10404:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10405:     my ($answer_name,$answer_ver,$answer_ext) =
10406:         &file_name_version_ext($file_name);
10407:     my $new_answer;
10408:     $env{'form.copy'} =
10409:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10410:     if($env{'form.copy'} eq '-1') {
10411:         $new_answer = 'problem getting file';
10412:     } else {
10413:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10414:         my $copy_result = 
10415:             &finishuserfileupload($stu_name,$domain,'copy',
10416:                                   '/portfolio'.$directory.$new_answer);
10417:     }
10418:     undef($env{'form.copy'});
10419:     return ($new_answer);
10420: }
10421: 
10422: sub file_name_version_ext {
10423:     my ($file)=@_;
10424:     my @file_parts = split(/\./, $file);
10425:     my ($name,$version,$ext);
10426:     if (@file_parts > 1) {
10427:         $ext=pop(@file_parts);
10428:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10429:             $version=pop(@file_parts);
10430:         }
10431:         $name=join('.',@file_parts);
10432:     } else {
10433:         $name=join('.',@file_parts);
10434:     }
10435:     return($name,$version,$ext);
10436: }
10437: 
10438: #----------------------------------------------Get portfolio file permissions
10439: 
10440: sub get_portfile_permissions {
10441:     my ($domain,$user) = @_;
10442:     my %current_permissions = &dump('file_permissions',$domain,$user);
10443:     my ($tmp)=keys(%current_permissions);
10444:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10445:     return \%current_permissions;
10446: }
10447: 
10448: #---------------------------------------------Get portfolio file access controls
10449: 
10450: sub get_access_controls {
10451:     my ($current_permissions,$group,$file) = @_;
10452:     my %access;
10453:     my $real_file = $file;
10454:     $file =~ s/\.meta$//;
10455:     if (defined($file)) {
10456:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10457:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10458:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10459:             }
10460:         }
10461:     } else {
10462:         foreach my $key (keys(%{$current_permissions})) {
10463:             if ($key =~ /\0accesscontrol$/) {
10464:                 if (defined($group)) {
10465:                     if ($key !~ m-^\Q$group\E/-) {
10466:                         next;
10467:                     }
10468:                 }
10469:                 my ($fullpath) = split(/\0/,$key);
10470:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10471:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10472:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10473:                     }
10474:                 }
10475:             }
10476:         }
10477:     }
10478:     return %access;
10479: }
10480: 
10481: sub modify_access_controls {
10482:     my ($file_name,$changes,$domain,$user)=@_;
10483:     my ($outcome,$deloutcome);
10484:     my %store_permissions;
10485:     my %new_values;
10486:     my %new_control;
10487:     my %translation;
10488:     my @deletions = ();
10489:     my $now = time;
10490:     if (exists($$changes{'activate'})) {
10491:         if (ref($$changes{'activate'}) eq 'HASH') {
10492:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10493:             my $numnew = scalar(@newitems);
10494:             for (my $i=0; $i<$numnew; $i++) {
10495:                 my $newkey = $newitems[$i];
10496:                 my $newid = &Apache::loncommon::get_cgi_id();
10497:                 if ($newkey =~ /^\d+:/) { 
10498:                     $newkey =~ s/^(\d+)/$newid/;
10499:                     $translation{$1} = $newid;
10500:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10501:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10502:                     $translation{$1} = $newid;
10503:                 }
10504:                 $new_values{$file_name."\0".$newkey} = 
10505:                                           $$changes{'activate'}{$newitems[$i]};
10506:                 $new_control{$newkey} = $now;
10507:             }
10508:         }
10509:     }
10510:     my %todelete;
10511:     my %changed_items;
10512:     foreach my $action ('delete','update') {
10513:         if (exists($$changes{$action})) {
10514:             if (ref($$changes{$action}) eq 'HASH') {
10515:                 foreach my $key (keys(%{$$changes{$action}})) {
10516:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10517:                     if ($action eq 'delete') { 
10518:                         $todelete{$itemnum} = 1;
10519:                     } else {
10520:                         $changed_items{$itemnum} = $key;
10521:                     }
10522:                 }
10523:             }
10524:         }
10525:     }
10526:     # get lock on access controls for file.
10527:     my $lockhash = {
10528:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10529:                                                        ':'.$env{'user.domain'},
10530:                    }; 
10531:     my $tries = 0;
10532:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10533:    
10534:     while (($gotlock ne 'ok') && $tries < 10) {
10535:         $tries ++;
10536:         sleep(0.1);
10537:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10538:     }
10539:     if ($gotlock eq 'ok') {
10540:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10541:         my ($tmp)=keys(%curr_permissions);
10542:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10543:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10544:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10545:             if (ref($curr_controls) eq 'HASH') {
10546:                 foreach my $control_item (keys(%{$curr_controls})) {
10547:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10548:                     if (defined($todelete{$itemnum})) {
10549:                         push(@deletions,$file_name."\0".$control_item);
10550:                     } else {
10551:                         if (defined($changed_items{$itemnum})) {
10552:                             $new_control{$changed_items{$itemnum}} = $now;
10553:                             push(@deletions,$file_name."\0".$control_item);
10554:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10555:                         } else {
10556:                             $new_control{$control_item} = $$curr_controls{$control_item};
10557:                         }
10558:                     }
10559:                 }
10560:             }
10561:         }
10562:         my ($group);
10563:         if (&is_course($domain,$user)) {
10564:             ($group,my $file) = split(/\//,$file_name,2);
10565:         }
10566:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10567:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10568:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10569:         #  remove lock
10570:         my @del_lock = ($file_name."\0".'locked_access_records');
10571:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10572:         my $sqlresult =
10573:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10574:                                     $group);
10575:     } else {
10576:         $outcome = "error: could not obtain lockfile\n";  
10577:     }
10578:     return ($outcome,$deloutcome,\%new_values,\%translation);
10579: }
10580: 
10581: sub make_public_indefinitely {
10582:     my (@requrl) = @_;
10583:     return &automated_portfile_access('public',\@requrl);
10584: }
10585: 
10586: sub automated_portfile_access {
10587:     my ($accesstype,$addsref,$delsref,$info) = @_;
10588:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10589:         return 'invalid';
10590:     }
10591:     my %urls;
10592:     if (ref($addsref) eq 'ARRAY') {
10593:         foreach my $requrl (@{$addsref}) {
10594:             if (&is_portfolio_url($requrl)) {
10595:                 unless (exists($urls{$requrl})) {
10596:                     $urls{$requrl} = 'add';
10597:                 }
10598:             }
10599:         }
10600:     }
10601:     if (ref($delsref) eq 'ARRAY') {
10602:         foreach my $requrl (@{$delsref}) { 
10603:             if (&is_portfolio_url($requrl)) {
10604:                 unless (exists($urls{$requrl})) {
10605:                     $urls{$requrl} = 'delete'; 
10606:                 }
10607:             }
10608:         }
10609:     }
10610:     unless (keys(%urls)) {
10611:         return 'invalid';
10612:     }
10613:     my $ip;
10614:     if ($accesstype eq 'ip') {
10615:         if (ref($info) eq 'HASH') {
10616:             if ($info->{'ip'} ne '') {
10617:                 $ip = $info->{'ip'};
10618:             }
10619:         }
10620:         if ($ip eq '') {
10621:             return 'invalid';
10622:         }
10623:     }
10624:     my $errors;
10625:     my $now = time;
10626:     my %current_perms;
10627:     foreach my $requrl (sort(keys(%urls))) {
10628:         my $action;
10629:         if ($urls{$requrl} eq 'add') {
10630:             $action = 'activate';
10631:         } else {
10632:             $action = 'none';
10633:         }
10634:         my $aclnum = 0;
10635:         my (undef,$udom,$unum,$file_name,$group) =
10636:             &parse_portfolio_url($requrl);
10637:         unless (exists($current_perms{$unum.':'.$udom})) {
10638:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10639:         }
10640:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10641:                                                    $group,$file_name);
10642:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10643:             my ($num,$scope,$end,$start) = 
10644:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10645:             if ($scope eq $accesstype) {
10646:                 if (($start <= $now) && ($end == 0)) {
10647:                     if ($accesstype eq 'ip') {
10648:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10649:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10650:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10651:                                     if ($urls{$requrl} eq 'add') {
10652:                                         $action = 'none';
10653:                                         last;
10654:                                     } else {
10655:                                         $action = 'delete';
10656:                                         $aclnum = $num;
10657:                                         last;
10658:                                     }
10659:                                 }
10660:                             }
10661:                         }
10662:                     } elsif ($accesstype eq 'public') {
10663:                         if ($urls{$requrl} eq 'add') {
10664:                             $action = 'none';
10665:                             last;
10666:                         } else {
10667:                             $action = 'delete';
10668:                             $aclnum = $num;
10669:                             last;
10670:                         }
10671:                     }
10672:                 } elsif ($accesstype eq 'public') {
10673:                     $action = 'update';
10674:                     $aclnum = $num;
10675:                     last;
10676:                 }
10677:             }
10678:         }
10679:         if ($action eq 'none') {
10680:             next;
10681:         } else {
10682:             my %changes;
10683:             my $newend = 0;
10684:             my $newstart = $now;
10685:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10686:             $changes{$action}{$newkey} = {
10687:                 type => $accesstype,
10688:                 time => {
10689:                     start => $newstart,
10690:                     end   => $newend,
10691:                 },
10692:             };
10693:             if ($accesstype eq 'ip') {
10694:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10695:             }
10696:             my ($outcome,$deloutcome,$new_values,$translation) =
10697:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10698:             unless ($outcome eq 'ok') {
10699:                 $errors .= $outcome.' ';
10700:             }
10701:         }
10702:     }
10703:     if ($errors) {
10704:         $errors =~ s/\s$//;
10705:         return $errors;
10706:     } else {
10707:         return 'ok';
10708:     }
10709: }
10710: 
10711: #------------------------------------------------------Get Marked as Read Only
10712: 
10713: sub get_marked_as_readonly {
10714:     my ($domain,$user,$what,$group) = @_;
10715:     my $current_permissions = &get_portfile_permissions($domain,$user);
10716:     my @readonly_files;
10717:     my $cmp1=$what;
10718:     if (ref($what)) { $cmp1=join('',@{$what}) };
10719:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10720:         if (defined($group)) {
10721:             if ($file_name !~ m-^\Q$group\E/-) {
10722:                 next;
10723:             }
10724:         }
10725:         if (ref($value) eq "ARRAY"){
10726:             foreach my $stored_what (@{$value}) {
10727:                 my $cmp2=$stored_what;
10728:                 if (ref($stored_what) eq 'ARRAY') {
10729:                     $cmp2=join('',@{$stored_what});
10730:                 }
10731:                 if ($cmp1 eq $cmp2) {
10732:                     push(@readonly_files, $file_name);
10733:                     last;
10734:                 } elsif (!defined($what)) {
10735:                     push(@readonly_files, $file_name);
10736:                     last;
10737:                 }
10738:             }
10739:         }
10740:     }
10741:     return @readonly_files;
10742: }
10743: #-----------------------------------------------------------Get Marked as Read Only Hash
10744: 
10745: sub get_marked_as_readonly_hash {
10746:     my ($current_permissions,$group,$what) = @_;
10747:     my %readonly_files;
10748:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10749:         if (defined($group)) {
10750:             if ($file_name !~ m-^\Q$group\E/-) {
10751:                 next;
10752:             }
10753:         }
10754:         if (ref($value) eq "ARRAY"){
10755:             foreach my $stored_what (@{$value}) {
10756:                 if (ref($stored_what) eq 'ARRAY') {
10757:                     foreach my $lock_descriptor(@{$stored_what}) {
10758:                         if ($lock_descriptor eq 'graded') {
10759:                             $readonly_files{$file_name} = 'graded';
10760:                         } elsif ($lock_descriptor eq 'handback') {
10761:                             $readonly_files{$file_name} = 'handback';
10762:                         } else {
10763:                             if (!exists($readonly_files{$file_name})) {
10764:                                 $readonly_files{$file_name} = 'locked';
10765:                             }
10766:                         }
10767:                     }
10768:                 } 
10769:             }
10770:         } 
10771:     }
10772:     return %readonly_files;
10773: }
10774: # ------------------------------------------------------------ Unmark as Read Only
10775: 
10776: sub unmark_as_readonly {
10777:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10778:     # for portfolio submissions, $what contains [$symb,$crsid] 
10779:     my ($domain,$user,$what,$file_name,$group) = @_;
10780:     $file_name = &declutter_portfile($file_name);
10781:     my $symb_crs = $what;
10782:     if (ref($what)) { $symb_crs=join('',@$what); }
10783:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10784:     my ($tmp)=keys(%current_permissions);
10785:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10786:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10787:     foreach my $file (@readonly_files) {
10788: 	my $clean_file = &declutter_portfile($file);
10789: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10790: 	my $current_locks = $current_permissions{$file};
10791:         my @new_locks;
10792:         my @del_keys;
10793:         if (ref($current_locks) eq "ARRAY"){
10794:             foreach my $locker (@{$current_locks}) {
10795:                 my $compare=$locker;
10796:                 if (ref($locker) eq 'ARRAY') {
10797:                     $compare=join('',@{$locker});
10798:                     if ($compare ne $symb_crs) {
10799:                         push(@new_locks, $locker);
10800:                     }
10801:                 }
10802:             }
10803:             if (scalar(@new_locks) > 0) {
10804:                 $current_permissions{$file} = \@new_locks;
10805:             } else {
10806:                 push(@del_keys, $file);
10807:                 &del('file_permissions',\@del_keys, $domain, $user);
10808:                 delete($current_permissions{$file});
10809:             }
10810:         }
10811:     }
10812:     &put('file_permissions',\%current_permissions,$domain,$user);
10813:     return;
10814: }
10815: 
10816: # ------------------------------------------------------------ Directory lister
10817: 
10818: sub dirlist {
10819:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10820:     $uri=~s/^\///;
10821:     $uri=~s/\/$//;
10822:     my ($udom, $uname);
10823:     if ($getuserdir) {
10824:         $udom = $userdomain;
10825:         $uname = $username;
10826:     } else {
10827:         (undef,$udom,$uname)=split(/\//,$uri);
10828:         if(defined($userdomain)) {
10829:             $udom = $userdomain;
10830:         }
10831:         if(defined($username)) {
10832:             $uname = $username;
10833:         }
10834:     }
10835:     my ($dirRoot,$listing,@listing_results);
10836: 
10837:     $dirRoot = $perlvar{'lonDocRoot'};
10838:     if (defined($getpropath)) {
10839:         $dirRoot = &propath($udom,$uname);
10840:         $dirRoot =~ s/\/$//;
10841:     } elsif (defined($getuserdir)) {
10842:         my $subdir=$uname.'__';
10843:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10844:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10845:                    ."/$udom/$subdir/$uname";
10846:     } elsif (defined($alternateRoot)) {
10847:         $dirRoot = $alternateRoot;
10848:     }
10849: 
10850:     if($udom) {
10851:         if($uname) {
10852:             my $uhome = &homeserver($uname,$udom);
10853:             if ($uhome eq 'no_host') {
10854:                 return ([],'no_host');
10855:             }
10856:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10857:                               .$getuserdir.':'.&escape($dirRoot)
10858:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10859:             if ($listing eq 'unknown_cmd') {
10860:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10861:             } else {
10862:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10863:             }
10864:             if ($listing eq 'unknown_cmd') {
10865:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10866:                 @listing_results = split(/:/,$listing);
10867:             } else {
10868:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10869:             }
10870:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10871:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10872:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10873:                 return ([],$listing);
10874:             } else {
10875:                 return (\@listing_results);
10876:             }
10877:         } elsif(!$alternateRoot) {
10878:             my (%allusers,%listerror);
10879: 	    my %servers = &get_servers($udom,'library');
10880:  	    foreach my $tryserver (keys(%servers)) {
10881:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10882:                                   &escape($udom),$tryserver);
10883:                 if ($listing eq 'unknown_cmd') {
10884: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10885: 				      $udom, $tryserver);
10886:                 } else {
10887:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10888:                 }
10889: 		if ($listing eq 'unknown_cmd') {
10890: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10891: 				      $udom, $tryserver);
10892: 		    @listing_results = split(/:/,$listing);
10893: 		} else {
10894: 		    @listing_results =
10895: 			map { &unescape($_); } split(/:/,$listing);
10896: 		}
10897:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10898:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10899:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10900:                     $listerror{$tryserver} = $listing;
10901:                 } else {
10902: 		    foreach my $line (@listing_results) {
10903: 			my ($entry) = split(/&/,$line,2);
10904: 			$allusers{$entry} = 1;
10905: 		    }
10906: 		}
10907:             }
10908:             my @alluserslist=();
10909:             foreach my $user (sort(keys(%allusers))) {
10910:                 push(@alluserslist,$user.'&user');
10911:             }
10912: 
10913:             if (!%listerror) {
10914:                 # no errors
10915:                 return (\@alluserslist);
10916:             } elsif (scalar(keys(%servers)) == 1) {
10917:                 # one library server, one error 
10918:                 my ($key) = keys(%listerror);
10919:                 return (\@alluserslist, $listerror{$key});
10920:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10921:                 # con_lost indicates that we might miss data from at least one
10922:                 # library server
10923:                 return (\@alluserslist, 'con_lost');
10924:             } else {
10925:                 # multiple library servers and no con_lost -> data should be
10926:                 # complete. 
10927:                 return (\@alluserslist);
10928:             }
10929: 
10930:         } else {
10931:             return ([],'missing username');
10932:         }
10933:     } elsif(!defined($getpropath)) {
10934:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10935:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10936:         return (\@all_domains);
10937:     } else {
10938:         return ([],'missing domain');
10939:     }
10940: }
10941: 
10942: # --------------------------------------------- GetFileTimestamp
10943: # This function utilizes dirlist and returns the date stamp for
10944: # when it was last modified.  It will also return an error of -1
10945: # if an error occurs
10946: 
10947: sub GetFileTimestamp {
10948:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10949:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10950:     $studentName   = &LONCAPA::clean_username($studentName);
10951:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10952:                                     undef,$getuserdir);
10953:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10954:         return -1;
10955:     }
10956:     if (ref($fileref) eq 'ARRAY') {
10957:         my @stats = split('&',$fileref->[0]);
10958:         # @stats contains first the filename, then the stat output
10959:         return $stats[10]; # so this is 10 instead of 9.
10960:     } else {
10961:         return -1;
10962:     }
10963: }
10964: 
10965: sub stat_file {
10966:     my ($uri) = @_;
10967:     $uri = &clutter_with_no_wrapper($uri);
10968: 
10969:     my ($udom,$uname,$file);
10970:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10971: 	($udom,$uname,$file) =
10972: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10973: 	$file = 'userfiles/'.$file;
10974:     }
10975:     if ($uri =~ m-^/res/-) {
10976: 	($udom,$uname) = 
10977: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10978: 	$file = $uri;
10979:     }
10980: 
10981:     if (!$udom || !$uname || !$file) {
10982: 	# unable to handle the uri
10983: 	return ();
10984:     }
10985:     my $getpropath;
10986:     if ($file =~ /^userfiles\//) {
10987:         $getpropath = 1;
10988:     }
10989:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10990:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10991:         return ();
10992:     } else {
10993:         if (ref($listref) eq 'ARRAY') {
10994:             my @stats = split('&',$listref->[0]);
10995: 	    shift(@stats); #filename is first
10996: 	    return @stats;
10997:         }
10998:     }
10999:     return ();
11000: }
11001: 
11002: # --------------------------------------------------------- recursedirs
11003: # Recursive function to traverse either a specific user's Authoring Space
11004: # or corresponding Published Resource Space, and populate the hash ref:
11005: # $dirhashref with URLs of all directories, and if $filehashref hash
11006: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11007: # or .rights files in resource space, and .meta, .save, .log, and .bak
11008: # files in Authoring Space.
11009: #
11010: # Inputs:
11011: #
11012: # $is_home - true if current server is home server for user's space
11013: # $context - either: priv, or res respectively for Authoring or Resource Space.
11014: # $docroot - Document root (i.e., /home/httpd/html
11015: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11016: # $relpath - Current path (relative to top level).
11017: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11018: # $filehashref - reference to hash to populate with URLs of files (Optional)
11019: #
11020: # Returns: nothing
11021: #
11022: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11023: #
11024: # Currently used by interface/londocs.pm to create linked select boxes for
11025: # directory and filename to import a Course "Author" resource into a course, and
11026: # also to create linked select boxes for Authoring Space and Directory to choose
11027: # save location for creation of a new "standard" problem from the Course Editor.
11028: #
11029: 
11030: sub recursedirs {
11031:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11032:     return unless (ref($dirhashref) eq 'HASH');
11033:     my $currpath = $docroot.$toppath;
11034:     if ($relpath) {
11035:         $currpath .= "/$relpath";
11036:     }
11037:     my $savefile;
11038:     if (ref($filehashref)) {
11039:         $savefile = 1;
11040:     }
11041:     if ($is_home) {
11042:         if (opendir(my $dirh,$currpath)) {
11043:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11044:                 next if ($item eq '');
11045:                 if (-d "$currpath/$item") {
11046:                     my $newpath;
11047:                     if ($relpath) {
11048:                         $newpath = "$relpath/$item";
11049:                     } else {
11050:                         $newpath = $item;
11051:                     }
11052:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11053:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11054:                 } elsif ($savefile) {
11055:                     if ($context eq 'priv') {
11056:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11057:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11058:                         }
11059:                     } else {
11060:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11061:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11062:                         }
11063:                     }
11064:                 }
11065:             }
11066:             closedir($dirh);
11067:         }
11068:     } else {
11069:         my ($dirlistref,$listerror) =
11070:             &dirlist($toppath.$relpath);
11071:         my @dir_lines;
11072:         my $dirptr=16384;
11073:         if (ref($dirlistref) eq 'ARRAY') {
11074:             foreach my $dir_line (sort
11075:                               {
11076:                                   my ($afile)=split('&',$a,2);
11077:                                   my ($bfile)=split('&',$b,2);
11078:                                   return (lc($afile) cmp lc($bfile));
11079:                               } (@{$dirlistref})) {
11080:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11081:                     split(/\&/,$dir_line,16);
11082:                 $item =~ s/\s+$//;
11083:                 next if (($item =~ /^\.\.?$/) || ($obs));
11084:                 if ($dirptr&$testdir) {
11085:                     my $newpath;
11086:                     if ($relpath) {
11087:                         $newpath = "$relpath/$item";
11088:                     } else {
11089:                         $relpath = '/';
11090:                         $newpath = $item;
11091:                     }
11092:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11093:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11094:                 } elsif ($savefile) {
11095:                     if ($context eq 'priv') {
11096:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11097:                             $filehashref->{$relpath}{$item} = 1;
11098:                         }
11099:                     } else {
11100:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11101:                             $filehashref->{$relpath}{$item} = 1;
11102:                         }
11103:                     }
11104:                 }
11105:             }
11106:         }
11107:     }
11108:     return;
11109: }
11110: 
11111: # -------------------------------------------------------- Value of a Condition
11112: 
11113: # gets the value of a specific preevaluated condition
11114: #    stored in the string  $env{user.state.<cid>}
11115: # or looks up a condition reference in the bighash and if if hasn't
11116: # already been evaluated recurses into docondval to get the value of
11117: # the condition, then memoizing it to 
11118: #   $env{user.state.<cid>.<condition>}
11119: sub directcondval {
11120:     my $number=shift;
11121:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11122: 	&Apache::lonuserstate::evalstate();
11123:     }
11124:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11125: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11126:     } elsif ($number =~ /^_/) {
11127: 	my $sub_condition;
11128: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11129: 		&GDBM_READER(),0640)) {
11130: 	    $sub_condition=$bighash{'conditions'.$number};
11131: 	    untie(%bighash);
11132: 	}
11133: 	my $value = &docondval($sub_condition);
11134: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11135: 	return $value;
11136:     }
11137:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11138:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11139:     } else {
11140:        return 2;
11141:     }
11142: }
11143: 
11144: # get the collection of conditions for this resource
11145: sub condval {
11146:     my $condidx=shift;
11147:     my $allpathcond='';
11148:     foreach my $cond (split(/\|/,$condidx)) {
11149: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11150: 	    $allpathcond.=
11151: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11152: 	}
11153:     }
11154:     $allpathcond=~s/\|$//;
11155:     return &docondval($allpathcond);
11156: }
11157: 
11158: #evaluates an expression of conditions
11159: sub docondval {
11160:     my ($allpathcond) = @_;
11161:     my $result=0;
11162:     if ($env{'request.course.id'}
11163: 	&& defined($allpathcond)) {
11164: 	my $operand='|';
11165: 	my @stack;
11166: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11167: 	    if ($chunk eq '(') {
11168: 		push @stack,($operand,$result);
11169: 	    } elsif ($chunk eq ')') {
11170: 		my $before=pop @stack;
11171: 		if (pop @stack eq '&') {
11172: 		    $result=$result>$before?$before:$result;
11173: 		} else {
11174: 		    $result=$result>$before?$result:$before;
11175: 		}
11176: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11177: 		$operand=$chunk;
11178: 	    } else {
11179: 		my $new=directcondval($chunk);
11180: 		if ($operand eq '&') {
11181: 		    $result=$result>$new?$new:$result;
11182: 		} else {
11183: 		    $result=$result>$new?$result:$new;
11184: 		}
11185: 	    }
11186: 	}
11187:     }
11188:     return $result;
11189: }
11190: 
11191: # ---------------------------------------------------- Devalidate courseresdata
11192: 
11193: sub devalidatecourseresdata {
11194:     my ($coursenum,$coursedomain)=@_;
11195:     my $hashid=$coursenum.':'.$coursedomain;
11196:     &devalidate_cache_new('courseres',$hashid);
11197: }
11198: 
11199: 
11200: # --------------------------------------------------- Course Resourcedata Query
11201: #
11202: #  Parameters:
11203: #      $coursenum    - Number of the course.
11204: #      $coursedomain - Domain at which the course was created.
11205: #  Returns:
11206: #     A hash of the course parameters along (I think) with timestamps
11207: #     and version info.
11208: 
11209: sub get_courseresdata {
11210:     my ($coursenum,$coursedomain)=@_;
11211:     my $coursehom=&homeserver($coursenum,$coursedomain);
11212:     my $hashid=$coursenum.':'.$coursedomain;
11213:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11214:     my %dumpreply;
11215:     unless (defined($cached)) {
11216: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11217: 	$result=\%dumpreply;
11218: 	my ($tmp) = keys(%dumpreply);
11219: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11220: 	    &do_cache_new('courseres',$hashid,$result,600);
11221: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11222: 	    return $tmp;
11223: 	} elsif ($tmp =~ /^(error)/) {
11224: 	    $result=undef;
11225: 	    &do_cache_new('courseres',$hashid,$result,600);
11226: 	}
11227:     }
11228:     return $result;
11229: }
11230: 
11231: sub devalidateuserresdata {
11232:     my ($uname,$udom)=@_;
11233:     my $hashid="$udom:$uname";
11234:     &devalidate_cache_new('userres',$hashid);
11235: }
11236: 
11237: sub get_userresdata {
11238:     my ($uname,$udom)=@_;
11239:     #most student don\'t have any data set, check if there is some data
11240:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11241: 
11242:     my $hashid="$udom:$uname";
11243:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11244:     if (!defined($cached)) {
11245: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11246: 	$result=\%resourcedata;
11247: 	&do_cache_new('userres',$hashid,$result,600);
11248:     }
11249:     my ($tmp)=keys(%$result);
11250:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11251: 	return $result;
11252:     }
11253:     #error 2 occurs when the .db doesn't exist
11254:     if ($tmp!~/error: 2 /) {
11255:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11256: 	    &logthis("<font color=\"blue\">WARNING:".
11257: 		     " Trying to get resource data for ".
11258: 		     $uname." at ".$udom.": ".
11259: 		     $tmp."</font>");
11260:         }
11261:     } elsif ($tmp=~/error: 2 /) {
11262: 	#&EXT_cache_set($udom,$uname);
11263: 	&do_cache_new('userres',$hashid,undef,600);
11264: 	undef($tmp); # not really an error so don't send it back
11265:     }
11266:     return $tmp;
11267: }
11268: #----------------------------------------------- resdata - return resource data
11269: #  Purpose:
11270: #    Return resource data for either users or for a course.
11271: #  Parameters:
11272: #     $name      - Course/user name.
11273: #     $domain    - Name of the domain the user/course is registered on.
11274: #     $type      - Type of thing $name is (must be 'course' or 'user')
11275: #     $mapp      - decluttered URL of enclosing map  
11276: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11277: #     $recurseup - Ref to array of map URLs, starting with map containing
11278: #                  $mapp up through hierarchy of nested maps to top level map.  
11279: #     $courseid  - CourseID (first part of param identifier).
11280: #     $modifier  - Middle part of param identifier.
11281: #     $what      - Last part of param identifier.
11282: #     @which     - Array of names of resources desired.
11283: #  Returns:
11284: #     The value of the first reasource in @which that is found in the
11285: #     resource hash.
11286: #  Exceptional Conditions:
11287: #     If the $type passed in is not valid (not the string 'course' or 
11288: #     'user', an undefined  reference is returned.
11289: #     If none of the resources are found, an undef is returned
11290: sub resdata {
11291:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11292:         $modifier,$what,@which)=@_;
11293:     my $result;
11294:     if ($type eq 'course') {
11295: 	$result=&get_courseresdata($name,$domain);
11296:     } elsif ($type eq 'user') {
11297: 	$result=&get_userresdata($name,$domain);
11298:     }
11299:     if (!ref($result)) { return $result; }    
11300:     foreach my $item (@which) {
11301:         if ($item->[1] eq 'course') {
11302:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11303:                 unless ($$recursed) {
11304:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11305:                     $$recursed = 1;
11306:                 }
11307:                 foreach my $item (@${recurseup}) {
11308:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11309:                     last if (defined($result->{$norecursechk}));
11310:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11311:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11312:                 }
11313:             }
11314:         }
11315:         if (defined($result->{$item->[0]})) {
11316: 	    return [$result->{$item->[0]},$item->[1]];
11317: 	}
11318:     }
11319:     return undef;
11320: }
11321: 
11322: sub get_domain_lti {
11323:     my ($cdom,$context) = @_;
11324:     my ($name,%lti);
11325:     if ($context eq 'consumer') {
11326:         $name = 'ltitools';
11327:     } elsif ($context eq 'provider') {
11328:         $name = 'lti';
11329:     } else {
11330:         return %lti;
11331:     }
11332:     my ($result,$cached)=&is_cached_new($name,$cdom);
11333:     if (defined($cached)) {
11334:         if (ref($result) eq 'HASH') {
11335:             %lti = %{$result};
11336:         }
11337:     } else {
11338:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11339:         if (ref($domconfig{$name}) eq 'HASH') {
11340:             %lti = %{$domconfig{$name}};
11341:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11342:             if (ref($encdomconfig{$name}) eq 'HASH') {
11343:                 foreach my $id (keys(%lti)) {
11344:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11345:                         foreach my $item ('key','secret') {
11346:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11347:                         }
11348:                     }
11349:                 }
11350:             }
11351:         }
11352:         my $cachetime = 24*60*60;
11353:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11354:     }
11355:     return %lti;
11356: }
11357: 
11358: sub get_numsuppfiles {
11359:     my ($cnum,$cdom,$ignorecache)=@_;
11360:     my $hashid=$cnum.':'.$cdom;
11361:     my ($suppcount,$cached);
11362:     unless ($ignorecache) {
11363:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11364:     }
11365:     unless (defined($cached)) {
11366:         my $chome=&homeserver($cnum,$cdom);
11367:         unless ($chome eq 'no_host') {
11368:             ($suppcount,my $supptools,my $errors) = (0,0,0);
11369:             my $suppmap = 'supplemental.sequence';
11370:             ($suppcount,$supptools,$errors) =
11371:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
11372:                                                          $supptools,$errors);
11373:         }
11374:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11375:     }
11376:     return $suppcount;
11377: }
11378: 
11379: #
11380: # EXT resource caching routines
11381: #
11382: 
11383: {
11384: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11385: #
11386: # The course for which we cache
11387: my $cachedmapkey='';
11388: # The cached recursive maps for this course
11389: my %cachedmaps=();
11390: # When this was last done
11391: my $cachedmaptime='';
11392: 
11393: sub clear_EXT_cache_status {
11394:     &delenv('cache.EXT.');
11395: }
11396: 
11397: sub EXT_cache_status {
11398:     my ($target_domain,$target_user) = @_;
11399:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11400:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11401:         # We know already the user has no data
11402:         return 1;
11403:     } else {
11404:         return 0;
11405:     }
11406: }
11407: 
11408: sub EXT_cache_set {
11409:     my ($target_domain,$target_user) = @_;
11410:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11411:     #&appenv({$cachename => time});
11412: }
11413: 
11414: # --------------------------------------------------------- Value of a Variable
11415: sub EXT {
11416: 
11417:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11418:     unless ($varname) { return ''; }
11419:     #get real user name/domain, courseid and symb
11420:     my $courseid;
11421:     my $publicuser;
11422:     if ($symbparm) {
11423: 	$symbparm=&get_symb_from_alias($symbparm);
11424:     }
11425:     if (!($uname && $udom)) {
11426:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11427:       if (!$symbparm) {	$symbparm=$cursymb; }
11428:     } else {
11429: 	$courseid=$env{'request.course.id'};
11430:     }
11431:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11432:     my $rest;
11433:     if (defined($therest[0])) {
11434:        $rest=join('.',@therest);
11435:     } else {
11436:        $rest='';
11437:     }
11438: 
11439:     my $qualifierrest=$qualifier;
11440:     if ($rest) { $qualifierrest.='.'.$rest; }
11441:     my $spacequalifierrest=$space;
11442:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11443:     if ($realm eq 'user') {
11444: # --------------------------------------------------------------- user.resource
11445: 	if ($space eq 'resource') {
11446: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11447: 		  || defined($Apache::lonhomework::parsing_a_task))
11448: 		 &&
11449: 		 ($symbparm eq &symbread()) ) {	
11450: 		# if we are in the middle of processing the resource the
11451: 		# get the value we are planning on committing
11452:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11453:                     return $Apache::lonhomework::results{$qualifierrest};
11454:                 } else {
11455:                     return $Apache::lonhomework::history{$qualifierrest};
11456:                 }
11457: 	    } else {
11458: 		my %restored;
11459: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11460: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11461: 		} else {
11462: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11463: 		}
11464: 		return $restored{$qualifierrest};
11465: 	    }
11466: # ----------------------------------------------------------------- user.access
11467:         } elsif ($space eq 'access') {
11468: 	    # FIXME - not supporting calls for a specific user
11469:             return &allowed($qualifier,$rest);
11470: # ------------------------------------------ user.preferences, user.environment
11471:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11472: 	    if (($uname eq $env{'user.name'}) &&
11473: 		($udom eq $env{'user.domain'})) {
11474: 		return $env{join('.',('environment',$qualifierrest))};
11475: 	    } else {
11476: 		my %returnhash;
11477: 		if (!$publicuser) {
11478: 		    %returnhash=&userenvironment($udom,$uname,
11479: 						 $qualifierrest);
11480: 		}
11481: 		return $returnhash{$qualifierrest};
11482: 	    }
11483: # ----------------------------------------------------------------- user.course
11484:         } elsif ($space eq 'course') {
11485: 	    # FIXME - not supporting calls for a specific user
11486:             return $env{join('.',('request.course',$qualifier))};
11487: # ------------------------------------------------------------------- user.role
11488:         } elsif ($space eq 'role') {
11489: 	    # FIXME - not supporting calls for a specific user
11490:             my ($role,$where)=split(/\./,$env{'request.role'});
11491:             if ($qualifier eq 'value') {
11492: 		return $role;
11493:             } elsif ($qualifier eq 'extent') {
11494:                 return $where;
11495:             }
11496: # ----------------------------------------------------------------- user.domain
11497:         } elsif ($space eq 'domain') {
11498:             return $udom;
11499: # ------------------------------------------------------------------- user.name
11500:         } elsif ($space eq 'name') {
11501:             return $uname;
11502: # ---------------------------------------------------- Any other user namespace
11503:         } else {
11504: 	    my %reply;
11505: 	    if (!$publicuser) {
11506: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11507: 	    }
11508: 	    return $reply{$qualifierrest};
11509:         }
11510:     } elsif ($realm eq 'query') {
11511: # ---------------------------------------------- pull stuff out of query string
11512:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11513: 						[$spacequalifierrest]);
11514: 	return $env{'form.'.$spacequalifierrest}; 
11515:    } elsif ($realm eq 'request') {
11516: # ------------------------------------------------------------- request.browser
11517:         if ($space eq 'browser') {
11518:             return $env{'browser.'.$qualifier};
11519: # ------------------------------------------------------------ request.filename
11520:         } else {
11521:             return $env{'request.'.$spacequalifierrest};
11522:         }
11523:     } elsif ($realm eq 'course') {
11524: # ---------------------------------------------------------- course.description
11525:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11526:     } elsif ($realm eq 'resource') {
11527: 
11528: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11529: 	    if (!$symbparm) { $symbparm=&symbread(); }
11530: 	}
11531: 
11532:         if ($qualifier eq '') {
11533: 	    if ($space eq 'title') {
11534: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11535: 	        return &gettitle($symbparm);
11536: 	    }
11537: 	
11538: 	    if ($space eq 'map') {
11539: 	        my ($map) = &decode_symb($symbparm);
11540: 	        return &symbread($map);
11541: 	    }
11542:             if ($space eq 'maptitle') {
11543:                 my ($map) = &decode_symb($symbparm);
11544:                 return &gettitle($map);
11545:             }
11546: 	    if ($space eq 'filename') {
11547: 	        if ($symbparm) {
11548: 		    return &clutter((&decode_symb($symbparm))[2]);
11549: 	        }
11550: 	        return &hreflocation('',$env{'request.filename'});
11551: 	    }
11552: 
11553:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11554:                 if ($space eq 'visibleparts') {
11555:                     my $navmap = Apache::lonnavmaps::navmap->new();
11556:                     my $item;
11557:                     if (ref($navmap)) {
11558:                         my $res = $navmap->getBySymb($symbparm);
11559:                         my $parts = $res->parts();
11560:                         if (ref($parts) eq 'ARRAY') {
11561:                             $item = join(',',@{$parts});
11562:                         }
11563:                         undef($navmap);
11564:                     }
11565:                     return $item;
11566:                 }
11567:             }
11568:         }
11569: 
11570: 	my ($section, $group, @groups, @recurseup, $recursed);
11571: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11572:         if (($courseid eq '') && ($cid)) {
11573:             $courseid = $cid;
11574:         }
11575: 	if (($symbparm && $courseid) && 
11576: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11577: 
11578: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11579: 
11580: # ----------------------------------------------------- Cascading lookup scheme
11581: 	    my $symbp=$symbparm;
11582: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11583: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11584:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11585: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11586: 	    if (($env{'user.name'} eq $uname) &&
11587: 		($env{'user.domain'} eq $udom)) {
11588: 		$section=$env{'request.course.sec'};
11589:                 @groups = split(/:/,$env{'request.course.groups'});  
11590:                 @groups=&sort_course_groups($courseid,@groups); 
11591: 	    } else {
11592: 		if (! defined($usection)) {
11593: 		    $section=&getsection($udom,$uname,$courseid);
11594: 		} else {
11595: 		    $section = $usection;
11596: 		}
11597:                 @groups = &get_users_groups($udom,$uname,$courseid);
11598: 	    }
11599: 
11600: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11601: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11602:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11603: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11604: 
11605: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11606: 	    my $courselevelr=$courseid.'.'.$symbparm;
11607:             $courseleveli=$courseid.'.'.$recurseparm;
11608: 	    $courselevelm=$courseid.'.'.$mapparm;
11609: 
11610: # ----------------------------------------------------------- first, check user
11611: 
11612: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11613:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11614: 				       ([$courselevelr,'resource'],
11615: 					[$courselevelm,'map'     ],
11616:                                         [$courseleveli,'map'     ],
11617: 					[$courselevel, 'course'  ]));
11618: 	    if (defined($userreply)) { return &get_reply($userreply); }
11619: 
11620: # ------------------------------------------------ second, check some of course
11621:             my $coursereply;
11622:             if (@groups > 0) {
11623:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11624:                                        $recurseparm,$mapparm,$spacequalifierrest,
11625:                                        $mapp,\$recursed,\@recurseup);
11626:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11627:             }
11628: 
11629: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11630: 				  $env{'course.'.$courseid.'.domain'},
11631: 				  'course',$mapp,\$recursed,\@recurseup,
11632:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11633: 				  ([$seclevelr,   'resource'],
11634: 				   [$seclevelm,   'map'     ],
11635:                                    [$secleveli,   'map'     ],
11636: 				   [$seclevel,    'course'  ],
11637: 				   [$courselevelr,'resource']));
11638: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11639: 
11640: # ------------------------------------------------------ third, check map parms
11641: 	    my %parmhash=();
11642: 	    my $thisparm='';
11643: 	    if (tie(%parmhash,'GDBM_File',
11644: 		    $env{'request.course.fn'}.'_parms.db',
11645: 		    &GDBM_READER(),0640)) {
11646: 		$thisparm=$parmhash{$symbparm};
11647: 		untie(%parmhash);
11648: 	    }
11649: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11650: 	}
11651: # ------------------------------------------ fourth, look in resource metadata
11652:  
11653:         my $what = $spacequalifierrest;
11654: 	$what=~s/\./\_/;
11655: 	my $filename;
11656: 	if (!$symbparm) { $symbparm=&symbread(); }
11657: 	if ($symbparm) {
11658: 	    $filename=(&decode_symb($symbparm))[2];
11659: 	} else {
11660: 	    $filename=$env{'request.filename'};
11661: 	}
11662:         my $toolsymb;
11663:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
11664:             $toolsymb = $symbparm;
11665:         }
11666: 	my $metadata=&metadata($filename,$what,$toolsymb);
11667: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11668: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
11669: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11670: 
11671: # ----------------------------------------------- fifth, look in rest of course
11672: 	if ($symbparm && defined($courseid) && 
11673: 	    $courseid eq $env{'request.course.id'}) {
11674: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11675: 				     $env{'course.'.$courseid.'.domain'},
11676: 				     'course',$mapp,\$recursed,\@recurseup,
11677:                                      $courseid,'.',$spacequalifierrest,
11678: 				     ([$courselevelm,'map'   ],
11679:                                       [$courseleveli,'map'   ],
11680: 				      [$courselevel, 'course']));
11681: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11682: 	}
11683: # ------------------------------------------------------------------ Cascade up
11684: 	unless ($space eq '0') {
11685: 	    my @parts=split(/_/,$space);
11686: 	    my $id=pop(@parts);
11687: 	    my $part=join('_',@parts);
11688: 	    if ($part eq '') { $part='0'; }
11689: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11690: 				 $symbparm,$udom,$uname,$section,1);
11691: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11692: 	}
11693: 	if ($recurse) { return undef; }
11694: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
11695: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11696: # ---------------------------------------------------- Any other user namespace
11697:     } elsif ($realm eq 'environment') {
11698: # ----------------------------------------------------------------- environment
11699: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11700: 	    return $env{'environment.'.$spacequalifierrest};
11701: 	} else {
11702: 	    if ($uname eq 'anonymous' && $udom eq '') {
11703: 		return '';
11704: 	    }
11705: 	    my %returnhash=&userenvironment($udom,$uname,
11706: 					    $spacequalifierrest);
11707: 	    return $returnhash{$spacequalifierrest};
11708: 	}
11709:     } elsif ($realm eq 'system') {
11710: # ----------------------------------------------------------------- system.time
11711: 	if ($space eq 'time') {
11712: 	    return time;
11713:         }
11714:     } elsif ($realm eq 'server') {
11715: # ----------------------------------------------------------------- system.time
11716: 	if ($space eq 'name') {
11717: 	    return $ENV{'SERVER_NAME'};
11718:         }
11719:     }
11720:     return '';
11721: }
11722: 
11723: sub get_reply {
11724:     my ($reply_value) = @_;
11725:     if (ref($reply_value) eq 'ARRAY') {
11726:         if (wantarray) {
11727: 	    return @$reply_value;
11728:         }
11729:         return $reply_value->[0];
11730:     } else {
11731:         return $reply_value;
11732:     }
11733: }
11734: 
11735: sub check_group_parms {
11736:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11737:         $recursed,$recurseupref) = @_;
11738:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11739:                   [$what,'course']);
11740:     my $coursereply;
11741:     foreach my $group (@{$groups}) {
11742:         my @groupitems = ();
11743:         foreach my $level (@levels) {
11744:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11745:              push(@groupitems,[$item,$level->[1]]);
11746:         }
11747:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11748:                                    $env{'course.'.$courseid.'.domain'},
11749:                                    'course',$mapp,$recursed,$recurseupref,
11750:                                    $courseid,'.['.$group.'].',$what,
11751:                                    @groupitems);
11752:         last if (defined($coursereply));
11753:     }
11754:     return $coursereply;
11755: }
11756: 
11757: sub get_map_hierarchy {
11758:     my ($mapname,$courseid) = @_;
11759:     my @recurseup = ();
11760:     if ($mapname) {
11761:         if (($cachedmapkey eq $courseid) &&
11762:             (abs($cachedmaptime-time)<5)) {
11763:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11764:                 return @{$cachedmaps{$mapname}};
11765:             }
11766:         }
11767:         my $navmap = Apache::lonnavmaps::navmap->new();
11768:         if (ref($navmap)) {
11769:             @recurseup = $navmap->recurseup_maps($mapname);
11770:             undef($navmap);
11771:             $cachedmaps{$mapname} = \@recurseup;
11772:             $cachedmaptime=time;
11773:             $cachedmapkey=$courseid;
11774:         }
11775:     }
11776:     return @recurseup;
11777: }
11778: 
11779: }
11780: 
11781: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11782:     my ($courseid,@groups) = @_;
11783:     @groups = sort(@groups);
11784:     return @groups;
11785: }
11786: 
11787: sub packages_tab_default {
11788:     my ($uri,$varname,$toolsymb)=@_;
11789:     my (undef,$part,$name)=split(/\./,$varname);
11790: 
11791:     my (@extension,@specifics,$do_default);
11792:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
11793: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11794: 	if ($pack_type eq 'default') {
11795: 	    $do_default=1;
11796: 	} elsif ($pack_type eq 'extension') {
11797: 	    push(@extension,[$package,$pack_type,$pack_part]);
11798: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11799: 	    # only look at packages defaults for packages that this id is
11800: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11801: 	}
11802:     }
11803:     # first look for a package that matches the requested part id
11804:     foreach my $package (@specifics) {
11805: 	my (undef,$pack_type,$pack_part)=@{$package};
11806: 	next if ($pack_part ne $part);
11807: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11808: 	    return $packagetab{"$pack_type&$name&default"};
11809: 	}
11810:     }
11811:     # look for any possible matching non extension_ package
11812:     foreach my $package (@specifics) {
11813: 	my (undef,$pack_type,$pack_part)=@{$package};
11814: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11815: 	    return $packagetab{"$pack_type&$name&default"};
11816: 	}
11817: 	if ($pack_type eq 'part') { $pack_part='0'; }
11818: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11819: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11820: 	}
11821:     }
11822:     # look for any posible extension_ match
11823:     foreach my $package (@extension) {
11824: 	my ($package,$pack_type)=@{$package};
11825: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11826: 	    return $packagetab{"$pack_type&$name&default"};
11827: 	}
11828: 	if (defined($packagetab{$package."&$name&default"})) {
11829: 	    return $packagetab{$package."&$name&default"};
11830: 	}
11831:     }
11832:     # look for a global default setting
11833:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11834: 	return $packagetab{"default&$name&default"};
11835:     }
11836:     return undef;
11837: }
11838: 
11839: sub add_prefix_and_part {
11840:     my ($prefix,$part)=@_;
11841:     my $keyroot;
11842:     if (defined($prefix) && $prefix !~ /^__/) {
11843: 	# prefix that has a part already
11844: 	$keyroot=$prefix;
11845:     } elsif (defined($prefix)) {
11846: 	# prefix that is missing a part
11847: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11848:     } else {
11849: 	# no prefix at all
11850: 	if (defined($part)) { $keyroot='_'.$part; }
11851:     }
11852:     return $keyroot;
11853: }
11854: 
11855: # ---------------------------------------------------------------- Get metadata
11856: 
11857: my %metaentry;
11858: my %importedpartids;
11859: my %importedrespids;
11860: sub metadata {
11861:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
11862:     $uri=&declutter($uri);
11863:     # if it is a non metadata possible uri return quickly
11864:     if (($uri eq '') || 
11865: 	(($uri =~ m|^/*adm/|) && 
11866: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11867:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11868: 	return undef;
11869:     }
11870:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11871: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11872: 	return undef;
11873:     }
11874:     my $filename=$uri;
11875:     $uri=~s/\.meta$//;
11876: #
11877: # Is the metadata already cached?
11878: # Look at timestamp of caching
11879: # Everything is cached by the main uri, libraries are never directly cached
11880: #
11881:     if (!defined($liburi)) {
11882: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11883: 	if (defined($cached)) { return $result->{':'.$what}; }
11884:     }
11885: 
11886: #
11887: # If the uri is for an external tool the file from
11888: # which metadata should be retrieved depends on whether
11889: # the tool had been configured to be gradable (set in the Course
11890: # Editor or Resource Editor).
11891: #
11892: # If a valid symb has been included as the third arg in the call
11893: # to &metadata() that can be used to retrieve the value of
11894: # parameter_0_gradable set for the resource, and included in the
11895: # uploaded map containing the tool. The value is retrieved via
11896: # &EXT(), if a valid symb is available.  Otherwise the value of
11897: # gradable in the exttool_$marker.db file for the tool instance
11898: # is retrieved via &get().
11899: #
11900: # When lonuserstate::traceroute() calls lonnet::EXT() for 
11901: # hiddenresource and encrypturl (during course initialization)
11902: # the map-level parameter for resource.0.gradable included in the 
11903: # uploaded map containing the tool will not yet have been stored
11904: # in the user_course_parms.db file for the user's session, so in 
11905: # this case fall back to retrieving gradable status from the
11906: # exttool_$marker.db file.
11907: #
11908: # In order to avoid an infinite loop, &metadata() will return
11909: # before a call to &EXT(), if the uri is for an external tool
11910: # and the $what for which metadata is being requested is
11911: # parameter_0_gradable or 0_gradable.
11912: #
11913: 
11914:     if ($uri =~ /ext\.tool$/) {
11915:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
11916:             return;
11917:         } else {
11918:             my ($checked,$use_passback);
11919:             if ($toolsymb ne '') {
11920:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
11921:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
11922:                     $checked = 1;
11923:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
11924:                         $use_passback = 1;
11925:                     }
11926:                 }
11927:             }
11928:             unless ($checked) {
11929:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
11930:                 $marker=~s/\D//g;
11931:                 if ($marker) {
11932:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
11933:                     $use_passback = $toolsettings{'gradable'};
11934:                 }
11935:             }
11936:             if ($use_passback) {
11937:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
11938:             } else {
11939:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
11940:             }
11941:         }
11942:     }
11943: 
11944:     {
11945: # Imported parts would go here
11946:         my @origfiletagids=();
11947:         my $importedparts=0;
11948: 
11949: # Imported responseids would go here
11950:         my $importedresponses=0;
11951: #
11952: # Is this a recursive call for a library?
11953: #
11954: #	if (! exists($metacache{$uri})) {
11955: #	    $metacache{$uri}={};
11956: #	}
11957: 	my $cachetime = 60*60;
11958:         if ($liburi) {
11959: 	    $liburi=&declutter($liburi);
11960:             $filename=$liburi;
11961:         } else {
11962: 	    &devalidate_cache_new('meta',$uri);
11963: 	    undef(%metaentry);
11964: 	}
11965:         my %metathesekeys=();
11966:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11967: 	my $metastring;
11968: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11969: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11970: 	    $metastring = 
11971: 		&Apache::lonnet::ssi_body($which,
11972: 					  ('grade_target' => 'meta'));
11973: 	    $cachetime = 1; # only want this cached in the child not long term
11974: 	} elsif (($uri !~ m -^(editupload)/-) && 
11975:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11976: 	    my $file=&filelocation('',&clutter($filename));
11977: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11978: 	    $metastring=&getfile($file);
11979: 	}
11980:         my $parser=HTML::LCParser->new(\$metastring);
11981:         my $token;
11982:         undef %metathesekeys;
11983:         while ($token=$parser->get_token) {
11984: 	    if ($token->[0] eq 'S') {
11985: 		if (defined($token->[2]->{'package'})) {
11986: #
11987: # This is a package - get package info
11988: #
11989: 		    my $package=$token->[2]->{'package'};
11990: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11991: 		    if (defined($token->[2]->{'id'})) { 
11992: 			$keyroot.='_'.$token->[2]->{'id'}; 
11993: 		    }
11994: 		    if ($metaentry{':packages'}) {
11995: 			$metaentry{':packages'}.=','.$package.$keyroot;
11996: 		    } else {
11997: 			$metaentry{':packages'}=$package.$keyroot;
11998: 		    }
11999: 		    foreach my $pack_entry (keys(%packagetab)) {
12000: 			my $part=$keyroot;
12001: 			$part=~s/^\_//;
12002: 			if ($pack_entry=~/^\Q$package\E\&/ || 
12003: 			    $pack_entry=~/^\Q$package\E_0\&/) {
12004: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
12005: 			    # ignore package.tab specified default values
12006:                             # here &package_tab_default() will fetch those
12007: 			    if ($subp eq 'default') { next; }
12008: 			    my $value=$packagetab{$pack_entry};
12009: 			    my $unikey;
12010: 			    if ($pack =~ /_0$/) {
12011: 				$unikey='parameter_0_'.$name;
12012: 				$part=0;
12013: 			    } else {
12014: 				$unikey='parameter'.$keyroot.'_'.$name;
12015: 			    }
12016: 			    if ($subp eq 'display') {
12017: 				$value.=' [Part: '.$part.']';
12018: 			    }
12019: 			    $metaentry{':'.$unikey.'.part'}=$part;
12020: 			    $metathesekeys{$unikey}=1;
12021: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12022: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
12023: 			    }
12024: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
12025: 				$metaentry{':'.$unikey}=
12026: 				    $metaentry{':'.$unikey.'.default'};
12027: 			    }
12028: 			}
12029: 		    }
12030: 		} else {
12031: #
12032: # This is not a package - some other kind of start tag
12033: #
12034: 		    my $entry=$token->[1];
12035: 		    my $unikey='';
12036: 
12037: 		    if ($entry eq 'import') {
12038: #
12039: # Importing a library here
12040: #
12041:                         my $location=$parser->get_text('/import');
12042:                         my $dir=$filename;
12043:                         $dir=~s|[^/]*$||;
12044:                         $location=&filelocation($dir,$location);
12045: 
12046:                         my $importid=$token->[2]->{'id'};
12047:                         my $importmode=$token->[2]->{'importmode'};
12048: #
12049: # Check metadata for imported file to
12050: # see if it contained response items
12051: #
12052:                         my ($origfile,@libfilekeys);
12053:                         my %currmetaentry = %metaentry;
12054:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12055:                                                            $depthcount+1));
12056:                         if (grep(/^responseorder$/,@libfilekeys)) {
12057:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12058:                                                              undef,$depthcount+1);
12059:                             if ($libresponseorder ne '') {
12060:                                 if ($#origfiletagids<0) {
12061:                                     undef(%importedrespids);
12062:                                     undef(%importedpartids);
12063:                                 }
12064:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
12065:                                 if (@respids) {
12066:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12067:                                 }
12068:                                 if ($importedrespids{$importid} ne '') {
12069:                                     $importedresponses = 1;
12070: # We need to get the original file and the imported file to get the response order correct
12071: # Load and inspect original file
12072:                                     if ($#origfiletagids<0) {
12073:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12074:                                         $origfile=&getfile($origfilelocation);
12075:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12076:                                     }
12077:                                 }
12078:                             }
12079:                         }
12080: # Do not overwrite contents of %metaentry hash for resource itself with 
12081: # hash populated for imported library file
12082:                         %metaentry = %currmetaentry;
12083:                         undef(%currmetaentry);
12084:                         if ($importmode eq 'part') {
12085: # Import as part(s)
12086:                            $importedparts=1;
12087: # We need to get the original file and the imported file to get the part order correct
12088: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
12089: # Load and inspect original file if we didn't do that already
12090:                            if ($#origfiletagids<0) {
12091:                                undef(%importedrespids);
12092:                                undef(%importedpartids);
12093:                                if ($origfile eq '') {
12094:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12095:                                    $origfile=&getfile($origfilelocation);
12096:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12097:                                }
12098:                            }
12099:                            my @impfilepartids;
12100: # If <partorder> tag is included in metadata for the imported file
12101: # get the parts in the imported file from that.
12102:                            if (grep(/^partorder$/,@libfilekeys)) {
12103:                                %currmetaentry = %metaentry;
12104:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12105:                                                             $depthcount+1);
12106:                                %metaentry = %currmetaentry;
12107:                                undef(%currmetaentry);
12108:                                if ($libpartorder ne '') {
12109:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
12110:                                }
12111:                            } else {
12112: # If no <partorder> tag available, load and inspect imported file
12113:                                my $impfile=&getfile($location);
12114:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12115:                            }
12116:                            if ($#impfilepartids>=0) {
12117: # This problem had parts
12118:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
12119:                            } else {
12120: # Importing by turning a single problem into a problem part
12121: # It gets the import-tags ID as part-ID
12122:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
12123:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
12124:                            }
12125:                         } else {
12126: # Import as problem or as normal import
12127:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12128:                             unless ($importmode eq 'problem') {
12129: # Normal import
12130:                                 if (defined($token->[2]->{'id'})) {
12131:                                     $unikey.='_'.$token->[2]->{'id'};
12132:                                 }
12133:                             }
12134: # Check metadata for imported file to
12135: # see if it contained parts
12136:                             if (grep(/^partorder$/,@libfilekeys)) {
12137:                                 %currmetaentry = %metaentry;
12138:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12139:                                                              $depthcount+1);
12140:                                 %metaentry = %currmetaentry;
12141:                                 undef(%currmetaentry);
12142:                                 if ($libpartorder ne '') {
12143:                                     $importedparts = 1;
12144:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12145:                                 }
12146:                             }
12147:                         }
12148: 			if ($depthcount<20) {
12149: 			    my $metadata = 
12150: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
12151: 					  $depthcount+1);
12152: 			    foreach my $meta (split(',',$metadata)) {
12153: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12154: 				$metathesekeys{$meta}=1;
12155: 			    }
12156:                         }
12157: 		    } else {
12158: #
12159: # Not importing, some other kind of non-package, non-library start tag
12160: # 
12161:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12162:                         if (defined($token->[2]->{'id'})) {
12163:                             $unikey.='_'.$token->[2]->{'id'};
12164:                         }
12165: 			if (defined($token->[2]->{'name'})) { 
12166: 			    $unikey.='_'.$token->[2]->{'name'}; 
12167: 			}
12168: 			$metathesekeys{$unikey}=1;
12169: 			foreach my $param (@{$token->[3]}) {
12170: 			    $metaentry{':'.$unikey.'.'.$param} =
12171: 				$token->[2]->{$param};
12172: 			}
12173: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12174: 			my $default=$metaentry{':'.$unikey.'.default'};
12175: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12176: 		 # only ws inside the tag, and not in default, so use default
12177: 		 # as value
12178: 			    $metaentry{':'.$unikey}=$default;
12179: 			} elsif ( $internaltext =~ /\S/ ) {
12180: 		  # something interesting inside the tag
12181: 			    $metaentry{':'.$unikey}=$internaltext;
12182: 			} else {
12183: 		  # no interesting values, don't set a default
12184: 			}
12185: # end of not-a-package not-a-library import
12186: 		    }
12187: # end of not-a-package start tag
12188: 		}
12189: # the next is the end of "start tag"
12190: 	    }
12191: 	}
12192: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12193: 	$extension = lc($extension);
12194: 	if ($extension eq 'htm') { $extension='html'; }
12195: 
12196: 	foreach my $key (keys(%packagetab)) {
12197: 	    #no specific packages #how's our extension
12198: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12199: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12200: 					 \%metathesekeys);
12201: 	}
12202: 
12203: 	if (!exists($metaentry{':packages'})
12204: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12205: 	    foreach my $key (keys(%packagetab)) {
12206: 		#no specific packages well let's get default then
12207: 		if ($key!~/^default&/) { next; }
12208: 		&metadata_create_package_def($uri,$key,'default',
12209: 					     \%metathesekeys);
12210: 	    }
12211: 	}
12212: # are there custom rights to evaluate
12213: 	if ($metaentry{':copyright'} eq 'custom') {
12214: 
12215:     #
12216:     # Importing a rights file here
12217:     #
12218: 	    unless ($depthcount) {
12219: 		my $location=$metaentry{':customdistributionfile'};
12220: 		my $dir=$filename;
12221: 		$dir=~s|[^/]*$||;
12222: 		$location=&filelocation($dir,$location);
12223: 		my $rights_metadata =
12224: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
12225: 			      $depthcount+1);
12226: 		foreach my $rights (split(',',$rights_metadata)) {
12227: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12228: 		    $metathesekeys{$rights}=1;
12229: 		}
12230: 	    }
12231: 	}
12232: 	# uniqifiy package listing
12233: 	my %seen;
12234: 	my @uniq_packages =
12235: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12236: 	$metaentry{':packages'} = join(',',@uniq_packages);
12237: 
12238:         if (($importedresponses) || ($importedparts)) {
12239:             if ($importedparts) {
12240: # We had imported parts and need to rebuild partorder
12241:                 $metaentry{':partorder'}='';
12242:                 $metathesekeys{'partorder'}=1;
12243:             }
12244:             if ($importedresponses) {
12245: # We had imported responses and need to rebuil responseorder
12246:                 $metaentry{':responseorder'}='';
12247:                 $metathesekeys{'responseorder'}=1;
12248:             }
12249:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12250:                 my $origid = $origfiletagids[$index+1];
12251:                 if ($origfiletagids[$index] eq 'part') {
12252: # Original part, part of the problem
12253:                     if ($importedparts) {
12254:                         $metaentry{':partorder'}.=','.$origid;
12255:                     }
12256:                 } elsif ($origfiletagids[$index] eq 'import') {
12257:                     if ($importedparts) {
12258: # We have imported parts at this position
12259:                         if ($importedpartids{$origid} ne '') {
12260:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
12261:                         }
12262:                     }
12263:                     if ($importedresponses) {
12264: # We have imported responses at this position
12265:                         if ($importedrespids{$origid} ne '') {
12266:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
12267:                         }
12268:                     }
12269:                 } else {
12270: # Original response item, part of the problem
12271:                     if ($importedresponses) {
12272:                         $metaentry{':responseorder'}.=','.$origid;
12273:                     }
12274:                 }
12275:             }
12276:             if ($importedparts) {
12277:                 $metaentry{':partorder'}=~s/^\,//;
12278:             }
12279:             if ($importedresponses) {
12280:                 $metaentry{':responseorder'}=~s/^\,//;
12281:             }
12282:         }
12283: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12284: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12285: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12286:         unless ($liburi) {
12287: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12288:         }
12289: # this is the end of "was not already recently cached
12290:     }
12291:     return $metaentry{':'.$what};
12292: }
12293: 
12294: sub metadata_create_package_def {
12295:     my ($uri,$key,$package,$metathesekeys)=@_;
12296:     my ($pack,$name,$subp)=split(/\&/,$key);
12297:     if ($subp eq 'default') { next; }
12298:     
12299:     if (defined($metaentry{':packages'})) {
12300: 	$metaentry{':packages'}.=','.$package;
12301:     } else {
12302: 	$metaentry{':packages'}=$package;
12303:     }
12304:     my $value=$packagetab{$key};
12305:     my $unikey;
12306:     $unikey='parameter_0_'.$name;
12307:     $metaentry{':'.$unikey.'.part'}=0;
12308:     $$metathesekeys{$unikey}=1;
12309:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12310: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12311:     }
12312:     if (defined($metaentry{':'.$unikey.'.default'})) {
12313: 	$metaentry{':'.$unikey}=
12314: 	    $metaentry{':'.$unikey.'.default'};
12315:     }
12316: }
12317: 
12318: sub metadata_generate_part0 {
12319:     my ($metadata,$metacache,$uri) = @_;
12320:     my %allnames;
12321:     foreach my $metakey (keys(%$metadata)) {
12322: 	if ($metakey=~/^parameter\_(.*)/) {
12323: 	  my $part=$$metacache{':'.$metakey.'.part'};
12324: 	  my $name=$$metacache{':'.$metakey.'.name'};
12325: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12326: 	    $allnames{$name}=$part;
12327: 	  }
12328: 	}
12329:     }
12330:     foreach my $name (keys(%allnames)) {
12331:       $$metadata{"parameter_0_$name"}=1;
12332:       my $key=":parameter_0_$name";
12333:       $$metacache{"$key.part"}='0';
12334:       $$metacache{"$key.name"}=$name;
12335:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12336: 					   $allnames{$name}.'_'.$name.
12337: 					   '.type'};
12338:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12339: 			     '.display'};
12340:       my $expr='[Part: '.$allnames{$name}.']';
12341:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12342:       $$metacache{"$key.display"}=$olddis;
12343:     }
12344: }
12345: 
12346: # ------------------------------------------------------ Devalidate title cache
12347: 
12348: sub devalidate_title_cache {
12349:     my ($url)=@_;
12350:     if (!$env{'request.course.id'}) { return; }
12351:     my $symb=&symbread($url);
12352:     if (!$symb) { return; }
12353:     my $key=$env{'request.course.id'}."\0".$symb;
12354:     &devalidate_cache_new('title',$key);
12355: }
12356: 
12357: # ------------------------------------------------- Get the title of a course
12358: 
12359: sub current_course_title {
12360:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12361: }
12362: # ------------------------------------------------- Get the title of a resource
12363: 
12364: sub gettitle {
12365:     my $urlsymb=shift;
12366:     my $symb=&symbread($urlsymb);
12367:     if ($symb) {
12368: 	my $key=$env{'request.course.id'}."\0".$symb;
12369: 	my ($result,$cached)=&is_cached_new('title',$key);
12370: 	if (defined($cached)) { 
12371: 	    return $result;
12372: 	}
12373: 	my ($map,$resid,$url)=&decode_symb($symb);
12374: 	my $title='';
12375: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12376: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12377: 	} else {
12378: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12379: 		    &GDBM_READER(),0640)) {
12380: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12381: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12382: 		untie(%bighash);
12383: 	    }
12384: 	}
12385: 	$title=~s/\&colon\;/\:/gs;
12386: 	if ($title) {
12387: # Remember both $symb and $title for dynamic metadata
12388:             $accesshash{$symb.'___crstitle'}=$title;
12389:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12390: # Cache this title and then return it
12391: 	    return &do_cache_new('title',$key,$title,600);
12392: 	}
12393: 	$urlsymb=$url;
12394:     }
12395:     my $title=&metadata($urlsymb,'title');
12396:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12397:     return $title;
12398: }
12399: 
12400: sub get_slot {
12401:     my ($which,$cnum,$cdom)=@_;
12402:     if (!$cnum || !$cdom) {
12403: 	(undef,my $courseid)=&whichuser();
12404: 	$cdom=$env{'course.'.$courseid.'.domain'};
12405: 	$cnum=$env{'course.'.$courseid.'.num'};
12406:     }
12407:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12408:     my %slotinfo;
12409:     if (exists($remembered{$key})) {
12410: 	$slotinfo{$which} = $remembered{$key};
12411:     } else {
12412: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12413: 	&Apache::lonhomework::showhash(%slotinfo);
12414: 	my ($tmp)=keys(%slotinfo);
12415: 	if ($tmp=~/^error:/) { return (); }
12416: 	$remembered{$key} = $slotinfo{$which};
12417:     }
12418:     if (ref($slotinfo{$which}) eq 'HASH') {
12419: 	return %{$slotinfo{$which}};
12420:     }
12421:     return $slotinfo{$which};
12422: }
12423: 
12424: sub get_reservable_slots {
12425:     my ($cnum,$cdom,$uname,$udom) = @_;
12426:     my $now = time;
12427:     my $reservable_info;
12428:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12429:     if (exists($remembered{$key})) {
12430:         $reservable_info = $remembered{$key};
12431:     } else {
12432:         my %resv;
12433:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12434:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12435:         $reservable_info = \%resv;
12436:         $remembered{$key} = $reservable_info;
12437:     }
12438:     return $reservable_info;
12439: }
12440: 
12441: sub get_course_slots {
12442:     my ($cnum,$cdom) = @_;
12443:     my $hashid=$cnum.':'.$cdom;
12444:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12445:     if (defined($cached)) {
12446:         if (ref($result) eq 'HASH') {
12447:             return %{$result};
12448:         }
12449:     } else {
12450:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12451:         my ($tmp) = keys(%slots);
12452:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12453:             &do_cache_new('allslots',$hashid,\%slots,600);
12454:             return %slots;
12455:         }
12456:     }
12457:     return;
12458: }
12459: 
12460: sub devalidate_slots_cache {
12461:     my ($cnum,$cdom)=@_;
12462:     my $hashid=$cnum.':'.$cdom;
12463:     &devalidate_cache_new('allslots',$hashid);
12464: }
12465: 
12466: sub get_coursechange {
12467:     my ($cdom,$cnum) = @_;
12468:     if ($cdom eq '' || $cnum eq '') {
12469:         return unless ($env{'request.course.id'});
12470:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12471:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12472:     }
12473:     my $hashid=$cdom.'_'.$cnum;
12474:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12475:     if ((defined($cached)) && ($change ne '')) {
12476:         return $change;
12477:     } else {
12478:         my %crshash;
12479:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12480:         if ($crshash{'internal.contentchange'} eq '') {
12481:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12482:             if ($change eq '') {
12483:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12484:                 $change = $crshash{'internal.created'};
12485:             }
12486:         } else {
12487:             $change = $crshash{'internal.contentchange'};
12488:         }
12489:         my $cachetime = 600;
12490:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12491:     }
12492:     return $change;
12493: }
12494: 
12495: sub devalidate_coursechange_cache {
12496:     my ($cnum,$cdom)=@_;
12497:     my $hashid=$cnum.':'.$cdom;
12498:     &devalidate_cache_new('crschange',$hashid);
12499: }
12500: 
12501: # ------------------------------------------------- Update symbolic store links
12502: 
12503: sub symblist {
12504:     my ($mapname,%newhash)=@_;
12505:     $mapname=&deversion(&declutter($mapname));
12506:     my %hash;
12507:     if (($env{'request.course.fn'}) && (%newhash)) {
12508:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12509:                       &GDBM_WRCREAT(),0640)) {
12510: 	    foreach my $url (keys(%newhash)) {
12511: 		next if ($url eq 'last_known'
12512: 			 && $env{'form.no_update_last_known'});
12513: 		$hash{declutter($url)}=&encode_symb($mapname,
12514: 						    $newhash{$url}->[1],
12515: 						    $newhash{$url}->[0]);
12516:             }
12517:             if (untie(%hash)) {
12518: 		return 'ok';
12519:             }
12520:         }
12521:     }
12522:     return 'error';
12523: }
12524: 
12525: # --------------------------------------------------------------- Verify a symb
12526: 
12527: sub symbverify {
12528:     my ($symb,$thisurl,$encstate)=@_;
12529:     my $thisfn=$thisurl;
12530:     $thisfn=&declutter($thisfn);
12531: # direct jump to resource in page or to a sequence - will construct own symbs
12532:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12533: # check URL part
12534:     my ($map,$resid,$url)=&decode_symb($symb);
12535: 
12536:     unless ($url eq $thisfn) { return 0; }
12537: 
12538:     $symb=&symbclean($symb);
12539:     $thisurl=&deversion($thisurl);
12540:     $thisfn=&deversion($thisfn);
12541: 
12542:     my %bighash;
12543:     my $okay=0;
12544: 
12545:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12546:                             &GDBM_READER(),0640)) {
12547:         my $noclutter;
12548:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12549:             $thisurl =~ s/\?.+$//;
12550:             if ($map =~ m{^uploaded/.+\.page$}) {
12551:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12552:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12553:                 $noclutter = 1;
12554:             }
12555:         }
12556:         my $ids;
12557:         if ($noclutter) {
12558:             $ids=$bighash{'ids_'.$thisurl};
12559:         } else {
12560:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12561:         }
12562:         unless ($ids) {
12563:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12564:             $ids=$bighash{$idkey};
12565:         }
12566:         if ($ids) {
12567: # ------------------------------------------------------------------- Has ID(s)
12568:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12569:                 $symb =~ s/\?.+$//;
12570:             }
12571: 	    foreach my $id (split(/\,/,$ids)) {
12572: 	       my ($mapid,$resid)=split(/\./,$id);
12573:                if (
12574:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12575:    eq $symb) {
12576:                    if (ref($encstate)) {
12577:                        $$encstate = $bighash{'encrypted_'.$id};
12578:                    }
12579: 		   if (($env{'request.role.adv'}) ||
12580: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12581:                        ($thisurl eq '/adm/navmaps')) {
12582: 		       $okay=1;
12583:                        last;
12584: 		   }
12585: 	       }
12586: 	   }
12587:         }
12588: 	untie(%bighash);
12589:     }
12590:     return $okay;
12591: }
12592: 
12593: # --------------------------------------------------------------- Clean-up symb
12594: 
12595: sub symbclean {
12596:     my $symb=shift;
12597:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12598: # remove version from map
12599:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12600: 
12601: # remove version from URL
12602:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12603: 
12604: # remove wrapper
12605: 
12606:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12607:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12608:     return $symb;
12609: }
12610: 
12611: # ---------------------------------------------- Split symb to find map and url
12612: 
12613: sub encode_symb {
12614:     my ($map,$resid,$url)=@_;
12615:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12616: }
12617: 
12618: sub decode_symb {
12619:     my $symb=shift;
12620:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12621:     my ($map,$resid,$url)=split(/___/,$symb);
12622:     return (&fixversion($map),$resid,&fixversion($url));
12623: }
12624: 
12625: sub fixversion {
12626:     my $fn=shift;
12627:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12628:     my %bighash;
12629:     my $uri=&clutter($fn);
12630:     my $key=$env{'request.course.id'}.'_'.$uri;
12631: # is this cached?
12632:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12633:     if (defined($cached)) { return $result; }
12634: # unfortunately not cached, or expired
12635:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12636: 	    &GDBM_READER(),0640)) {
12637:  	if ($bighash{'version_'.$uri}) {
12638:  	    my $version=$bighash{'version_'.$uri};
12639:  	    unless (($version eq 'mostrecent') || 
12640: 		    ($version==&getversion($uri))) {
12641:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12642:  	    }
12643:  	}
12644:  	untie %bighash;
12645:     }
12646:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12647: }
12648: 
12649: sub deversion {
12650:     my $url=shift;
12651:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12652:     return $url;
12653: }
12654: 
12655: # ------------------------------------------------------ Return symb list entry
12656: 
12657: sub symbread {
12658:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12659:     my $cache_str='request.symbread.cached.'.$thisfn;
12660:     if (defined($env{$cache_str})) {
12661:         if ($ignorecachednull) {
12662:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12663:         } else {
12664:             return $env{$cache_str};
12665:         }
12666:     }
12667: # no filename provided? try from environment
12668:     unless ($thisfn) {
12669:         if ($env{'request.symb'}) {
12670: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12671: 	}
12672: 	$thisfn=$env{'request.filename'};
12673:     }
12674:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12675: # is that filename actually a symb? Verify, clean, and return
12676:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12677: 	if (&symbverify($thisfn,$1)) {
12678: 	    return $env{$cache_str}=&symbclean($thisfn);
12679: 	}
12680:     }
12681:     $thisfn=declutter($thisfn);
12682:     my %hash;
12683:     my %bighash;
12684:     my $syval='';
12685:     if (($env{'request.course.fn'}) && ($thisfn)) {
12686:         my $targetfn = $thisfn;
12687:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12688:             $targetfn = 'adm/wrapper/'.$thisfn;
12689:         }
12690: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12691: 	    $targetfn=$1;
12692: 	}
12693:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12694:                       &GDBM_READER(),0640)) {
12695: 	    $syval=$hash{$targetfn};
12696:             untie(%hash);
12697:         }
12698: # ---------------------------------------------------------- There was an entry
12699:         if ($syval) {
12700: 	    #unless ($syval=~/\_\d+$/) {
12701: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12702: 		    #&appenv({'request.ambiguous' => $thisfn});
12703: 		    #return $env{$cache_str}='';
12704: 		#}    
12705: 		#$syval.=$1;
12706: 	    #}
12707:         } else {
12708: # ------------------------------------------------------- Was not in symb table
12709:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12710:                             &GDBM_READER(),0640)) {
12711: # ---------------------------------------------- Get ID(s) for current resource
12712:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12713:               unless ($ids) { 
12714:                  $ids=$bighash{'ids_/'.$thisfn};
12715:               }
12716:               unless ($ids) {
12717: # alias?
12718: 		  $ids=$bighash{'mapalias_'.$thisfn};
12719:               }
12720:               if ($ids) {
12721: # ------------------------------------------------------------------- Has ID(s)
12722:                  my @possibilities=split(/\,/,$ids);
12723:                  if ($#possibilities==0) {
12724: # ----------------------------------------------- There is only one possibility
12725: 		     my ($mapid,$resid)=split(/\./,$ids);
12726: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12727: 						    $resid,$thisfn);
12728:                      if (ref($possibles) eq 'HASH') {
12729:                          $possibles->{$syval} = 1;    
12730:                      }
12731:                      if ($checkforblock) {
12732:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12733:                          if (@blockers) {
12734:                              $syval = '';
12735:                              return;
12736:                          }
12737:                      }
12738:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12739: # ------------------------------------------ There is more than one possibility
12740:                      my $realpossible=0;
12741:                      foreach my $id (@possibilities) {
12742: 			 my $file=$bighash{'src_'.$id};
12743:                          my $canaccess;
12744:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12745:                              $canaccess = 1;
12746:                          } else { 
12747:                              $canaccess = &allowed('bre',$file);
12748:                          }
12749:                          if ($canaccess) {
12750:          		     my ($mapid,$resid)=split(/\./,$id);
12751:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12752:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12753: 						             $resid,$thisfn);
12754:                                  if (ref($possibles) eq 'HASH') {
12755:                                      $possibles->{$syval} = 1;
12756:                                  }
12757:                                  if ($checkforblock) {
12758:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12759:                                      unless (@blockers > 0) {
12760:                                          $syval = $poss_syval;
12761:                                          $realpossible++;
12762:                                      }
12763:                                  } else {
12764:                                      $syval = $poss_syval;
12765:                                      $realpossible++;
12766:                                  }
12767:                              }
12768: 			 }
12769:                      }
12770: 		     if ($realpossible!=1) { $syval=''; }
12771:                  } else {
12772:                      $syval='';
12773:                  }
12774: 	      }
12775:               untie(%bighash);
12776:            }
12777:         }
12778:         if ($syval) {
12779: 	    return $env{$cache_str}=$syval;
12780:         }
12781:     }
12782:     &appenv({'request.ambiguous' => $thisfn});
12783:     return $env{$cache_str}='';
12784: }
12785: 
12786: # ---------------------------------------------------------- Return random seed
12787: 
12788: sub numval {
12789:     my $txt=shift;
12790:     $txt=~tr/A-J/0-9/;
12791:     $txt=~tr/a-j/0-9/;
12792:     $txt=~tr/K-T/0-9/;
12793:     $txt=~tr/k-t/0-9/;
12794:     $txt=~tr/U-Z/0-5/;
12795:     $txt=~tr/u-z/0-5/;
12796:     $txt=~s/\D//g;
12797:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12798:     return int($txt);
12799: }
12800: 
12801: sub numval2 {
12802:     my $txt=shift;
12803:     $txt=~tr/A-J/0-9/;
12804:     $txt=~tr/a-j/0-9/;
12805:     $txt=~tr/K-T/0-9/;
12806:     $txt=~tr/k-t/0-9/;
12807:     $txt=~tr/U-Z/0-5/;
12808:     $txt=~tr/u-z/0-5/;
12809:     $txt=~s/\D//g;
12810:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12811:     my $total;
12812:     foreach my $val (@txts) { $total+=$val; }
12813:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12814:     return int($total);
12815: }
12816: 
12817: sub numval3 {
12818:     use integer;
12819:     my $txt=shift;
12820:     $txt=~tr/A-J/0-9/;
12821:     $txt=~tr/a-j/0-9/;
12822:     $txt=~tr/K-T/0-9/;
12823:     $txt=~tr/k-t/0-9/;
12824:     $txt=~tr/U-Z/0-5/;
12825:     $txt=~tr/u-z/0-5/;
12826:     $txt=~s/\D//g;
12827:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12828:     my $total;
12829:     foreach my $val (@txts) { $total+=$val; }
12830:     if ($_64bit) { $total=(($total<<32)>>32); }
12831:     return $total;
12832: }
12833: 
12834: sub digest {
12835:     my ($data)=@_;
12836:     my $digest=&Digest::MD5::md5($data);
12837:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12838:     my ($e,$f);
12839:     {
12840:         use integer;
12841:         $e=($a+$b);
12842:         $f=($c+$d);
12843:         if ($_64bit) {
12844:             $e=(($e<<32)>>32);
12845:             $f=(($f<<32)>>32);
12846:         }
12847:     }
12848:     if (wantarray) {
12849: 	return ($e,$f);
12850:     } else {
12851: 	my $g;
12852: 	{
12853: 	    use integer;
12854: 	    $g=($e+$f);
12855: 	    if ($_64bit) {
12856: 		$g=(($g<<32)>>32);
12857: 	    }
12858: 	}
12859: 	return $g;
12860:     }
12861: }
12862: 
12863: sub latest_rnd_algorithm_id {
12864:     return '64bit5';
12865: }
12866: 
12867: sub get_rand_alg {
12868:     my ($courseid)=@_;
12869:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12870:     if ($courseid) {
12871: 	return $env{"course.$courseid.rndseed"};
12872:     }
12873:     return &latest_rnd_algorithm_id();
12874: }
12875: 
12876: sub validCODE {
12877:     my ($CODE)=@_;
12878:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12879:     return 0;
12880: }
12881: 
12882: sub getCODE {
12883:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12884:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12885: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12886: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12887: 	return $Apache::lonhomework::history{'resource.CODE'};
12888:     }
12889:     return undef;
12890: }
12891: #
12892: #  Determines the random seed for a specific context:
12893: #
12894: # parameters:
12895: #   symb      - in course context the symb for the seed.
12896: #   course_id - The course id of the form domain_coursenum.
12897: #   domain    - Domain for the user.
12898: #   course    - Course for the user.
12899: #   cenv      - environment of the course.
12900: #
12901: # NOTE:
12902: #   All parameters are picked out of the environment if missing
12903: #   or not defined.
12904: #   If a symb cannot be determined the current time is used instead.
12905: #
12906: #  For a given well defined symb, courside, domain, username,
12907: #  and course environment, the seed is reproducible.
12908: #
12909: sub rndseed {
12910:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12911:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12912:     if (!defined($symb)) {
12913: 	unless ($symb=$wsymb) { return time; }
12914:     }
12915:     if (!defined $courseid) { 
12916: 	$courseid=$wcourseid; 
12917:     }
12918:     if (!defined $domain) { $domain=$wdomain; }
12919:     if (!defined $username) { $username=$wusername }
12920: 
12921:     my $which;
12922:     if (defined($cenv->{'rndseed'})) {
12923: 	$which = $cenv->{'rndseed'};
12924:     } else {
12925: 	$which =&get_rand_alg($courseid);
12926:     }
12927:     if (defined(&getCODE())) {
12928: 
12929: 	if ($which eq '64bit5') {
12930: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12931: 	} elsif ($which eq '64bit4') {
12932: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12933: 	} else {
12934: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12935: 	}
12936:     } elsif ($which eq '64bit5') {
12937: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12938:     } elsif ($which eq '64bit4') {
12939: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12940:     } elsif ($which eq '64bit3') {
12941: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12942:     } elsif ($which eq '64bit2') {
12943: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12944:     } elsif ($which eq '64bit') {
12945: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12946:     }
12947:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12948: }
12949: 
12950: sub rndseed_32bit {
12951:     my ($symb,$courseid,$domain,$username)=@_;
12952:     {
12953: 	use integer;
12954: 	my $symbchck=unpack("%32C*",$symb) << 27;
12955: 	my $symbseed=numval($symb) << 22;
12956: 	my $namechck=unpack("%32C*",$username) << 17;
12957: 	my $nameseed=numval($username) << 12;
12958: 	my $domainseed=unpack("%32C*",$domain) << 7;
12959: 	my $courseseed=unpack("%32C*",$courseid);
12960: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12961: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12962: 	#&logthis("rndseed :$num:$symb");
12963: 	if ($_64bit) { $num=(($num<<32)>>32); }
12964: 	return $num;
12965:     }
12966: }
12967: 
12968: sub rndseed_64bit {
12969:     my ($symb,$courseid,$domain,$username)=@_;
12970:     {
12971: 	use integer;
12972: 	my $symbchck=unpack("%32S*",$symb) << 21;
12973: 	my $symbseed=numval($symb) << 10;
12974: 	my $namechck=unpack("%32S*",$username);
12975: 	
12976: 	my $nameseed=numval($username) << 21;
12977: 	my $domainseed=unpack("%32S*",$domain) << 10;
12978: 	my $courseseed=unpack("%32S*",$courseid);
12979: 	
12980: 	my $num1=$symbchck+$symbseed+$namechck;
12981: 	my $num2=$nameseed+$domainseed+$courseseed;
12982: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12983: 	#&logthis("rndseed :$num:$symb");
12984: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12985: 	return "$num1,$num2";
12986:     }
12987: }
12988: 
12989: sub rndseed_64bit2 {
12990:     my ($symb,$courseid,$domain,$username)=@_;
12991:     {
12992: 	use integer;
12993: 	# strings need to be an even # of cahracters long, it it is odd the
12994:         # last characters gets thrown away
12995: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12996: 	my $symbseed=numval($symb) << 10;
12997: 	my $namechck=unpack("%32S*",$username.' ');
12998: 	
12999: 	my $nameseed=numval($username) << 21;
13000: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13001: 	my $courseseed=unpack("%32S*",$courseid.' ');
13002: 	
13003: 	my $num1=$symbchck+$symbseed+$namechck;
13004: 	my $num2=$nameseed+$domainseed+$courseseed;
13005: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13006: 	#&logthis("rndseed :$num:$symb");
13007: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13008: 	return "$num1,$num2";
13009:     }
13010: }
13011: 
13012: sub rndseed_64bit3 {
13013:     my ($symb,$courseid,$domain,$username)=@_;
13014:     {
13015: 	use integer;
13016: 	# strings need to be an even # of cahracters long, it it is odd the
13017:         # last characters gets thrown away
13018: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13019: 	my $symbseed=numval2($symb) << 10;
13020: 	my $namechck=unpack("%32S*",$username.' ');
13021: 	
13022: 	my $nameseed=numval2($username) << 21;
13023: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13024: 	my $courseseed=unpack("%32S*",$courseid.' ');
13025: 	
13026: 	my $num1=$symbchck+$symbseed+$namechck;
13027: 	my $num2=$nameseed+$domainseed+$courseseed;
13028: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13029: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13030: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13031: 	
13032: 	return "$num1:$num2";
13033:     }
13034: }
13035: 
13036: sub rndseed_64bit4 {
13037:     my ($symb,$courseid,$domain,$username)=@_;
13038:     {
13039: 	use integer;
13040: 	# strings need to be an even # of cahracters long, it it is odd the
13041:         # last characters gets thrown away
13042: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
13043: 	my $symbseed=numval3($symb) << 10;
13044: 	my $namechck=unpack("%32S*",$username.' ');
13045: 	
13046: 	my $nameseed=numval3($username) << 21;
13047: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
13048: 	my $courseseed=unpack("%32S*",$courseid.' ');
13049: 	
13050: 	my $num1=$symbchck+$symbseed+$namechck;
13051: 	my $num2=$nameseed+$domainseed+$courseseed;
13052: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13053: 	#&logthis("rndseed :$num1:$num2:$_64bit");
13054: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
13055: 	
13056: 	return "$num1:$num2";
13057:     }
13058: }
13059: 
13060: sub rndseed_64bit5 {
13061:     my ($symb,$courseid,$domain,$username)=@_;
13062:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13063:     return "$num1:$num2";
13064: }
13065: 
13066: sub rndseed_CODE_64bit {
13067:     my ($symb,$courseid,$domain,$username)=@_;
13068:     {
13069: 	use integer;
13070: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13071: 	my $symbseed=numval2($symb);
13072: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13073: 	my $CODEseed=numval(&getCODE());
13074: 	my $courseseed=unpack("%32S*",$courseid.' ');
13075: 	my $num1=$symbseed+$CODEchck;
13076: 	my $num2=$CODEseed+$courseseed+$symbchck;
13077: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13078: 	#&logthis("rndseed :$num1:$num2:$symb");
13079: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13080: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13081: 	return "$num1:$num2";
13082:     }
13083: }
13084: 
13085: sub rndseed_CODE_64bit4 {
13086:     my ($symb,$courseid,$domain,$username)=@_;
13087:     {
13088: 	use integer;
13089: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
13090: 	my $symbseed=numval3($symb);
13091: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13092: 	my $CODEseed=numval3(&getCODE());
13093: 	my $courseseed=unpack("%32S*",$courseid.' ');
13094: 	my $num1=$symbseed+$CODEchck;
13095: 	my $num2=$CODEseed+$courseseed+$symbchck;
13096: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13097: 	#&logthis("rndseed :$num1:$num2:$symb");
13098: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
13099: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
13100: 	return "$num1:$num2";
13101:     }
13102: }
13103: 
13104: sub rndseed_CODE_64bit5 {
13105:     my ($symb,$courseid,$domain,$username)=@_;
13106:     my $code = &getCODE();
13107:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
13108:     return "$num1:$num2";
13109: }
13110: 
13111: sub setup_random_from_rndseed {
13112:     my ($rndseed)=@_;
13113:     if ($rndseed =~/([,:])/) {
13114:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13115:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13116:             &Math::Random::random_set_seed_from_phrase($rndseed);
13117:         } else {
13118:             &Math::Random::random_set_seed($num1,$num2);
13119:         }
13120:     } else {
13121: 	&Math::Random::random_set_seed_from_phrase($rndseed);
13122:     }
13123: }
13124: 
13125: sub latest_receipt_algorithm_id {
13126:     return 'receipt3';
13127: }
13128: 
13129: sub recunique {
13130:     my $fucourseid=shift;
13131:     my $unique;
13132:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13133: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13134: 	$unique=$env{"course.$fucourseid.internal.encseed"};
13135:     } else {
13136: 	$unique=$perlvar{'lonReceipt'};
13137:     }
13138:     return unpack("%32C*",$unique);
13139: }
13140: 
13141: sub recprefix {
13142:     my $fucourseid=shift;
13143:     my $prefix;
13144:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13145: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13146: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13147:     } else {
13148: 	$prefix=$perlvar{'lonHostID'};
13149:     }
13150:     return unpack("%32C*",$prefix);
13151: }
13152: 
13153: sub ireceipt {
13154:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13155: 
13156:     my $return =&recprefix($fucourseid).'-';
13157: 
13158:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13159: 	$env{'request.state'} eq 'construct') {
13160: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13161: 	return $return;
13162:     }
13163: 
13164:     my $cuname=unpack("%32C*",$funame);
13165:     my $cudom=unpack("%32C*",$fudom);
13166:     my $cucourseid=unpack("%32C*",$fucourseid);
13167:     my $cusymb=unpack("%32C*",$fusymb);
13168:     my $cunique=&recunique($fucourseid);
13169:     my $cpart=unpack("%32S*",$part);
13170:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13171: 
13172: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13173: 			       
13174: 	$return.= ($cunique%$cuname+
13175: 		   $cunique%$cudom+
13176: 		   $cusymb%$cuname+
13177: 		   $cusymb%$cudom+
13178: 		   $cucourseid%$cuname+
13179: 		   $cucourseid%$cudom+
13180: 		   $cpart%$cuname+
13181: 		   $cpart%$cudom);
13182:     } else {
13183: 	$return.= ($cunique%$cuname+
13184: 		   $cunique%$cudom+
13185: 		   $cusymb%$cuname+
13186: 		   $cusymb%$cudom+
13187: 		   $cucourseid%$cuname+
13188: 		   $cucourseid%$cudom);
13189:     }
13190:     return $return;
13191: }
13192: 
13193: sub receipt {
13194:     my ($part)=@_;
13195:     my ($symb,$courseid,$domain,$name) = &whichuser();
13196:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13197: }
13198: 
13199: sub whichuser {
13200:     my ($passedsymb)=@_;
13201:     my ($symb,$courseid,$domain,$name,$publicuser);
13202:     if (defined($env{'form.grade_symb'})) {
13203: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13204: 	my $allowed=&allowed('vgr',$tmp_courseid);
13205: 	if (!$allowed &&
13206: 	    exists($env{'request.course.sec'}) &&
13207: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13208: 	    $allowed=&allowed('vgr',$tmp_courseid.
13209: 			      '/'.$env{'request.course.sec'});
13210: 	}
13211: 	if ($allowed) {
13212: 	    ($symb)=&get_env_multiple('form.grade_symb');
13213: 	    $courseid=$tmp_courseid;
13214: 	    ($domain)=&get_env_multiple('form.grade_domain');
13215: 	    ($name)=&get_env_multiple('form.grade_username');
13216: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13217: 	}
13218:     }
13219:     if (!$passedsymb) {
13220: 	$symb=&symbread();
13221:     } else {
13222: 	$symb=$passedsymb;
13223:     }
13224:     $courseid=$env{'request.course.id'};
13225:     $domain=$env{'user.domain'};
13226:     $name=$env{'user.name'};
13227:     if ($name eq 'public' && $domain eq 'public') {
13228: 	if (!defined($env{'form.username'})) {
13229: 	    $env{'form.username'}.=time.rand(10000000);
13230: 	}
13231: 	$name.=$env{'form.username'};
13232:     }
13233:     return ($symb,$courseid,$domain,$name,$publicuser);
13234: 
13235: }
13236: 
13237: # ------------------------------------------------------------ Serves up a file
13238: # returns either the contents of the file or 
13239: # -1 if the file doesn't exist
13240: #
13241: # if the target is a file that was uploaded via DOCS, 
13242: # a check will be made to see if a current copy exists on the local server,
13243: # if it does this will be served, otherwise a copy will be retrieved from
13244: # the home server for the course and stored in /home/httpd/html/userfiles on
13245: # the local server.   
13246: 
13247: sub getfile {
13248:     my ($file) = @_;
13249:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13250:     &repcopy($file);
13251:     return &readfile($file);
13252: }
13253: 
13254: sub repcopy_userfile {
13255:     my ($file)=@_;
13256:     my $londocroot = $perlvar{'lonDocRoot'};
13257:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13258:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13259:     my ($cdom,$cnum,$filename) = 
13260: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13261:     my $uri="/uploaded/$cdom/$cnum/$filename";
13262:     if (-e "$file") {
13263: # we already have a local copy, check it out
13264: 	my @fileinfo = stat($file);
13265: 	my $rtncode;
13266: 	my $info;
13267: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13268: 	if ($lwpresp ne 'ok') {
13269: # there is no such file anymore, even though we had a local copy
13270: 	    if ($rtncode eq '404') {
13271: 		unlink($file);
13272: 	    }
13273: 	    return -1;
13274: 	}
13275: 	if ($info < $fileinfo[9]) {
13276: # nice, the file we have is up-to-date, just say okay
13277: 	    return 'ok';
13278: 	} else {
13279: # the file is outdated, get rid of it
13280: 	    unlink($file);
13281: 	}
13282:     }
13283: # one way or the other, at this point, we don't have the file
13284: # construct the correct path for the file
13285:     my @parts = ($cdom,$cnum); 
13286:     if ($filename =~ m|^(.+)/[^/]+$|) {
13287: 	push @parts, split(/\//,$1);
13288:     }
13289:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13290:     foreach my $part (@parts) {
13291: 	$path .= '/'.$part;
13292: 	if (!-e $path) {
13293: 	    mkdir($path,0770);
13294: 	}
13295:     }
13296: # now the path exists for sure
13297: # get a user agent
13298:     my $transferfile=$file.'.in.transfer';
13299: # FIXME: this should flock
13300:     if (-e $transferfile) { return 'ok'; }
13301:     my $request;
13302:     $uri=~s/^\///;
13303:     my $homeserver = &homeserver($cnum,$cdom);
13304:     my $protocol = $protocol{$homeserver};
13305:     $protocol = 'http' if ($protocol ne 'https');
13306:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
13307:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
13308: # did it work?
13309:     if ($response->is_error()) {
13310: 	unlink($transferfile);
13311: 	&logthis("Userfile repcopy failed for $uri");
13312: 	return -1;
13313:     }
13314: # worked, rename the transfer file
13315:     rename($transferfile,$file);
13316:     return 'ok';
13317: }
13318: 
13319: sub tokenwrapper {
13320:     my $uri=shift;
13321:     $uri=~s|^https?\://([^/]+)||;
13322:     $uri=~s|^/||;
13323:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13324:     my $token=$1;
13325:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13326:     if ($udom && $uname && $file) {
13327: 	$file=~s|(\?\.*)*$||;
13328:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13329:         my $homeserver = &homeserver($uname,$udom);
13330:         my $protocol = $protocol{$homeserver};
13331:         $protocol = 'http' if ($protocol ne 'https');
13332:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13333:                (($uri=~/\?/)?'&':'?').'token='.$token.
13334:                                '&tokenissued='.$perlvar{'lonHostID'};
13335:     } else {
13336:         return '/adm/notfound.html';
13337:     }
13338: }
13339: 
13340: # call with reqtype HEAD: get last modification time
13341: # call with reqtype GET: get the file contents
13342: # Do not call this with reqtype GET for large files! It loads everything into memory
13343: #
13344: sub getuploaded {
13345:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13346:     $uri=~s/^\///;
13347:     my $homeserver = &homeserver($cnum,$cdom);
13348:     my $protocol = $protocol{$homeserver};
13349:     $protocol = 'http' if ($protocol ne 'https');
13350:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13351:     my $request=new HTTP::Request($reqtype,$uri);
13352:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13353:     $$rtncode = $response->code;
13354:     if (! $response->is_success()) {
13355: 	return 'failed';
13356:     }      
13357:     if ($reqtype eq 'HEAD') {
13358: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13359:     } elsif ($reqtype eq 'GET') {
13360: 	$$info = $response->content;
13361:     }
13362:     return 'ok';
13363: }
13364: 
13365: sub readfile {
13366:     my $file = shift;
13367:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13368:     my $fh;
13369:     open($fh,"<",$file);
13370:     my $a='';
13371:     while (my $line = <$fh>) { $a .= $line; }
13372:     return $a;
13373: }
13374: 
13375: sub filelocation {
13376:     my ($dir,$file) = @_;
13377:     my $location;
13378:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13379: 
13380:     if ($file =~ m-^/adm/-) {
13381: 	$file=~s-^/adm/wrapper/-/-;
13382: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13383:     }
13384: 
13385:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13386:         $location = $file;
13387:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13388:         my ($udom,$uname,$filename)=
13389:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13390:         my $home=&homeserver($uname,$udom);
13391:         my $is_me=0;
13392:         my @ids=&current_machine_ids();
13393:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13394:         if ($is_me) {
13395:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13396:         } else {
13397:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13398:   	      $udom.'/'.$uname.'/'.$filename;
13399:         }
13400:     } elsif ($file =~ m-^/adm/-) {
13401: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13402:     } else {
13403:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13404:         $file=~s:^/(res|priv)/:/:;
13405:         my $space=$1;
13406:         if ( !( $file =~ m:^/:) ) {
13407:             $location = $dir. '/'.$file;
13408:         } else {
13409:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13410:         }
13411:     }
13412:     $location=~s://+:/:g; # remove duplicate /
13413:     while ($location=~m{/\.\./}) {
13414: 	if ($location =~ m{/[^/]+/\.\./}) {
13415: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13416: 	} else {
13417: 	    $location=~ s{/\.\./}{/}g;
13418: 	}
13419:     } #remove dir/..
13420:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13421:     return $location;
13422: }
13423: 
13424: sub hreflocation {
13425:     my ($dir,$file)=@_;
13426:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13427: 	$file=filelocation($dir,$file);
13428:     } elsif ($file=~m-^/adm/-) {
13429: 	$file=~s-^/adm/wrapper/-/-;
13430: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13431:     }
13432:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13433: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13434:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13435: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13436: 	        {/uploaded/$1/$2/}x;
13437:     }
13438:     if ($file=~ m{^/userfiles/}) {
13439: 	$file =~ s{^/userfiles/}{/uploaded/};
13440:     }
13441:     return $file;
13442: }
13443: 
13444: 
13445: 
13446: 
13447: 
13448: sub current_machine_domains {
13449:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13450: }
13451: 
13452: sub machine_domains {
13453:     my ($hostname) = @_;
13454:     my @domains;
13455:     my %hostname = &all_hostnames();
13456:     while( my($id, $name) = each(%hostname)) {
13457: #	&logthis("-$id-$name-$hostname-");
13458: 	if ($hostname eq $name) {
13459: 	    push(@domains,&host_domain($id));
13460: 	}
13461:     }
13462:     return @domains;
13463: }
13464: 
13465: sub current_machine_ids {
13466:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13467: }
13468: 
13469: sub machine_ids {
13470:     my ($hostname) = @_;
13471:     $hostname ||= &hostname($perlvar{'lonHostID'});
13472:     my @ids;
13473:     my %name_to_host = &all_names();
13474:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13475: 	return @{ $name_to_host{$hostname} };
13476:     }
13477:     return;
13478: }
13479: 
13480: sub additional_machine_domains {
13481:     my @domains;
13482:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13483:     while( my $line = <$fh>) {
13484:         $line =~ s/\s//g;
13485:         push(@domains,$line);
13486:     }
13487:     return @domains;
13488: }
13489: 
13490: sub default_login_domain {
13491:     my $domain = $perlvar{'lonDefDomain'};
13492:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13493:     foreach my $posdom (&current_machine_domains(),
13494:                         &additional_machine_domains()) {
13495:         if (lc($posdom) eq lc($testdomain)) {
13496:             $domain=$posdom;
13497:             last;
13498:         }
13499:     }
13500:     return $domain;
13501: }
13502: 
13503: # ------------------------------------------------------------- Declutters URLs
13504: 
13505: sub declutter {
13506:     my $thisfn=shift;
13507:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13508:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13509:         $thisfn=~s{^/home/httpd/html}{};
13510:     }
13511:     $thisfn=~s/^\///;
13512:     $thisfn=~s|^adm/wrapper/||;
13513:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13514:     $thisfn=~s/^res\///;
13515:     $thisfn=~s/^priv\///;
13516:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13517:         $thisfn=~s/\?.+$//;
13518:     }
13519:     return $thisfn;
13520: }
13521: 
13522: # ------------------------------------------------------------- Clutter up URLs
13523: 
13524: sub clutter {
13525:     my $thisfn='/'.&declutter(shift);
13526:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13527: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13528:        $thisfn='/res'.$thisfn; 
13529:     }
13530:     if ($thisfn !~m|^/adm|) {
13531: 	if ($thisfn =~ m|^/ext/|) {
13532: 	    $thisfn='/adm/wrapper'.$thisfn;
13533: 	} else {
13534: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13535: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13536: 	    if ($embstyle eq 'ssi'
13537: 		|| ($embstyle eq 'hdn')
13538: 		|| ($embstyle eq 'rat')
13539: 		|| ($embstyle eq 'prv')
13540: 		|| ($embstyle eq 'ign')) {
13541: 		#do nothing with these
13542: 	    } elsif (($embstyle eq 'img') 
13543: 		|| ($embstyle eq 'emb')
13544: 		|| ($embstyle eq 'wrp')) {
13545: 		$thisfn='/adm/wrapper'.$thisfn;
13546: 	    } elsif ($embstyle eq 'unk'
13547: 		     && $thisfn!~/\.(sequence|page)$/) {
13548: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13549: 	    } else {
13550: #		&logthis("Got a blank emb style");
13551: 	    }
13552: 	}
13553:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13554:         $thisfn='/adm/wrapper'.$thisfn;
13555:     }
13556:     return $thisfn;
13557: }
13558: 
13559: sub clutter_with_no_wrapper {
13560:     my $uri = &clutter(shift);
13561:     if ($uri =~ m-^/adm/-) {
13562: 	$uri =~ s-^/adm/wrapper/-/-;
13563: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13564:     }
13565:     return $uri;
13566: }
13567: 
13568: sub freeze_escape {
13569:     my ($value)=@_;
13570:     if (ref($value)) {
13571: 	$value=&nfreeze($value);
13572: 	return '__FROZEN__'.&escape($value);
13573:     }
13574:     return &escape($value);
13575: }
13576: 
13577: 
13578: sub thaw_unescape {
13579:     my ($value)=@_;
13580:     if ($value =~ /^__FROZEN__/) {
13581: 	substr($value,0,10,undef);
13582: 	$value=&unescape($value);
13583: 	return &thaw($value);
13584:     }
13585:     return &unescape($value);
13586: }
13587: 
13588: sub correct_line_ends {
13589:     my ($result)=@_;
13590:     $$result =~s/\r\n/\n/mg;
13591:     $$result =~s/\r/\n/mg;
13592: }
13593: # ================================================================ Main Program
13594: 
13595: sub goodbye {
13596:    &logthis("Starting Shut down");
13597: #not converted to using infrastruture and probably shouldn't be
13598:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13599: #converted
13600: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13601:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13602: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13603: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13604: #1.1 only
13605: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13606: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13607: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13608: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13609:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13610:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13611:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13612:    &flushcourselogs();
13613:    &logthis("Shutting down");
13614: }
13615: 
13616: sub get_dns {
13617:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13618:     if (!$ignore_cache) {
13619: 	my ($content,$cached)=
13620: 	    &Apache::lonnet::is_cached_new('dns',$url);
13621: 	if ($cached) {
13622: 	    &$func($content,$hashref);
13623: 	    return;
13624: 	}
13625:     }
13626: 
13627:     my %alldns;
13628:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13629:         foreach my $dns (<$config>) {
13630: 	    next if ($dns !~ /^\^(\S*)/x);
13631:             my $line = $1;
13632:             my ($host,$protocol) = split(/:/,$line);
13633:             if ($protocol ne 'https') {
13634:                 $protocol = 'http';
13635:             }
13636: 	    $alldns{$host} = $protocol;
13637:         }
13638:         close($config);
13639:     }
13640:     while (%alldns) {
13641: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13642: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13643:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13644:         delete($alldns{$dns});
13645: 	next if ($response->is_error());
13646:         if ($url eq '/adm/dns/loncapaCRL') {
13647:             return &$func($response);
13648:         } else {
13649: 	    my @content = split("\n",$response->content);
13650: 	    unless ($nocache) {
13651: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
13652: 	    }
13653: 	    &$func(\@content,$hashref);
13654:             return;
13655:         }
13656:     }
13657:     my $which = (split('/',$url,4))[3];
13658:     if ($which eq 'loncapaCRL') {
13659:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13660:         if (-e $diskfile) {
13661:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
13662:         } else {
13663:             &logthis("unable to contact DNS, no on disk file $diskfile available");
13664:         }
13665:     } else {
13666:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13667:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13668:             my @content = <$config>;
13669:             close($config);
13670:             &$func(\@content,$hashref);
13671:         }
13672:     }
13673:     return;
13674: }
13675: 
13676: # ------------------------------------------------------Get DNS checksums file
13677: sub parse_dns_checksums_tab {
13678:     my ($lines,$hashref) = @_;
13679:     my $lonhost = $perlvar{'lonHostID'};
13680:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13681:     my $loncaparev = &get_server_loncaparev($machine_dom);
13682:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13683:     my $webconfdir = '/etc/httpd/conf';
13684:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13685:         $webconfdir = '/etc/apache2';
13686:     } elsif ($distro =~ /^sles(\d+)$/) {
13687:         if ($1 >= 10) {
13688:             $webconfdir = '/etc/apache2';
13689:         }
13690:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13691:         if ($1 >= 10.0) {
13692:             $webconfdir = '/etc/apache2';
13693:         }
13694:     }
13695:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13696:     my (%chksum,%revnum);
13697:     if (ref($lines) eq 'ARRAY') {
13698:         chomp(@{$lines});
13699:         my $version = shift(@{$lines});
13700:         if ($version eq $release) {  
13701:             foreach my $line (@{$lines}) {
13702:                 my ($file,$version,$shasum) = split(/,/,$line);
13703:                 if ($file =~ m{^/etc/httpd/conf}) {
13704:                     if ($webconfdir eq '/etc/apache2') {
13705:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13706:                     }
13707:                 }
13708:                 $chksum{$file} = $shasum;
13709:                 $revnum{$file} = $version;
13710:             }
13711:             if (ref($hashref) eq 'HASH') {
13712:                 %{$hashref} = (
13713:                                 sums     => \%chksum,
13714:                                 versions => \%revnum,
13715:                               );
13716:             }
13717:         }
13718:     }
13719:     return;
13720: }
13721: 
13722: sub fetch_dns_checksums {
13723:     my %checksums;
13724:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13725:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13726:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13727:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13728:              \%checksums);
13729:     return \%checksums;
13730: }
13731: 
13732: sub fetch_crl_pemfile {
13733:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
13734: }
13735: 
13736: sub save_crl_pem {
13737:     my ($response) = @_;
13738:     my ($msg,$hadchanges);
13739:     if (ref($response)) {
13740:         my $now = time;
13741:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
13742:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
13743:         if (open(my $fh,'>',"$tmpcrl")) {
13744:             print $fh $response->content;
13745:             close($fh);
13746:             if (-e $lonca) {
13747:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
13748:                     my $check = <PIPE>;
13749:                     close(PIPE);
13750:                     chomp($check);
13751:                     if ($check eq 'verify OK') {
13752:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
13753:                         my $backup;
13754:                         if (-e $dest) {
13755:                             if (&File::Copy::move($dest,"$dest.bak")) {
13756:                                 $backup = 'ok';
13757:                             }
13758:                         }
13759:                         if (&File::Copy::move($tmpcrl,$dest)) {
13760:                             $msg = 'ok';
13761:                             if ($backup) {
13762:                                 my (%oldnums,%newnums);
13763:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
13764:                                     while (<PIPE>) {
13765:                                         $oldnums{(split(/:/))[1]} = 1;
13766:                                     }
13767:                                     close(PIPE);
13768:                                 }
13769:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
13770:                                     while(<PIPE>) {
13771:                                         $newnums{(split(/:/))[1]} = 1;
13772:                                     }
13773:                                     close(PIPE);
13774:                                 }
13775:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
13776:                                     unless (exists($oldnums{$key})) {
13777:                                         $hadchanges = 1;
13778:                                         last;
13779:                                     }
13780:                                 }
13781:                                 unless ($hadchanges) {
13782:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
13783:                                         unless (exists($newnums{$key})) {
13784:                                             $hadchanges = 1;
13785:                                             last;
13786:                                         }
13787:                                     }
13788:                                 }
13789:                             }
13790:                         }
13791:                     } else {
13792:                         unlink($tmpcrl);
13793:                     }
13794:                 } else {
13795:                     unlink($tmpcrl);
13796:                 }
13797:             } else {
13798:                 unlink($tmpcrl);
13799:             }
13800:         }
13801:     }
13802:     return ($msg,$hadchanges);
13803: }
13804: 
13805: # ------------------------------------------------------------ Read domain file
13806: {
13807:     my $loaded;
13808:     my %domain;
13809: 
13810:     sub parse_domain_tab {
13811: 	my ($lines) = @_;
13812: 	foreach my $line (@$lines) {
13813: 	    next if ($line =~ /^(\#|\s*$ )/x);
13814: 
13815: 	    chomp($line);
13816: 	    my ($name,@elements) = split(/:/,$line,9);
13817: 	    my %this_domain;
13818: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13819: 			       'lang_def', 'city', 'longi', 'lati',
13820: 			       'primary') {
13821: 		$this_domain{$field} = shift(@elements);
13822: 	    }
13823: 	    $domain{$name} = \%this_domain;
13824: 	}
13825:     }
13826: 
13827:     sub reset_domain_info {
13828: 	undef($loaded);
13829: 	undef(%domain);
13830:     }
13831: 
13832:     sub load_domain_tab {
13833: 	my ($ignore_cache,$nocache) = @_;
13834: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13835: 	my $fh;
13836: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13837: 	    my @lines = <$fh>;
13838: 	    &parse_domain_tab(\@lines);
13839: 	}
13840: 	close($fh);
13841: 	$loaded = 1;
13842:     }
13843: 
13844:     sub domain {
13845: 	&load_domain_tab() if (!$loaded);
13846: 
13847: 	my ($name,$what) = @_;
13848: 	return if ( !exists($domain{$name}) );
13849: 
13850: 	if (!$what) {
13851: 	    return $domain{$name}{'description'};
13852: 	}
13853: 	return $domain{$name}{$what};
13854:     }
13855: 
13856:     sub domain_info {
13857:         &load_domain_tab() if (!$loaded);
13858:         return %domain;
13859:     }
13860: 
13861: }
13862: 
13863: 
13864: # ------------------------------------------------------------- Read hosts file
13865: {
13866:     my %hostname;
13867:     my %hostdom;
13868:     my %libserv;
13869:     my $loaded;
13870:     my %name_to_host;
13871:     my %internetdom;
13872:     my %LC_dns_serv;
13873: 
13874:     sub parse_hosts_tab {
13875: 	my ($file) = @_;
13876: 	foreach my $configline (@$file) {
13877: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13878:             chomp($configline);
13879: 	    if ($configline =~ /^\^/) {
13880:                 if ($configline =~ /^\^([\w.\-]+)/) {
13881:                     $LC_dns_serv{$1} = 1;
13882:                 }
13883:                 next;
13884:             }
13885: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13886: 	    $name=~s/\s//g;
13887: 	    if ($id && $domain && $role && $name) {
13888:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13889:                     my $curr = $hostname{$id};
13890:                     my $skip;
13891:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13892:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13893:                             $skip = 1;
13894:                         } else {
13895:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13896:                         }
13897:                     }
13898:                     unless ($skip) {
13899:                         push(@{$name_to_host{$name}},$id);
13900:                     }
13901:                 } else {
13902:                     push(@{$name_to_host{$name}},$id);
13903:                 }
13904: 		$hostname{$id}=$name;
13905: 		$hostdom{$id}=$domain;
13906: 		if ($role eq 'library') { $libserv{$id}=$name; }
13907:                 if (defined($protocol)) {
13908:                     if ($protocol eq 'https') {
13909:                         $protocol{$id} = $protocol;
13910:                     } else {
13911:                         $protocol{$id} = 'http'; 
13912:                     }
13913:                 } else {
13914:                     $protocol{$id} = 'http';
13915:                 }
13916:                 if (defined($intdom)) {
13917:                     $internetdom{$id} = $intdom;
13918:                 }
13919: 	    }
13920: 	}
13921:     }
13922:     
13923:     sub reset_hosts_info {
13924: 	&purge_remembered();
13925: 	&reset_domain_info();
13926: 	&reset_hosts_ip_info();
13927:         undef(%internetdom);
13928: 	undef(%name_to_host);
13929: 	undef(%hostname);
13930: 	undef(%hostdom);
13931: 	undef(%libserv);
13932: 	undef($loaded);
13933:     }
13934: 
13935:     sub load_hosts_tab {
13936: 	my ($ignore_cache,$nocache) = @_;
13937: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13938: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13939: 	my @config = <$config>;
13940: 	&parse_hosts_tab(\@config);
13941: 	close($config);
13942: 	$loaded=1;
13943:     }
13944: 
13945:     sub hostname {
13946: 	&load_hosts_tab() if (!$loaded);
13947: 
13948: 	my ($lonid) = @_;
13949: 	return $hostname{$lonid};
13950:     }
13951: 
13952:     sub all_hostnames {
13953: 	&load_hosts_tab() if (!$loaded);
13954: 
13955: 	return %hostname;
13956:     }
13957: 
13958:     sub all_names {
13959:         my ($ignore_cache,$nocache) = @_;
13960: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13961: 
13962: 	return %name_to_host;
13963:     }
13964: 
13965:     sub all_host_domain {
13966:         &load_hosts_tab() if (!$loaded);
13967:         return %hostdom;
13968:     }
13969: 
13970:     sub all_host_intdom {
13971:         &load_hosts_tab() if (!$loaded);
13972:         return %internetdom;
13973:     }
13974: 
13975:     sub is_library {
13976: 	&load_hosts_tab() if (!$loaded);
13977: 
13978: 	return exists($libserv{$_[0]});
13979:     }
13980: 
13981:     sub all_library {
13982: 	&load_hosts_tab() if (!$loaded);
13983: 
13984: 	return %libserv;
13985:     }
13986: 
13987:     sub unique_library {
13988: 	#2x reverse removes all hostnames that appear more than once
13989:         my %unique = reverse &all_library();
13990:         return reverse %unique;
13991:     }
13992: 
13993:     sub get_servers {
13994: 	&load_hosts_tab() if (!$loaded);
13995: 
13996: 	my ($domain,$type) = @_;
13997: 	my %possible_hosts = ($type eq 'library') ? %libserv
13998: 	                                          : %hostname;
13999: 	my %result;
14000: 	if (ref($domain) eq 'ARRAY') {
14001: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14002: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
14003: 		    $result{$host} = $hostname;
14004: 		}
14005: 	    }
14006: 	} else {
14007: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
14008: 		if ($hostdom{$host} eq $domain) {
14009: 		    $result{$host} = $hostname;
14010: 		}
14011: 	    }
14012: 	}
14013: 	return %result;
14014:     }
14015: 
14016:     sub get_unique_servers {
14017:         my %unique = reverse &get_servers(@_);
14018: 	return reverse %unique;
14019:     }
14020: 
14021:     sub host_domain {
14022: 	&load_hosts_tab() if (!$loaded);
14023: 
14024: 	my ($lonid) = @_;
14025: 	return $hostdom{$lonid};
14026:     }
14027: 
14028:     sub all_domains {
14029: 	&load_hosts_tab() if (!$loaded);
14030: 
14031: 	my %seen;
14032: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
14033: 	return @uniq;
14034:     }
14035: 
14036:     sub internet_dom {
14037:         &load_hosts_tab() if (!$loaded);
14038: 
14039:         my ($lonid) = @_;
14040:         return $internetdom{$lonid};
14041:     }
14042: 
14043:     sub is_LC_dns {
14044:         &load_hosts_tab() if (!$loaded);
14045: 
14046:         my ($hostname) = @_;
14047:         return exists($LC_dns_serv{$hostname});
14048:     }
14049: 
14050: }
14051: 
14052: { 
14053:     my %iphost;
14054:     my %name_to_ip;
14055:     my %lonid_to_ip;
14056: 
14057:     sub get_hosts_from_ip {
14058: 	my ($ip) = @_;
14059: 	my %iphosts = &get_iphost();
14060: 	if (ref($iphosts{$ip})) {
14061: 	    return @{$iphosts{$ip}};
14062: 	}
14063: 	return;
14064:     }
14065:     
14066:     sub reset_hosts_ip_info {
14067: 	undef(%iphost);
14068: 	undef(%name_to_ip);
14069: 	undef(%lonid_to_ip);
14070:     }
14071: 
14072:     sub get_host_ip {
14073: 	my ($lonid) = @_;
14074: 	if (exists($lonid_to_ip{$lonid})) {
14075: 	    return $lonid_to_ip{$lonid};
14076: 	}
14077: 	my $name=&hostname($lonid);
14078:    	my $ip = gethostbyname($name);
14079: 	return if (!$ip || length($ip) ne 4);
14080: 	$ip=inet_ntoa($ip);
14081: 	$name_to_ip{$name}   = $ip;
14082: 	$lonid_to_ip{$lonid} = $ip;
14083: 	return $ip;
14084:     }
14085:     
14086:     sub get_iphost {
14087: 	my ($ignore_cache,$nocache) = @_;
14088: 
14089: 	if (!$ignore_cache) {
14090: 	    if (%iphost) {
14091: 		return %iphost;
14092: 	    }
14093: 	    my ($ip_info,$cached)=
14094: 		&Apache::lonnet::is_cached_new('iphost','iphost');
14095: 	    if ($cached) {
14096: 		%iphost      = %{$ip_info->[0]};
14097: 		%name_to_ip  = %{$ip_info->[1]};
14098: 		%lonid_to_ip = %{$ip_info->[2]};
14099: 		return %iphost;
14100: 	    }
14101: 	}
14102: 
14103: 	# get yesterday's info for fallback
14104: 	my %old_name_to_ip;
14105: 	my ($ip_info,$cached)=
14106: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
14107: 	if ($cached) {
14108: 	    %old_name_to_ip = %{$ip_info->[1]};
14109: 	}
14110: 
14111: 	my %name_to_host = &all_names($ignore_cache,$nocache);
14112: 	foreach my $name (keys(%name_to_host)) {
14113: 	    my $ip;
14114: 	    if (!exists($name_to_ip{$name})) {
14115: 		$ip = gethostbyname($name);
14116: 		if (!$ip || length($ip) ne 4) {
14117: 		    if (defined($old_name_to_ip{$name})) {
14118: 			$ip = $old_name_to_ip{$name};
14119: 			&logthis("Can't find $name defaulting to old $ip");
14120: 		    } else {
14121: 			&logthis("Name $name no IP found");
14122: 			next;
14123: 		    }
14124: 		} else {
14125: 		    $ip=inet_ntoa($ip);
14126: 		}
14127: 		$name_to_ip{$name} = $ip;
14128: 	    } else {
14129: 		$ip = $name_to_ip{$name};
14130: 	    }
14131: 	    foreach my $id (@{ $name_to_host{$name} }) {
14132: 		$lonid_to_ip{$id} = $ip;
14133: 	    }
14134: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
14135: 	}
14136:         unless ($nocache) {
14137: 	    &do_cache_new('iphost','iphost',
14138: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
14139: 		          48*60*60);
14140:         }
14141: 
14142: 	return %iphost;
14143:     }
14144: 
14145:     #
14146:     #  Given a DNS returns the loncapa host name for that DNS 
14147:     # 
14148:     sub host_from_dns {
14149:         my ($dns) = @_;
14150:         my @hosts;
14151:         my $ip;
14152: 
14153:         if (exists($name_to_ip{$dns})) {
14154:             $ip = $name_to_ip{$dns};
14155:         }
14156:         if (!$ip) {
14157:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14158:             if (length($ip) == 4) { 
14159: 	        $ip   = &IO::Socket::inet_ntoa($ip);
14160:             }
14161:         }
14162:         if ($ip) {
14163: 	    @hosts = get_hosts_from_ip($ip);
14164: 	    return $hosts[0];
14165:         }
14166:         return undef;
14167:     }
14168: 
14169:     sub get_internet_names {
14170:         my ($lonid) = @_;
14171:         return if ($lonid eq '');
14172:         my ($idnref,$cached)=
14173:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14174:         if ($cached) {
14175:             return $idnref;
14176:         }
14177:         my $ip = &get_host_ip($lonid);
14178:         my @hosts = &get_hosts_from_ip($ip);
14179:         my %iphost = &get_iphost();
14180:         my (@idns,%seen);
14181:         foreach my $id (@hosts) {
14182:             my $dom = &host_domain($id);
14183:             my $prim_id = &domain($dom,'primary');
14184:             my $prim_ip = &get_host_ip($prim_id);
14185:             next if ($seen{$prim_ip});
14186:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14187:                 foreach my $id (@{$iphost{$prim_ip}}) {
14188:                     my $intdom = &internet_dom($id);
14189:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14190:                         push(@idns,$intdom);
14191:                     }
14192:                 }
14193:             }
14194:             $seen{$prim_ip} = 1;
14195:         }
14196:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14197:     }
14198: 
14199: }
14200: 
14201: sub all_loncaparevs {
14202:     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);
14203: }
14204: 
14205: # ---------------------------------------------------------- Read loncaparev table
14206: {
14207:     sub load_loncaparevs { 
14208:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14209:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14210:                 while (my $configline=<$config>) {
14211:                     chomp($configline);
14212:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14213:                     $loncaparevs{$hostid}=$loncaparev;
14214:                 }
14215:                 close($config);
14216:             }
14217:         }
14218:     }
14219: }
14220: 
14221: # ---------------------------------------------------------- Read serverhostID table
14222: {
14223:     sub load_serverhomeIDs {
14224:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14225:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14226:                 while (my $configline=<$config>) {
14227:                     chomp($configline);
14228:                     my ($name,$id)=split(/:/,$configline);
14229:                     $serverhomeIDs{$name}=$id;
14230:                 }
14231:                 close($config);
14232:             }
14233:         }
14234:     }
14235: }
14236: 
14237: 
14238: BEGIN {
14239: 
14240: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14241:     unless ($readit) {
14242: {
14243:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14244:     %perlvar = (%perlvar,%{$configvars});
14245: }
14246: 
14247: 
14248: # ------------------------------------------------------ Read spare server file
14249: {
14250:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14251: 
14252:     while (my $configline=<$config>) {
14253:        chomp($configline);
14254:        if ($configline) {
14255: 	   my ($host,$type) = split(':',$configline,2);
14256: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14257: 	   push(@{ $spareid{$type} }, $host);
14258:        }
14259:     }
14260:     close($config);
14261: }
14262: # ------------------------------------------------------------ Read permissions
14263: {
14264:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14265: 
14266:     while (my $configline=<$config>) {
14267: 	chomp($configline);
14268: 	if ($configline) {
14269: 	    my ($role,$perm)=split(/ /,$configline);
14270: 	    if ($perm ne '') { $pr{$role}=$perm; }
14271: 	}
14272:     }
14273:     close($config);
14274: }
14275: 
14276: # -------------------------------------------- Read plain texts for permissions
14277: {
14278:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14279: 
14280:     while (my $configline=<$config>) {
14281: 	chomp($configline);
14282: 	if ($configline) {
14283: 	    my ($short,@plain)=split(/:/,$configline);
14284:             %{$prp{$short}} = ();
14285: 	    if (@plain > 0) {
14286:                 $prp{$short}{'std'} = $plain[0];
14287:                 for (my $i=1; $i<@plain; $i++) {
14288:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14289:                 }
14290:             }
14291: 	}
14292:     }
14293:     close($config);
14294: }
14295: 
14296: # ---------------------------------------------------------- Read package table
14297: {
14298:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14299: 
14300:     while (my $configline=<$config>) {
14301: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14302: 	chomp($configline);
14303: 	my ($short,$plain)=split(/:/,$configline);
14304: 	my ($pack,$name)=split(/\&/,$short);
14305: 	if ($plain ne '') {
14306: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14307: 	    $packagetab{$short}=$plain; 
14308: 	}
14309:     }
14310:     close($config);
14311: }
14312: 
14313: # ---------------------------------------------------------- Read loncaparev table
14314: 
14315: &load_loncaparevs();
14316: 
14317: # ---------------------------------------------------------- Read serverhostID table
14318: 
14319: &load_serverhomeIDs();
14320: 
14321: # ---------------------------------------------------------- Read releaseslist XML
14322: {
14323:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14324:     if (-e $file) {
14325:         my $parser = HTML::LCParser->new($file);
14326:         while (my $token = $parser->get_token()) {
14327:             if ($token->[0] eq 'S') {
14328:                 my $item = $token->[1];
14329:                 my $name = $token->[2]{'name'};
14330:                 my $value = $token->[2]{'value'};
14331:                 my $valuematch = $token->[2]{'valuematch'};
14332:                 my $namematch = $token->[2]{'namematch'};
14333:                 if ($item eq 'parameter') {
14334:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
14335:                         my $release = $parser->get_text();
14336:                         $release =~ s/(^\s*|\s*$ )//gx;
14337:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
14338:                     }
14339:                 } elsif ($item ne '' && $name ne '') {
14340:                     my $release = $parser->get_text();
14341:                     $release =~ s/(^\s*|\s*$ )//gx;
14342:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14343:                 }
14344:             }
14345:         }
14346:     }
14347: }
14348: 
14349: # ---------------------------------------------------------- Read managers table
14350: {
14351:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14352:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14353:             while (my $configline=<$config>) {
14354:                 chomp($configline);
14355:                 next if ($configline =~ /^\#/);
14356:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14357:                     $managerstab{$configline} = 1;
14358:                 }
14359:             }
14360:             close($config);
14361:         }
14362:     }
14363: }
14364: 
14365: # ------------- set up temporary directory
14366: {
14367:     $tmpdir = LONCAPA::tempdir();
14368: 
14369: }
14370: 
14371: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14372: 				'compress_threshold'=> 20_000,
14373:  			        });
14374: 
14375: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14376: $dumpcount=0;
14377: $locknum=0;
14378: 
14379: &logtouch();
14380: &logthis('<font color="yellow">INFO: Read configuration</font>');
14381: $readit=1;
14382:     {
14383: 	use integer;
14384: 	my $test=(2**32)+1;
14385: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14386: 	&logthis(" Detected 64bit platform ($_64bit)");
14387:     }
14388: }
14389: }
14390: 
14391: 1;
14392: __END__
14393: 
14394: =pod
14395: 
14396: =head1 NAME
14397: 
14398: Apache::lonnet - Subroutines to ask questions about things in the network.
14399: 
14400: =head1 SYNOPSIS
14401: 
14402: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14403: 
14404:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14405: 
14406: Common parameters:
14407: 
14408: =over 4
14409: 
14410: =item *
14411: 
14412: $uname : an internal username (if $cname expecting a course Id specifically)
14413: 
14414: =item *
14415: 
14416: $udom : a domain (if $cdom expecting a course's domain specifically)
14417: 
14418: =item *
14419: 
14420: $symb : a resource instance identifier
14421: 
14422: =item *
14423: 
14424: $namespace : the name of a .db file that contains the data needed or
14425: being set.
14426: 
14427: =back
14428: 
14429: =head1 OVERVIEW
14430: 
14431: lonnet provides subroutines which interact with the
14432: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14433: about classes, users, and resources.
14434: 
14435: For many of these objects you can also use this to store data about
14436: them or modify them in various ways.
14437: 
14438: =head2 Symbs
14439: 
14440: To identify a specific instance of a resource, LON-CAPA uses symbols
14441: or "symbs"X<symb>. These identifiers are built from the URL of the
14442: map, the resource number of the resource in the map, and the URL of
14443: the resource itself. The latter is somewhat redundant, but might help
14444: if maps change.
14445: 
14446: An example is
14447: 
14448:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14449: 
14450: The respective map entry is
14451: 
14452:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14453:   title="Problem 2">
14454:  </resource>
14455: 
14456: Symbs are used by the random number generator, as well as to store and
14457: restore data specific to a certain instance of for example a problem.
14458: 
14459: =head2 Storing And Retrieving Data
14460: 
14461: X<store()>X<cstore()>X<restore()>Three of the most important functions
14462: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14463: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14464: is is the non-critical message twin of cstore. These functions are for
14465: handlers to store a perl hash to a user's permanent data space in an
14466: easy manner, and to retrieve it again on another call. It is expected
14467: that a handler would use this once at the beginning to retrieve data,
14468: and then again once at the end to send only the new data back.
14469: 
14470: The data is stored in the user's data directory on the user's
14471: homeserver under the ID of the course.
14472: 
14473: The hash that is returned by restore will have all of the previous
14474: value for all of the elements of the hash.
14475: 
14476: Example:
14477: 
14478:  #creating a hash
14479:  my %hash;
14480:  $hash{'foo'}='bar';
14481: 
14482:  #storing it
14483:  &Apache::lonnet::cstore(\%hash);
14484: 
14485:  #changing a value
14486:  $hash{'foo'}='notbar';
14487: 
14488:  #adding a new value
14489:  $hash{'bar'}='foo';
14490:  &Apache::lonnet::cstore(\%hash);
14491: 
14492:  #retrieving the hash
14493:  my %history=&Apache::lonnet::restore();
14494: 
14495:  #print the hash
14496:  foreach my $key (sort(keys(%history))) {
14497:    print("\%history{$key} = $history{$key}");
14498:  }
14499: 
14500: Will print out:
14501: 
14502:  %history{1:foo} = bar
14503:  %history{1:keys} = foo:timestamp
14504:  %history{1:timestamp} = 990455579
14505:  %history{2:bar} = foo
14506:  %history{2:foo} = notbar
14507:  %history{2:keys} = foo:bar:timestamp
14508:  %history{2:timestamp} = 990455580
14509:  %history{bar} = foo
14510:  %history{foo} = notbar
14511:  %history{timestamp} = 990455580
14512:  %history{version} = 2
14513: 
14514: Note that the special hash entries C<keys>, C<version> and
14515: C<timestamp> were added to the hash. C<version> will be equal to the
14516: total number of versions of the data that have been stored. The
14517: C<timestamp> attribute will be the UNIX time the hash was
14518: stored. C<keys> is available in every historical section to list which
14519: keys were added or changed at a specific historical revision of a
14520: hash.
14521: 
14522: B<Warning>: do not store the hash that restore returns directly. This
14523: will cause a mess since it will restore the historical keys as if the
14524: were new keys. I.E. 1:foo will become 1:1:foo etc.
14525: 
14526: Calling convention:
14527: 
14528:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14529:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14530: 
14531: For more detailed information, see lonnet specific documentation.
14532: 
14533: =head1 RETURN MESSAGES
14534: 
14535: =over 4
14536: 
14537: =item * B<con_lost>: unable to contact remote host
14538: 
14539: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14540: when the connection is brought back up
14541: 
14542: =item * B<con_failed>: unable to contact remote host and unable to save message
14543: for later delivery
14544: 
14545: =item * B<error:>: an error a occurred, a description of the error follows the :
14546: 
14547: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14548: that was requested
14549: 
14550: =back
14551: 
14552: =head1 PUBLIC SUBROUTINES
14553: 
14554: =head2 Session Environment Functions
14555: 
14556: =over 4
14557: 
14558: =item * 
14559: X<appenv()>
14560: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14561: the user envirnoment file, and will be restored for each access this
14562: user makes during this session, also modifies the %env for the current
14563: process. Optional rolesarrayref - if defined contains a reference to an array
14564: of roles which are exempt from the restriction on modifying user.role entries 
14565: in the user's environment.db and in %env.    
14566: 
14567: =item *
14568: X<delenv()>
14569: B<delenv($delthis,$regexp)>: removes all items from the session
14570: environment file that begin with $delthis. If the 
14571: optional second arg - $regexp - is true, $delthis is treated as a 
14572: regular expression, otherwise \Q$delthis\E is used. 
14573: The values are also deleted from the current processes %env.
14574: 
14575: =item * get_env_multiple($name) 
14576: 
14577: gets $name from the %env hash, it seemlessly handles the cases where multiple
14578: values may be defined and end up as an array ref.
14579: 
14580: returns an array of values
14581: 
14582: =back
14583: 
14584: =head2 User Information
14585: 
14586: =over 4
14587: 
14588: =item *
14589: X<queryauthenticate()>
14590: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14591: authentication scheme
14592: 
14593: =item *
14594: X<authenticate()>
14595: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14596: authenticate user from domain's lib servers (first use the current
14597: one). C<$upass> should be the users password.
14598: $checkdefauth is optional (value is 1 if a check should be made to
14599:    authenticate user using default authentication method, and allow
14600:    account creation if username does not have account in the domain).
14601: $clientcancheckhost is optional (value is 1 if checking whether the
14602:    server can host will occur on the client side in lonauth.pm).   
14603: 
14604: =item *
14605: X<homeserver()>
14606: B<homeserver($uname,$udom)>: find the server which has
14607: the user's directory and files (there must be only one), this caches
14608: the answer, and also caches if there is a borken connection.
14609: 
14610: =item *
14611: X<idget()>
14612: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14613: a list of student/employee IDs or clicker IDs
14614: (student/employee IDs are a unique resource in a domain, there must be 
14615: only 1 ID per username, and only 1 username per ID in a specific domain).
14616: clickerIDs are not necessarily unique, as students might share clickers.
14617: (returns hash: id=>name,id=>name)
14618: 
14619: =item *
14620: X<idrget()>
14621: B<idrget($udom,@unames)>: find the IDs behind a list of
14622: usernames (returns hash: name=>id,name=>id)
14623: 
14624: =item *
14625: X<idput()>
14626: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14627: names and associated student/employee IDs or clicker IDs.
14628: 
14629: =item *
14630: X<iddel()>
14631: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14632: student/employee ID or clicker ID username look-ups from domain.
14633: The homeserver ($uhome) and namespace ($namespace) are optional.
14634: If no $uhome is provided, it will be determined usig &homeserver()
14635: for each user.  If no $namespace is provided, the default is ids.
14636: 
14637: =item *
14638: X<updateclickers()>
14639: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14640: clicker ID-to-username look-ups in clickers.db on library server.
14641: Permitted actions are add or del (i.e., add or delete). The 
14642: clickers.db contains clickerID as keys (escaped), and each corresponding
14643: value is an escaped comma-separated list of usernames (for whom the
14644: library server is the homeserver), who registered that particular ID.
14645: If $critical is true, the update will be sent via &critical, otherwise
14646: &reply() will be used.
14647: 
14648: =item *
14649: X<rolesinit()>
14650: B<rolesinit($udom,$username)>: get user privileges.
14651: returns user role, first access and timer interval hashes
14652: 
14653: =item *
14654: X<privileged()>
14655: B<privileged($username,$domain)>: returns a true if user has a
14656: privileged and active role (i.e. su or dc), false otherwise.
14657: 
14658: =item *
14659: X<getsection()>
14660: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14661: course $cname, return section name/number or '' for "not in course"
14662: and '-1' for "no section"
14663: 
14664: =item *
14665: X<userenvironment()>
14666: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14667: passed in @what from the requested user's environment, returns a hash
14668: 
14669: =item * 
14670: X<userlog_query()>
14671: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14672: activity.log file. %filters defines filters applied when parsing the
14673: log file. These can be start or end timestamps, or the type of action
14674: - log to look for Login or Logout events, check for Checkin or
14675: Checkout, role for role selection. The response is in the form
14676: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14677: escaped strings of the action recorded in the activity.log file.
14678: 
14679: =back
14680: 
14681: =head2 User Roles
14682: 
14683: =over 4
14684: 
14685: =item *
14686: 
14687: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14688: returns codes for allowed actions.
14689: 
14690: The first argument is required, all others are optional.
14691: 
14692: $priv is the privilege being checked.
14693: $uri contains additional information about what is being checked for access (e.g.,
14694: URL, course ID etc.). 
14695: $symb is the unique resource instance identifier in a course; if needed,
14696: but not provided, it will be retrieved via a call to &symbread(). 
14697: $role is the role for which a priv is being checked (only used if priv is evb). 
14698: $clientip is the user's IP address (only used when checking for access to portfolio 
14699: files).
14700: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14701: prevents recursive calls to &allowed.
14702: 
14703:  F: full access
14704:  U,I,K: authentication modes (cxx only)
14705:  '': forbidden
14706:  1: user needs to choose course
14707:  2: browse allowed
14708:  A: passphrase authentication needed
14709:  B: access temporarily blocked because of a blocking event in a course.
14710: 
14711: =item *
14712: 
14713: constructaccess($url,$setpriv) : check for access to construction space URL
14714: 
14715: See if the owner domain and name in the URL match those in the
14716: expected environment.  If so, return three element list
14717: ($ownername,$ownerdomain,$ownerhome).
14718: 
14719: Otherwise return the null string.
14720: 
14721: If second argument 'setpriv' is true, it assigns the privileges,
14722: and returns the same three element list, unless the owner has
14723: blocked "ad hoc" Domain Coordinator access to the Author Space,
14724: in which case the null string is returned.
14725: 
14726: =item *
14727: 
14728: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14729: define a custom role rolename set privileges in format of lonTabs/roles.tab
14730: for system, domain, and course level. $uname and $udom are optional (current
14731: user's username and domain will be used when either of $uname or $udom are absent.
14732: 
14733: =item *
14734: 
14735: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14736: (rolesplain.tab); plain text explanation of a user role term.
14737: $type is Course (default) or Community.
14738: If $forcedefault evaluates to true, text returned will be default 
14739: text for $type. Otherwise, if this is a course, the text returned 
14740: will be a custom name for the role (if defined in the course's 
14741: environment).  If no custom name is defined the default is returned.
14742:    
14743: =item *
14744: 
14745: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14746: All arguments are optional. Returns a hash of a roles, either for
14747: co-author/assistant author roles for a user's Construction Space
14748: (default), or if $context is 'userroles', roles for the user himself,
14749: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14750: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14751: For each key, value is set to colon-separated start and end times for
14752: the role.  If no username and domain are specified, will default to
14753: current user/domain. Types, roles, and roledoms are references to arrays
14754: of role statuses (active, future or previous), roles 
14755: (e.g., cc,in, st etc.) and domains of the roles which can be used
14756: to restrict the list of roles reported. If no array ref is 
14757: provided for types, will default to return only active roles.
14758: 
14759: =item *
14760: 
14761: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14762: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14763: 
14764: Additional optional arguments are: $type (if role checking is to be restricted 
14765: to certain user status types -- previous (expired roles), active (currently
14766: available roles) or future (roles available in the future), and
14767: $hideprivileged -- if true will not report course roles for users who
14768: have active Domain Coordinator role in course's domain or in additional
14769: domains (specified in 'Domains to check for privileged users' in course
14770: environment -- set via:  Course Settings -> Classlists and staff listing).
14771: 
14772: =item *
14773: 
14774: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14775: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14776: $possdomains and $possroles are optional array refs -- to domains to check and
14777: roles to check.  If $possdomains is not specified, a dump will be done of the
14778: users' roles.db to check for a dc or su role in any domain. This can be
14779: time consuming if &privileged is called repeatedly (e.g., when displaying a
14780: classlist), so in such cases, supplying a $possdomains array is preferred, as
14781: this then allows &privileged_by_domain() to be used, which caches the identity
14782: of privileged users, eliminating the need for repeated calls to &dump().
14783: 
14784: =item *
14785: 
14786: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14787: where the outer hash keys are domains specified in the $possdomains array ref,
14788: next inner hash keys are privileged roles specified in the $roles array ref,
14789: and the innermost hash contains key = value pairs for username:domain = end:start
14790: for active or future "privileged" users with that role in that domain. To avoid
14791: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14792: innerhash are cached using priv_$role and $dom as the identifiers.
14793: 
14794: =back
14795: 
14796: =head2 User Modification
14797: 
14798: =over 4
14799: 
14800: =item *
14801: 
14802: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14803: user for the level given by URL.  Optional start and end dates (leave empty
14804: string or zero for "no date")
14805: 
14806: =item *
14807: 
14808: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14809: change a users, password, possible return values are: ok,
14810: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14811: refused
14812: 
14813: =item *
14814: 
14815: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14816: 
14817: =item *
14818: 
14819: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14820:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14821: 
14822: will update user information (firstname,middlename,lastname,generation,
14823: permanentemail), and if forceid is true, student/employee ID also.
14824: A user's institutional affiliation(s) can also be updated.
14825: User information fields will not be overwritten with empty entries 
14826: unless the field is included in the $candelete array reference.
14827: This array is included when a single user is modified via "Manage Users",
14828: or when Autoupdate.pl is run by cron in a domain.
14829: 
14830: =item *
14831: 
14832: modifystudent
14833: 
14834: modify a student's enrollment and identification information.
14835: The course id is resolved based on the current user's environment.  
14836: This means the invoking user must be a course coordinator or otherwise
14837: associated with a course.
14838: 
14839: This call is essentially a wrapper for lonnet::modifyuser and
14840: lonnet::modify_student_enrollment
14841: 
14842: Inputs: 
14843: 
14844: =over 4
14845: 
14846: =item B<$udom> Student's loncapa domain
14847: 
14848: =item B<$uname> Student's loncapa login name
14849: 
14850: =item B<$uid> Student/Employee ID
14851: 
14852: =item B<$umode> Student's authentication mode
14853: 
14854: =item B<$upass> Student's password
14855: 
14856: =item B<$first> Student's first name
14857: 
14858: =item B<$middle> Student's middle name
14859: 
14860: =item B<$last> Student's last name
14861: 
14862: =item B<$gene> Student's generation
14863: 
14864: =item B<$usec> Student's section in course
14865: 
14866: =item B<$end> Unix time of the roles expiration
14867: 
14868: =item B<$start> Unix time of the roles start date
14869: 
14870: =item B<$forceid> If defined, allow $uid to be changed
14871: 
14872: =item B<$desiredhome> server to use as home server for student
14873: 
14874: =item B<$email> Student's permanent e-mail address
14875: 
14876: =item B<$type> Type of enrollment (auto or manual)
14877: 
14878: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14879: 
14880: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14881: 
14882: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14883: 
14884: =item B<$context> role change context (shown in User Management Logs display in a course)
14885: 
14886: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14887: 
14888: =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.
14889: 
14890: =back
14891: 
14892: =item *
14893: 
14894: modify_student_enrollment
14895: 
14896: Change a student's enrollment status in a class.  The environment variable
14897: 'role.request.course' must be defined for this function to proceed.
14898: 
14899: Inputs:
14900: 
14901: =over 4
14902: 
14903: =item $udom, student's domain
14904: 
14905: =item $uname, student's name
14906: 
14907: =item $uid, student's user id
14908: 
14909: =item $first, student's first name
14910: 
14911: =item $middle
14912: 
14913: =item $last
14914: 
14915: =item $gene
14916: 
14917: =item $usec
14918: 
14919: =item $end
14920: 
14921: =item $start
14922: 
14923: =item $type
14924: 
14925: =item $locktype
14926: 
14927: =item $cid
14928: 
14929: =item $selfenroll
14930: 
14931: =item $context
14932: 
14933: =item $credits, number of credits student will earn from this class
14934: 
14935: =item $instsec, institutional course section code for student
14936: 
14937: =back
14938: 
14939: 
14940: =item *
14941: 
14942: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14943: custom role; give a custom role to a user for the level given by URL.  Specify
14944: name and domain of role author, and role name
14945: 
14946: =item *
14947: 
14948: revokerole($udom,$uname,$url,$role) : revoke a role for url
14949: 
14950: =item *
14951: 
14952: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14953: 
14954: =back
14955: 
14956: =head2 Course Infomation
14957: 
14958: =over 4
14959: 
14960: =item *
14961: 
14962: coursedescription($courseid,$options) : returns a hash of information about the
14963: specified course id, including all environment settings for the
14964: course, the description of the course will be in the hash under the
14965: key 'description'
14966: 
14967: $options is an optional parameter that if supplied is a hash reference that controls
14968: what how this function works.  It has the following key/values:
14969: 
14970: =over 4
14971: 
14972: =item freshen_cache
14973: 
14974: If defined, and the environment cache for the course is valid, it is 
14975: returned in the returned hash.
14976: 
14977: =item one_time
14978: 
14979: If defined, the last cache time is set to _now_
14980: 
14981: =item user
14982: 
14983: If defined, the supplied username is used instead of the current user.
14984: 
14985: 
14986: =back
14987: 
14988: =item *
14989: 
14990: resdata($name,$domain,$type,@which) : request for current parameter
14991: setting for a specific $type, where $type is either 'course' or 'user',
14992: @what should be a list of parameters to ask about. This routine caches
14993: answers for 10 minutes.
14994: 
14995: =item *
14996: 
14997: get_courseresdata($courseid, $domain) : dump the entire course resource
14998: data base, returning a hash that is keyed by the resource name and has
14999: values that are the resource value.  I believe that the timestamps and
15000: versions are also returned.
15001: 
15002: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
15003: supplemental content area. This routine caches the number of files for 
15004: 10 minutes.
15005: 
15006: =back
15007: 
15008: =head2 Course Modification
15009: 
15010: =over 4
15011: 
15012: =item *
15013: 
15014: writecoursepref($courseid,%prefs) : write preferences (environment
15015: database) for a course
15016: 
15017: =item *
15018: 
15019: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
15020: 
15021: =item *
15022: 
15023: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
15024: 
15025: =item *
15026: 
15027: is_course($courseid), is_course($cdom, $cnum)
15028: 
15029: Accepts either a combined $courseid (in the form of domain_courseid) or the
15030: two component version $cdom, $cnum. It checks if the specified course exists.
15031: 
15032: Returns:
15033:     undef if the course doesn't exist, otherwise
15034:     in scalar context the combined courseid.
15035:     in list context the two components of the course identifier, domain and 
15036:     courseid.    
15037: 
15038: =back
15039: 
15040: =head2 Resource Subroutines
15041: 
15042: =over 4
15043: 
15044: =item *
15045: 
15046: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
15047: 
15048: =item *
15049: 
15050: repcopy($filename) : subscribes to the requested file, and attempts to
15051: replicate from the owning library server, Might return
15052: 'unavailable', 'not_found', 'forbidden', 'ok', or
15053: 'bad_request', also attempts to grab the metadata for the
15054: resource. Expects the local filesystem pathname
15055: (/home/httpd/html/res/....)
15056: 
15057: =back
15058: 
15059: =head2 Resource Information
15060: 
15061: =over 4
15062: 
15063: =item *
15064: 
15065: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
15066: and returns the value of a variety of different possible values,
15067: $varname should be a request string, and the other parameters can be
15068: used to specify who and what one is asking about. Ordinarily, $cid 
15069: does not need to be specified, as it is retrived from 
15070: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15071: within lonuserstate::loadmap() when initializing a course, before
15072: $env{'request.course.id'} has been set, so it needs to be provided
15073: in that one case.
15074: 
15075: Possible values for $varname are environment.lastname (or other item
15076: from the envirnment hash), user.name (or someother aspect about the
15077: user), resource.0.maxtries (or some other part and parameter of a
15078: resource)
15079: 
15080: =item *
15081: 
15082: directcondval($number) : get current value of a condition; reads from a state
15083: string
15084: 
15085: =item *
15086: 
15087: condval($condidx) : value of condition index based on state
15088: 
15089: =item *
15090: 
15091: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
15092: resource's metadata, $what should be either a specific key, or either
15093: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15094: packages that this resource currently uses, the last 3 arguments are 
15095: only used internally for recursive metadata.
15096: 
15097: the toolsymb is only used where the uri is for an external tool (for which
15098: the uri as well as the symb are guaranteed to be unique).
15099: 
15100: this function automatically caches all requests except any made recursively
15101: to retrieve a list of metadata keys for an imported library file ($liburi is 
15102: defined).
15103: 
15104: =item *
15105: 
15106: metadata_query($query,$custom,$customshow) : make a metadata query against the
15107: network of library servers; returns file handle of where SQL and regex results
15108: will be stored for query
15109: 
15110: =item *
15111: 
15112: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
15113: return symbolic list entry (all arguments optional). 
15114: 
15115: Args: filename is the filename (including path) for the file for which a symb 
15116: is required; donotrecurse, if true will prevent calls to allowed() being made 
15117: to check access status if more than one resource was found in the bighash 
15118: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
15119: a randompick); ignorecachednull, if true will prevent a symb of '' being 
15120: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15121: cause possible symbs to be checked to determine if they are subject to content
15122: blocking, if so they will not be included as possible symbs; possibles is a
15123: ref to a hash, which, as a side effect, will be populated with all possible 
15124: symbs (content blocking not tested).
15125:  
15126: returns the data handle
15127: 
15128: =item *
15129: 
15130: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15131: and is a possible symb for the URL in $thisfn, and if is an encrypted
15132: resource that the user accessed using /enc/ returns a 1 on success, 0
15133: on failure, user must be in a course, as it assumes the existence of
15134: the course initial hash, and uses $env('request.course.id'}.  The third
15135: arg is an optional reference to a scalar.  If this arg is passed in the 
15136: call to symbverify, it will be set to 1 if the symb has been set to be 
15137: encrypted; otherwise it will be null.  
15138: 
15139: =item *
15140: 
15141: symbclean($symb) : removes versions numbers from a symb, returns the
15142: cleaned symb
15143: 
15144: =item *
15145: 
15146: is_on_map($uri) : checks if the $uri is somewhere on the current
15147: course map, user must be in a course for it to work.
15148: 
15149: =item *
15150: 
15151: numval($salt) : return random seed value (addend for rndseed)
15152: 
15153: =item *
15154: 
15155: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15156: a random seed, all arguments are optional, if they aren't sent it uses the
15157: environment to derive them. Note: if symb isn't sent and it can't get one
15158: from &symbread it will use the current time as its return value
15159: 
15160: =item *
15161: 
15162: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15163: unfakeable, receipt
15164: 
15165: =item *
15166: 
15167: receipt() : API to ireceipt working off of env values; given out to users
15168: 
15169: =item *
15170: 
15171: countacc($url) : count the number of accesses to a given URL
15172: 
15173: =item *
15174: 
15175: 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
15176: 
15177: =item *
15178: 
15179: 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)
15180: 
15181: =item *
15182: 
15183: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15184: 
15185: =item *
15186: 
15187: devalidate($symb) : devalidate temporary spreadsheet calculations,
15188: forcing spreadsheet to reevaluate the resource scores next time.
15189: 
15190: =item * 
15191: 
15192: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15193: when viewing in course context.
15194: 
15195:  input: six args -- filename (decluttered), course number, course domain,
15196:                     url, symb (if registered) and group (if this is a 
15197:                     group item -- e.g., bulletin board, group page etc.).
15198: 
15199:  output: array of five scalars --
15200:          $cfile -- url for file editing if editable on current server
15201:          $home -- homeserver of resource (i.e., for author if published,
15202:                                           or course if uploaded.).
15203:          $switchserver --  1 if server switch will be needed.
15204:          $forceedit -- 1 if icon/link should be to go to edit mode 
15205:          $forceview -- 1 if icon/link should be to go to view mode
15206: 
15207: =item *
15208: 
15209: is_course_upload($file,$cnum,$cdom)
15210: 
15211: Used in course context to determine if current file was uploaded to 
15212: the course (i.e., would be found in /userfiles/docs on the course's 
15213: homeserver.
15214: 
15215:   input: 3 args -- filename (decluttered), course number and course domain.
15216:   output: boolean -- 1 if file was uploaded.
15217: 
15218: =back
15219: 
15220: =head2 Storing/Retreiving Data
15221: 
15222: =over 4
15223: 
15224: =item *
15225: 
15226: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15227: permanently for this url; hashref needs to be given and should be a \%hashname;
15228: the remaining args aren't required and if they aren't passed or are '' they will
15229: be derived from the env (with the exception of $laststore, which is an 
15230: optional arg used when a user's submission is stored in grading).
15231: $laststore is $version=$timestamp, where $version is the most recent version
15232: number retrieved for the corresponding $symb in the $namespace db file, and
15233: $timestamp is the timestamp for that transaction (UNIX time).
15234: $laststore is currently only passed when cstore() is called by 
15235: structuretags::finalize_storage().
15236: 
15237: =item *
15238: 
15239: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15240: but uses critical subroutine
15241: 
15242: =item *
15243: 
15244: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15245: all args are optional
15246: 
15247: =item *
15248: 
15249: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15250: dumps the complete (or key matching regexp) namespace into a hash
15251: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15252: normally &store()ed into
15253: 
15254: $range should be either an integer '100' (give me the first 100
15255:                                            matching records)
15256:               or be  two integers sperated by a - with no spaces
15257:                  '30-50' (give me the 30th through the 50th matching
15258:                           records)
15259: 
15260: 
15261: =item *
15262: 
15263: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15264: replaces a &store() version of data with a replacement set of data
15265: for a particular resource in a namespace passed in the $storehash hash 
15266: reference. If $tolog is true, the transaction is logged in the courselog
15267: with an action=PUTSTORE.
15268: 
15269: =item *
15270: 
15271: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15272: works very similar to store/cstore, but all data is stored in a
15273: temporary location and can be reset using tmpreset, $storehash should
15274: be a hash reference, returns nothing on success
15275: 
15276: =item *
15277: 
15278: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15279: similar to restore, but all data is stored in a temporary location and
15280: can be reset using tmpreset. Returns a hash of values on success,
15281: error string otherwise.
15282: 
15283: =item *
15284: 
15285: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15286: deltes all keys for $symb form the temporary storage hash.
15287: 
15288: =item *
15289: 
15290: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15291: reference filled in from namesp ($udom and $uname are optional)
15292: 
15293: =item *
15294: 
15295: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15296: namesp ($udom and $uname are optional)
15297: 
15298: =item *
15299: 
15300: dump($namespace,$udom,$uname,$regexp,$range) : 
15301: dumps the complete (or key matching regexp) namespace into a hash
15302: ($udom, $uname, $regexp, $range are optional)
15303: 
15304: $range should be either an integer '100' (give me the first 100
15305:                                            matching records)
15306:               or be  two integers sperated by a - with no spaces
15307:                  '30-50' (give me the 30th through the 50th matching
15308:                           records)
15309: =item *
15310: 
15311: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15312: $store can be a scalar, an array reference, or if the amount to be 
15313: incremented is > 1, a hash reference.
15314: 
15315: ($udom and $uname are optional)
15316: 
15317: =item *
15318: 
15319: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15320: ($udom and $uname are optional)
15321: 
15322: =item *
15323: 
15324: cput($namespace,$storehash,$udom,$uname) : critical put
15325: ($udom and $uname are optional)
15326: 
15327: =item *
15328: 
15329: newput($namespace,$storehash,$udom,$uname) :
15330: 
15331: Attempts to store the items in the $storehash, but only if they don't
15332: currently exist, if this succeeds you can be certain that you have 
15333: successfully created a new key value pair in the $namespace db.
15334: 
15335: 
15336: Args:
15337:  $namespace: name of database to store values to
15338:  $storehash: hashref to store to the db
15339:  $udom: (optional) domain of user containing the db
15340:  $uname: (optional) name of user caontaining the db
15341: 
15342: Returns:
15343:  'ok' -> succeeded in storing all keys of $storehash
15344:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15345:                         least <key> already existed in the db (other
15346:                         requested keys may also already exist)
15347:  'error: <msg>' -> unable to tie the DB or other error occurred
15348:  'con_lost' -> unable to contact request server
15349:  'refused' -> action was not allowed by remote machine
15350: 
15351: 
15352: =item *
15353: 
15354: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15355: reference filled in from namesp (encrypts the return communication)
15356: ($udom and $uname are optional)
15357: 
15358: =item *
15359: 
15360: log($udom,$name,$home,$message) : write to permanent log for user; use
15361: critical subroutine
15362: 
15363: =item *
15364: 
15365: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15366: array reference filled in from namespace found in domain level on either
15367: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15368: 
15369: =item *
15370: 
15371: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15372: domain level either on specified domain server ($uhome) or primary domain 
15373: server ($udom and $uhome are optional)
15374: 
15375: =item * 
15376: 
15377: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
15378: for: authentication, language, quotas, timezone, date locale, and portal URL in
15379: the target domain.
15380: 
15381: May also include additional key => value pairs for the following groups:
15382: 
15383: =over
15384: 
15385: =item
15386: disk quotas (MB allocated by default to portfolios and authoring spaces).
15387: 
15388: =over
15389: 
15390: =item defaultquota, authorquota
15391: 
15392: =back
15393: 
15394: =item
15395: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15396: portfolio for users).
15397: 
15398: =over
15399: 
15400: =item
15401: aboutme, blog, webdav, portfolio
15402: 
15403: =back
15404: 
15405: =item
15406: requestcourses: ability to request courses, and how requests are processed.
15407: 
15408: =over
15409: 
15410: =item
15411: official, unofficial, community, textbook, placement
15412: 
15413: =back
15414: 
15415: =item
15416: inststatus: types of institutional affiliation, and order in which they are displayed.
15417: 
15418: =over
15419: 
15420: =item
15421: inststatustypes, inststatusorder, inststatusguest
15422: 
15423: =back
15424: 
15425: =item
15426: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15427: for course's uploaded content.
15428: 
15429: =over
15430: 
15431: =item
15432: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15433: communityquota, textbookquota, placementquota
15434: 
15435: =back
15436: 
15437: =item
15438: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15439: on your servers.
15440: 
15441: =over
15442: 
15443: =item 
15444: remotesessions, hostedsessions
15445: 
15446: =back
15447: 
15448: =back
15449: 
15450: In cases where a domain coordinator has never used the "Set Domain Configuration"
15451: utility to create a configuration.db file on a domain's primary library server 
15452: only the following domain defaults: auth_def, auth_arg_def, lang_def
15453: -- corresponding values are authentication type (internal, krb4, krb5,
15454: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15455: will be available. Values are retrieved from cache (if current), unless the
15456: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15457: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15458: 
15459: Typical usage:
15460: 
15461: %domdefaults = &get_domain_defaults($target_domain);
15462: 
15463: =back
15464: 
15465: =head2 Network Status Functions
15466: 
15467: =over 4
15468: 
15469: =item *
15470: 
15471: dirlist() : return directory list based on URI (first arg).
15472: 
15473: Inputs: 1 required, 5 optional.
15474: 
15475: =over
15476: 
15477: =item 
15478: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15479: 
15480: =item
15481: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15482: 
15483: =item
15484: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15485: 
15486: =item
15487: $getpropath - boolean: 1 if prepend path using &propath(). 
15488: 
15489: =item
15490: $getuserdir - boolean: 1 if prepend path for "userfiles".
15491: 
15492: =item 
15493: $alternateRoot - path to prepend in place of path from $uri.
15494: 
15495: =back
15496: 
15497: Returns: Array of up to two items.
15498: 
15499: =over
15500: 
15501: a reference to an array of files/subdirectories
15502: 
15503: =over
15504: 
15505: Each element in the array of files/subdirectories is a & separated list of
15506: item name and the result of running stat on the item.  If dirlist was requested
15507: for a file instead of a directory, the item name will be ''. For a directory 
15508: listing, if the item is a metadata file, the element will end &N&M 
15509: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15510: default copyright set (1).  
15511: 
15512: =back
15513: 
15514: a scalar containing error condition (if encountered).
15515: 
15516: =over
15517: 
15518: =item 
15519: no_host (no homeserver identified for $username:$domain).
15520: 
15521: =item 
15522: no_such_host (server contacted for listing not identified as valid host).
15523: 
15524: =item 
15525: con_lost (connection to remote server failed).
15526: 
15527: =item 
15528: refused (invalid $username:$domain received on lond side).
15529: 
15530: =item 
15531: no_such_dir (directory at specified path on lond side does not exist). 
15532: 
15533: =item 
15534: empty (directory at specified path on lond side is empty).
15535: 
15536: =over
15537: 
15538: This is currently not encountered because the &ls3, &ls2, 
15539: &ls (_handler) routines on the lond side do not filter out
15540: . and .. from a directory listing. 
15541: 
15542: =back
15543: 
15544: =back
15545: 
15546: =back
15547: 
15548: =item *
15549: 
15550: spareserver() : find server with least workload from spare.tab
15551: 
15552: 
15553: =item *
15554: 
15555: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15556: if there is no corresponding loncapa host.
15557: 
15558: =back
15559: 
15560: 
15561: =head2 Apache Request
15562: 
15563: =over 4
15564: 
15565: =item *
15566: 
15567: ssi($url,%hash) : server side include, does a complete request cycle on url to
15568: localhost, posts hash
15569: 
15570: =back
15571: 
15572: =head2 Data to String to Data
15573: 
15574: =over 4
15575: 
15576: =item *
15577: 
15578: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15579: and '&' separators, supports elements that are arrayrefs and hashrefs
15580: 
15581: =item *
15582: 
15583: hashref2str($hashref) : convert a hashref into a string complete with
15584: escaping and '=' and '&' separators, supports elements that are
15585: arrayrefs and hashrefs
15586: 
15587: =item *
15588: 
15589: arrayref2str($arrayref) : convert an arrayref into a string complete
15590: with escaping and '&' separators, supports elements that are arrayrefs
15591: and hashrefs
15592: 
15593: =item *
15594: 
15595: str2hash($string) : convert string to hash using unescaping and
15596: splitting on '=' and '&', supports elements that are arrayrefs and
15597: hashrefs
15598: 
15599: =item *
15600: 
15601: str2array($string) : convert string to hash using unescaping and
15602: splitting on '&', supports elements that are arrayrefs and hashrefs
15603: 
15604: =back
15605: 
15606: =head2 Logging Routines
15607: 
15608: 
15609: These routines allow one to make log messages in the lonnet.log and
15610: lonnet.perm logfiles.
15611: 
15612: =over 4
15613: 
15614: =item *
15615: 
15616: logtouch() : make sure the logfile, lonnet.log, exists
15617: 
15618: =item *
15619: 
15620: logthis() : append message to the normal lonnet.log file, it gets
15621: preiodically rolled over and deleted.
15622: 
15623: =item *
15624: 
15625: logperm() : append a permanent message to lonnet.perm.log, this log
15626: file never gets deleted by any automated portion of the system, only
15627: messages of critical importance should go in here.
15628: 
15629: 
15630: =back
15631: 
15632: =head2 General File Helper Routines
15633: 
15634: =over 4
15635: 
15636: =item *
15637: 
15638: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15639: (a) files in /uploaded
15640:   (i) If a local copy of the file exists - 
15641:       compares modification date of local copy with last-modified date for 
15642:       definitive version stored on home server for course. If local copy is 
15643:       stale, requests a new version from the home server and stores it. 
15644:       If the original has been removed from the home server, then local copy 
15645:       is unlinked.
15646:   (ii) If local copy does not exist -
15647:       requests the file from the home server and stores it. 
15648:   
15649:   If $caller is 'uploadrep':  
15650:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15651:     for request for files originally uploaded via DOCS. 
15652:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15653:   
15654:   Otherwise:
15655:      This indicates a call from the content generation phase of the request.
15656:      -  returns the entire contents of the file or -1.
15657:      
15658: (b) files in /res
15659:    - returns the entire contents of a file or -1; 
15660:    it properly subscribes to and replicates the file if neccessary.
15661: 
15662: 
15663: =item *
15664: 
15665: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15666:                   reference
15667: 
15668: returns either a stat() list of data about the file or an empty list
15669: if the file doesn't exist or couldn't find out about it (connection
15670: problems or user unknown)
15671: 
15672: =item *
15673: 
15674: filelocation($dir,$file) : returns file system location of a file
15675: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15676: directory that relative $file lookups are to looked in ($dir of /a/dir
15677: and a file of ../bob will become /a/bob)
15678: 
15679: =item *
15680: 
15681: hreflocation($dir,$file) : returns file system location or a URL; same as
15682: filelocation except for hrefs
15683: 
15684: =item *
15685: 
15686: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15687: also removes beginning /home/httpd/html unless /priv/ follows it.
15688: 
15689: =back
15690: 
15691: =head2 Usererfile file routines (/uploaded*)
15692: 
15693: =over 4
15694: 
15695: =item *
15696: 
15697: userfileupload(): main rotine for putting a file in a user or course's
15698:                   filespace, arguments are,
15699: 
15700:  formname - required - this is the name of the element in $env where the
15701:            filename, and the contents of the file to create/modifed exist
15702:            the filename is in $env{'form.'.$formname.'.filename'} and the
15703:            contents of the file is located in $env{'form.'.$formname}
15704:  context - if coursedoc, store the file in the course of the active role
15705:              of the current user; 
15706:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15707:            if 'canceloverwrite': delete file in tmp/overwrites directory
15708:  subdir - required - subdirectory to put the file in under ../userfiles/
15709:          if undefined, it will be placed in "unknown"
15710: 
15711:  (This routine calls clean_filename() to remove any dangerous
15712:  characters from the filename, and then calls finuserfileupload() to
15713:  complete the transaction)
15714: 
15715:  returns either the url of the uploaded file (/uploaded/....) if successful
15716:  and /adm/notfound.html if unsuccessful
15717: 
15718: =item *
15719: 
15720: clean_filename(): routine for cleaing a filename up for storage in
15721:                  userfile space, argument is:
15722: 
15723:  filename - proposed filename
15724: 
15725: returns: the new clean filename
15726: 
15727: =item *
15728: 
15729: finishuserfileupload(): routine that creates and sends the file to
15730: userspace, probably shouldn't be called directly
15731: 
15732:   docuname: username or courseid of destination for the file
15733:   docudom: domain of user/course of destination for the file
15734:   formname: same as for userfileupload()
15735:   fname: filename (including subdirectories) for the file
15736:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15737:   allfiles: reference to hash used to store objects found by parser
15738:   codebase: reference to hash used for codebases of java objects found by parser
15739:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15740:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15741:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15742:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15743:   context: if 'overwrite', will move the uploaded file from its temporary location to
15744:             userfiles to facilitate overwriting a previously uploaded file with same name.
15745:   mimetype: reference to scalar to accommodate mime type determined
15746:             from File::MMagic if $parser = parse.
15747: 
15748:  returns either the url of the uploaded file (/uploaded/....) if successful
15749:  and /adm/notfound.html if unsuccessful (or an error message if context 
15750:  was 'overwrite').
15751:  
15752: 
15753: =item *
15754: 
15755: renameuserfile(): renames an existing userfile to a new name
15756: 
15757:   Args:
15758:    docuname: username or courseid of destination for the file
15759:    docudom: domain of user/course of destination for the file
15760:    old: current file name (including any subdirs under userfiles)
15761:    new: desired file name (including any subdirs under userfiles)
15762: 
15763: =item *
15764: 
15765: mkdiruserfile(): creates a directory is a userfiles dir
15766: 
15767:   Args:
15768:    docuname: username or courseid of destination for the file
15769:    docudom: domain of user/course of destination for the file
15770:    dir: dir to create (including any subdirs under userfiles)
15771: 
15772: =item *
15773: 
15774: removeuserfile(): removes a file that exists in userfiles
15775: 
15776:   Args:
15777:    docuname: username or courseid of destination for the file
15778:    docudom: domain of user/course of destination for the file
15779:    fname: filname to delete (including any subdirs under userfiles)
15780: 
15781: =item *
15782: 
15783: removeuploadedurl(): convience function for removeuserfile()
15784: 
15785:   Args:
15786:    url:  a full /uploaded/... url to delete
15787: 
15788: =item * 
15789: 
15790: get_portfile_permissions():
15791:   Args:
15792:     domain: domain of user or course contain the portfolio files
15793:     user: name of user or num of course contain the portfolio files
15794:   Returns:
15795:     hashref of a dump of the proper file_permissions.db
15796:    
15797: 
15798: =item * 
15799: 
15800: get_access_controls():
15801: 
15802: Args:
15803:   current_permissions: the hash ref returned from get_portfile_permissions()
15804:   group: (optional) the group you want the files associated with
15805:   file: (optional) the file you want access info on
15806: 
15807: Returns:
15808:     a hash (keys are file names) of hashes containing
15809:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15810:         values are XML containing access control settings (see below) 
15811: 
15812: Internal notes:
15813: 
15814:  access controls are stored in file_permissions.db as key=value pairs.
15815:     key -> path to file/file_name\0uniqueID:scope_end_start
15816:         where scope -> public,guest,course,group,domains or users.
15817:               end -> UNIX time for end of access (0 -> no end date)
15818:               start -> UNIX time for start of access
15819: 
15820:     value -> XML description of access control
15821:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15822:             <start></start>
15823:             <end></end>
15824: 
15825:             <password></password>  for scope type = guest
15826: 
15827:             <domain></domain>     for scope type = course or group
15828:             <number></number>
15829:             <roles id="">
15830:              <role></role>
15831:              <access></access>
15832:              <section></section>
15833:              <group></group>
15834:             </roles>
15835: 
15836:             <dom></dom>         for scope type = domains
15837: 
15838:             <users>             for scope type = users
15839:              <user>
15840:               <uname></uname>
15841:               <udom></udom>
15842:              </user>
15843:             </users>
15844:            </scope> 
15845:               
15846:  Access data is also aggregated for each file in an additional key=value pair:
15847:  key -> path to file/file_name\0accesscontrol 
15848:  value -> reference to hash
15849:           hash contains key = value pairs
15850:           where key = uniqueID:scope_end_start
15851:                 value = UNIX time record was last updated
15852: 
15853:           Used to improve speed of look-ups of access controls for each file.  
15854:  
15855:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15856: 
15857: =item *
15858: 
15859: modify_access_controls():
15860: 
15861: Modifies access controls for a portfolio file
15862: Args
15863: 1. file name
15864: 2. reference to hash of required changes,
15865: 3. domain
15866: 4. username
15867:   where domain,username are the domain of the portfolio owner 
15868:   (either a user or a course) 
15869: 
15870: Returns:
15871: 1. result of additions or updates ('ok' or 'error', with error message). 
15872: 2. result of deletions ('ok' or 'error', with error message).
15873: 3. reference to hash of any new or updated access controls.
15874: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15875:    key = integer (inbound ID)
15876:    value = uniqueID
15877: 
15878: =item *
15879: 
15880: get_timebased_id():
15881: 
15882: Attempts to get a unique timestamp-based suffix for use with items added to a 
15883: course via the Course Editor (e.g., folders, composite pages, 
15884: group bulletin boards).
15885: 
15886: Args: (first three required; six others optional)
15887: 
15888: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15889:    docssequence, or name of group
15890: 
15891: 2. keyid (alphanumeric): name of temporary locking key in hash,
15892:    e.g., num, boardids
15893: 
15894: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15895:    file will be named nohist_namespace.db
15896: 
15897: 4. cdom: domain of course; default is current course domain from %env
15898: 
15899: 5. cnum: course number; default is current course number from %env
15900: 
15901: 6. idtype: set to concat if an additional digit is to be appended to the 
15902:    unix timestamp to form the suffix, if the plain timestamp is already
15903:    in use.  Default is to not do this, but simply increment the unix 
15904:    timestamp by 1 until a unique key is obtained.
15905: 
15906: 7. who: holder of locking key; defaults to user:domain for user.
15907: 
15908: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15909:    retrying); default is 3.
15910: 
15911: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15912: 
15913: Returns:
15914: 
15915: 1. suffix obtained (numeric)
15916: 
15917: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15918: 
15919: 3. error: contains (localized) error message if an error occurred.
15920: 
15921: 
15922: =back
15923: 
15924: =head2 HTTP Helper Routines
15925: 
15926: =over 4
15927: 
15928: =item *
15929: 
15930: escape() : unpack non-word characters into CGI-compatible hex codes
15931: 
15932: =item *
15933: 
15934: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15935: 
15936: =back
15937: 
15938: =head1 PRIVATE SUBROUTINES
15939: 
15940: =head2 Underlying communication routines (Shouldn't call)
15941: 
15942: =over 4
15943: 
15944: =item *
15945: 
15946: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15947: 
15948: =item *
15949: 
15950: reply() : uses subreply to send a message to remote machine, logs all failures
15951: 
15952: =item *
15953: 
15954: critical() : passes a critical message to another server; if cannot
15955: get through then place message in connection buffer directory and
15956: returns con_delayed, if incapable of saving message, returns
15957: con_failed
15958: 
15959: =item *
15960: 
15961: reconlonc() : tries to reconnect lonc client processes.
15962: 
15963: =back
15964: 
15965: =head2 Resource Access Logging
15966: 
15967: =over 4
15968: 
15969: =item *
15970: 
15971: flushcourselogs() : flush (save) buffer logs and access logs
15972: 
15973: =item *
15974: 
15975: courselog($what) : save message for course in hash
15976: 
15977: =item *
15978: 
15979: courseacclog($what) : save message for course using &courselog().  Perform
15980: special processing for specific resource types (problems, exams, quizzes, etc).
15981: 
15982: =item *
15983: 
15984: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15985: as a PerlChildExitHandler
15986: 
15987: =back
15988: 
15989: =head2 Other
15990: 
15991: =over 4
15992: 
15993: =item *
15994: 
15995: symblist($mapname,%newhash) : update symbolic storage links
15996: 
15997: =back
15998: 
15999: =cut
16000: 

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